Compare commits

...
Author SHA1 Message Date
lemonknowsall 316ddf284d lazy chat loading 2026-01-12 22:18:45 -08:00
lemonknowsall 5fc96c9007 dim old conversation on new chat initiation and remove sessionId underscore convention 2026-01-11 12:10:11 -08:00
lemonknowsall 9352b70df8 remove unnecessary timestamp function 2026-01-11 11:47:49 -08:00
lemonknowsall b4cfc1a5ee improve scroll behavior 2026-01-11 01:26:34 -08:00
lemonknowsall a07368b190 remove redundant tracking, add session ids 2026-01-11 01:14:36 -08:00
lemonknowsall 66bfb56694 update languages for New Chat divider 2026-01-11 00:39:00 -08:00
lemonknowsall 3cb7a8f673 feat: maintain continuous chat history after new chat start 2026-01-11 00:26:17 -08: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
132 changed files with 11072 additions and 9521 deletions

No files matched your search

+4 -14
View File
@@ -33,7 +33,7 @@ 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
@@ -53,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:**
@@ -62,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:
@@ -89,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
@@ -218,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
@@ -1299,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"]
}
}
}
+3 -623
View File
File diff suppressed because it is too large. Load diff
+1 -4
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",
@@ -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/');
+9 -6
View File
@@ -24,8 +24,13 @@ export default {
return new Response('Invalid url parameter', { status: 400 });
}
let hostname = url.hostname;
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
// GitHub hack: neutral color for light/dark mode
if (url.hostname === 'github.com') {
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' },
@@ -33,18 +38,16 @@ export default {
}
// 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 === '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 === 'api.z.ai') {
} else if (url.host === 'z.ai') {
hostname = 'docs.z.ai';
}
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
+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,PUT,PATCH,DELETE,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,PUT,PATCH,DELETE,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;
}
+23 -77
View File
@@ -21,8 +21,8 @@ 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';
@@ -47,55 +47,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: {
@@ -124,34 +75,27 @@ const defaultConfig: AppConfig = {
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
url: "https://gitlab.com/lemonknowsall/nutstack.git",
},
{
name: "Luvstack",
description: "Barebones React template. Choose this to build mockups or demo sites that don't require Nostr functionality. Only choose this if the user has indicated they want to create a demo or mockup site, as it cannot support any sort of backend functionality or remote storage. It might also work for simple PWAs.",
url: "https://gitlab.com/soapbox-pub/luvstack.git",
}
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
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",
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 initialization and cleanup on startup
// Ensures tmp directory exists and removes files older than 1 hour
@@ -201,17 +145,19 @@ export function App() {
<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>
+2
View File
@@ -18,6 +18,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";
@@ -39,6 +40,7 @@ export function AppRouter() {
<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 />} />
File diff suppressed because it is too large. Load diff
+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,10 +2,10 @@ 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',
@@ -18,7 +18,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -26,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', () => {
@@ -36,7 +36,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -55,7 +55,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -74,7 +74,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -100,7 +100,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={openrouterProvider}
@@ -112,7 +112,7 @@ 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',
@@ -122,7 +122,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={customProvider}
@@ -130,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();
});
});
@@ -8,13 +8,13 @@ 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);
@@ -32,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);
@@ -69,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">
@@ -164,9 +163,9 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
/>
</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>
@@ -183,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"
+1 -21
View File
@@ -45,6 +45,7 @@ const AppConfigSchema = z.object({
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),
@@ -89,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,
@@ -163,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>
</>
);
}
+4 -3
View File
@@ -30,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', () => {
@@ -45,7 +46,7 @@ describe('CreditsBadge', () => {
</TestApp>
);
const badge = screen.getByText('$10.50');
const badge = screen.getByText('$11');
fireEvent.click(badge);
expect(mockCallback).toHaveBeenCalled();
@@ -58,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 (
+74 -26
View File
@@ -1,9 +1,18 @@
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();
@@ -15,30 +24,42 @@ const mockProvider: AIProvider = {
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>
);
@@ -46,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>
);
@@ -96,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();
});
});
});
+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>
);
}
+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>
);
}
+8 -4
View File
@@ -1,12 +1,11 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl } from '@/lib/faviconUrl';
import { normalizeUrl } from '@/lib/url';
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 */
@@ -29,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;
}
@@ -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>
);
}
+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>
);
}
+32 -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,7 +26,7 @@ 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',
@@ -40,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 () => {
@@ -61,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();
});
});
});
+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>
);
}
+20 -27
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';
@@ -465,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>
)}
@@ -726,7 +717,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
{/* Credits Dialog */}
{showCreditsDialog && selectedModel && selectedProvider && (
<CreditsDialog
<AIProviderConfigDialog
open={showCreditsDialog}
onOpenChange={(open) => {
if (!open) {
@@ -739,6 +730,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
onUpdate={() => {}}
onRemove={() => {}}
/>
)}
</>
+142 -1
View File
@@ -23,20 +23,28 @@ import {
DollarSign,
ExternalLink,
FileCode,
Download,
Trash2,
} from 'lucide-react';
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;
open: boolean;
onOpenChange: (open: boolean) => void;
onProjectDeleted?: () => void;
}
export function ProjectDetailsDialog({ project, open, onOpenChange }: 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 [newProjectName, setNewProjectName] = useState(project.id);
const [totalCost, setTotalCost] = useState<number | null>(null);
const [isLoading, setIsLoading] = useState(false);
@@ -129,6 +137,105 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
}
};
const handleDeleteProject = async () => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(project.id);
// Invalidate the projects query to update the sidebar
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: "Project deleted",
description: `"${project.name}" has been permanently deleted.`,
});
// Close the dialog first
onOpenChange(false);
// Navigate back to home and notify parent
navigate('/');
if (onProjectDeleted) {
onProjectDeleted();
}
} catch (error) {
toast({
title: "Failed to delete project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsDeleting(false);
}
};
const handleExportProject = async () => {
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `${projectsPath}/${project.id}`;
// Recursive function to add files and directories to zip from a specific project
const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addFolderToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from the project directory
await addFolderToZip(projectPath, zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
link.download = `${project.id}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast({
title: "Project exported successfully",
description: `"${project.name}" has been downloaded as a zip file.`,
});
} catch (error) {
console.error('Failed to export project:', error);
toast({
title: "Failed to export project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
@@ -223,6 +330,40 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
{/* Labels */}
<LabelSelector projectId={project.id} />
<Separator />
{/* Export Project Button */}
<Button
onClick={handleExportProject}
disabled={isExporting || isDeleting || isRenaming}
className="w-full gap-2"
variant="outline"
>
{isExporting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Download className="h-4 w-4" />
)}
{isExporting ? 'Exporting...' : 'Export Project'}
</Button>
{/* Delete Project Button */}
<DeleteProjectDialog
projectName={project.name}
onDelete={handleDeleteProject}
isDeleting={isDeleting}
trigger={
<Button
variant="destructive"
className="w-full gap-2"
disabled={isExporting || isDeleting || isRenaming}
>
<Trash2 className="h-4 w-4" />
Delete Project
</Button>
}
/>
</div>
</DialogContent>
</Dialog>
+1 -20
View File
@@ -12,13 +12,11 @@ import {
Folder,
Copy,
ChevronDown,
Download,
Trash2,
Star,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
interface ProjectTitleMenuProps {
@@ -27,7 +25,6 @@ interface ProjectTitleMenuProps {
onNewChat: () => void;
onGitHistory: () => void;
onDuplicate: () => void;
onExport: () => void;
onDelete: () => void;
onProjectDetails: () => void;
isAILoading: boolean;
@@ -41,7 +38,6 @@ export function ProjectTitleMenu({
onNewChat,
onGitHistory,
onDuplicate,
onExport,
onDelete,
onProjectDetails,
isAILoading,
@@ -50,7 +46,6 @@ export function ProjectTitleMenu({
}: ProjectTitleMenuProps) {
const { t } = useTranslation();
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const { toast } = useToast();
const queryClient = useQueryClient();
const isFavorite = favorites.includes(projectId);
@@ -67,11 +62,6 @@ export function ProjectTitleMenu({
// Invalidate the projects query to trigger a refetch with new sorting
queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: isFavorite ? "Project Unfavorited" : "Project Favorited",
description: `"${projectName}" has been ${isFavorite ? 'removed from' : 'added to'} your favorites.`,
});
};
return (
@@ -125,7 +115,7 @@ export function ProjectTitleMenu({
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
{t('newChat')}
</DropdownMenuItem>
<DropdownMenuItem
@@ -137,15 +127,6 @@ export function ProjectTitleMenu({
{t('duplicateProject')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={onExport}
disabled={isAnyLoading}
className="gap-2"
>
<Download className="h-4 w-4" />
Export Project
</DropdownMenuItem>
<DropdownMenuItem
onClick={onDelete}
disabled={isAnyLoading}
+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', () => {
+4 -2
View File
@@ -6,7 +6,7 @@ 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';
@@ -279,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>
+54 -6
View File
@@ -2,7 +2,13 @@ import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch, Loader2 } from 'lucide-react';
import { GitBranch, Loader2, EllipsisVertical, Edit } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
@@ -15,6 +21,8 @@ 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';
interface RepositoryCardProps {
repo: Repository;
@@ -28,13 +36,20 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
const projectsManager = useProjectsManager();
const { toast } = useToast();
const { t } = useTranslation();
const queryClient = useQueryClient();
const [isCloning, setIsCloning] = useState(false);
const [editRepoOpen, setEditRepoOpen] = useState(false);
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
const isOwnRepo = user?.pubkey === repo.pubkey;
// Construct Nostr clone URL
const nostrURI = new NostrURI({ pubkey: repo.pubkey, identifier: repo.repoId });
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
@@ -89,14 +104,40 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
}
};
const handleRepoEditSuccess = () => {
// Refresh repositories list after successful edit
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
};
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and author */}
{/* Header with name and menu */}
<div className="mb-4 flex items-start justify-between">
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
</div>
{isOwnRepo && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8 -mt-1 -mr-2 shrink-0">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
{/* Author */}
<div className="mb-4">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
{profileImage && (
@@ -164,6 +205,13 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
</Button>
</div>
</CardContent>
<NostrRepoEditDialog
open={editRepoOpen}
onOpenChange={setEditRepoOpen}
repoIdentifier={repo.repoId}
onSuccess={handleRepoEditSuccess}
/>
</Card>
);
}
+4
View File
@@ -34,6 +34,7 @@ describe('SentryProvider', () => {
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',
@@ -75,6 +76,7 @@ describe('SentryProvider', () => {
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',
@@ -117,6 +119,7 @@ describe('SentryProvider', () => {
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',
@@ -162,6 +165,7 @@ describe('SentryProvider', () => {
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',
+16
View File
@@ -0,0 +1,16 @@
import { useTranslation } from 'react-i18next';
/** Visual divider between chat sessions */
export function SessionDivider() {
const { t } = useTranslation();
return (
<div className="flex items-center gap-3 text-xs text-muted-foreground py-4">
<div className="flex-1 h-px bg-border" />
<span className="uppercase tracking-wide">
{t('newChat', 'New chat')}
</span>
<div className="flex-1 h-px bg-border" />
</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>
);
}
+3 -3
View File
@@ -115,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={isLoadingSettings || isLoading || (isConfigured && !providerModel.trim())}
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
@@ -136,7 +136,7 @@ export const ChatInput = memo(function ChatInput({
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoadingSettings || isLoading}
disabled={isLoadingSettings}
multiple={true}
/>
@@ -185,7 +185,7 @@ export const ChatInput = memo(function ChatInput({
<ModelSelector
value={providerModel}
onChange={onProviderModelChange}
disabled={isLoadingSettings || isLoading}
disabled={isLoadingSettings}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={onModelSelectorOpenChange}
+158 -22
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 { ChevronDown } from 'lucide-react';
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
@@ -15,6 +15,7 @@ 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';
@@ -46,11 +47,12 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { SessionDivider } from '@/components/SessionDivider';
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';
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
// Clean interfaces now handled by proper hooks
@@ -87,6 +89,7 @@ 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>());
@@ -159,13 +162,19 @@ 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 }),
@@ -234,7 +243,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, 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]);
@@ -286,15 +295,22 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const {
messages,
displayMessages,
sessionName,
streamingMessage,
isLoading: internalIsLoading,
isLoadingHistory,
hasMoreHistory,
isLoadingMoreHistory,
totalCost,
lastInputTokens,
lastFinishReason,
addMessage,
sendMessage,
startGeneration,
stopGeneration,
startNewSession: internalStartNewSession,
loadMoreHistory,
} = useAIChat({
projectId,
tools,
@@ -308,7 +324,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const checkTemplateInfo = async () => {
try {
// Only check if we have at least 1 message
if (messages.length === 0) {
if (displayMessages.length === 0) {
setShowTemplateInfo(false);
return;
}
@@ -347,7 +363,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
checkTemplateInfo();
}, [fs, projectsPath, projectId, messages.length]);
}, [fs, projectsPath, projectId, displayMessages.length]);
// Handle console error help requests
const handleConsoleErrorHelp = useCallback(async () => {
@@ -426,7 +442,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Function to scroll to bottom
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
});
}
}, []);
@@ -479,17 +499,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const lastMessage = messages[messages.length - 1];
const isUserMessage = lastMessage?.role === 'user';
// Check if user was already near the bottom (within 100px threshold)
const threshold = 100;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
// Scroll to bottom if user sent a message or was already near the bottom
if (isUserMessage || isNearBottom) {
scrollToBottom();
}
}
}, [messages, streamingMessage, isLoading]);
}, [messages, streamingMessage, isLoading, scrollToBottom]);
// Scroll to bottom when first visiting a project (including page refresh)
useEffect(() => {
@@ -567,8 +590,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// Scroll to bottom when user sends a message
scrollToBottom();
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, scrollToBottom]);
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
@@ -701,8 +727,53 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</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 && displayMessages.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">
@@ -726,13 +797,49 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
{messages.map((message, index) => {
{/* Load older messages button */}
{!isLoadingHistory && hasMoreHistory && (
<div className="flex justify-center py-3">
<Button
variant="ghost"
size="sm"
onClick={async () => {
const container = scrollAreaRef.current;
const oldScrollHeight = container?.scrollHeight || 0;
await loadMoreHistory();
// Preserve scroll position after prepending content
if (container) {
requestAnimationFrame(() => {
container.scrollTop += container.scrollHeight - oldScrollHeight;
});
}
}}
disabled={isLoadingMoreHistory}
className="gap-2 text-muted-foreground"
>
<ChevronUp className="h-4 w-4" />
{isLoadingMoreHistory ? t('loading') : t('loadOlderMessages', 'Load older messages')}
</Button>
</div>
)}
{!isLoadingHistory && displayMessages.map((message, index) => {
// Get the current message's session ID and compare to previous
const currentSessionId = (message as DisplayMessage).sessionId;
const prevSessionId = index > 0 ? (displayMessages[index - 1] as DisplayMessage).sessionId : undefined;
// Show divider when session changes (not on first message)
const showDivider = index > 0 && currentSessionId !== prevSessionId;
// Dim messages from older sessions (compare against current active session)
const isOlderSession = currentSessionId !== sessionName;
// Find the corresponding tool call for tool messages
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
if (message.role === 'tool') {
// Look backwards to find the assistant message with matching tool call
for (let i = index - 1; i >= 0; i--) {
const prevMessage = messages[i];
const prevMessage = displayMessages[i];
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
if (toolCall) break;
@@ -741,15 +848,44 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return (
<AIMessageItem
<div
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
message={message}
toolCall={toolCall}
/>
className={isOlderSession ? 'opacity-65' : ''}
>
{showDivider && <SessionDivider />}
<AIMessageItem
message={message}
toolCall={toolCall}
/>
</div>
);
})}
{renderStreamingMessage()}
{/* Trailing session divider - shown when New Chat is clicked before sending a message */}
{!isLoadingHistory && displayMessages.length > 0 && (() => {
const lastSessionId = (displayMessages[displayMessages.length - 1] as DisplayMessage).sessionId;
return sessionName && lastSessionId && sessionName !== lastSessionId ? (
<SessionDivider key="trailing-divider" />
) : null;
})()}
{!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>
)}
{/* Error Alert (Console or AI) - Don't show while assistant is loading */}
{displayError && !isLoading && (
+31 -30
View File
@@ -13,6 +13,7 @@ import { Button } from '@/components/ui/button';
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 { type DeviceMode } from '@/components/ui/device-toggle';
import {
@@ -526,6 +527,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
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" />
)}
@@ -618,7 +620,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
size="sm"
onClick={toggleFullscreen}
className="h-8 w-8 p-0"
title={isFullscreen ? 'Exit immersive view' : 'Enter immersive view'}
title={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
>
{isFullscreen ? (
<Shrink className="h-4 w-4" />
@@ -661,6 +663,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
) : (
<Hammer className="h-4 w-4" />
)}
<span className="hidden lg:inline">Build</span>
</Button>
{(!isMobile && onToggleView && isPreviewable) && (
<Button
@@ -670,6 +673,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
<span className="hidden lg:inline">Code</span>
</Button>
)}
<ConsoleDropdown />
@@ -727,8 +731,24 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
<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">
@@ -739,35 +759,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
/>
</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">
@@ -819,7 +815,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
<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"
@@ -830,6 +826,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
{t('backToPreview')}
</Button>
<div className="flex-1" />
<BranchSwitcher projectId={projectId} />
<Button
variant="ghost"
size="sm"
@@ -837,13 +834,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
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"
@@ -851,6 +851,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
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>
+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.content && result.content.trim()) {
addLine('output', result.content);
}
// 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"
>
+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">
+2 -2
View File
@@ -1,6 +1,6 @@
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';
@@ -78,7 +78,7 @@ export function URLFragmentHandler() {
}
return (
<AddProviderDialog
<AddSharedProviderDialog
open={dialogOpen}
onOpenChange={handleDialogClose}
provider={providerFromURL}
+22 -7
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
@@ -11,6 +11,7 @@ import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import { useGitStatus } from '@/hooks/useGitStatus';
import { formatRelativeTime } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
interface GitCommit {
oid: string;
@@ -40,6 +41,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [internalOpen, setInternalOpen] = useState(false);
const gitCache = useRef<object>({});
const queryClient = useQueryClient();
// Use controlled or internal state
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
@@ -72,6 +75,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const gitLog = await git.log({
dir: projectPath,
depth: 50, // Limit to last 50 commits
cache: gitCache.current,
});
setCommits(gitLog);
@@ -86,11 +90,10 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
if (!fs) return;
const projectPath = `${projectsPath}/${projectId}`;
setIsRollingBack(targetCommit.oid);
try {
const projectPath = `${projectsPath}/${projectId}`;
// Get the current HEAD commit
const currentCommit = await git.resolveRef({
dir: projectPath,
@@ -110,6 +113,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const allCommits = await git.log({
dir: projectPath,
depth: 1000,
cache: gitCache.current,
});
// Find the index of target commit and current HEAD
@@ -142,12 +146,14 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const targetFiles = await git.listFiles({
dir: projectPath,
ref: targetCommit.oid,
cache: gitCache.current,
});
// Get current files to know what to remove
const currentFiles = await git.listFiles({
dir: projectPath,
ref: 'HEAD',
cache: gitCache.current,
});
// Remove files that don't exist in target commit
@@ -158,6 +164,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
await git.remove({
dir: projectPath,
filepath,
cache: gitCache.current,
});
} catch (err) {
// File might not exist, continue
@@ -173,6 +180,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
dir: projectPath,
oid: targetCommit.oid,
filepath,
cache: gitCache.current,
});
// Ensure directory exists
@@ -188,6 +196,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
await git.add({
dir: projectPath,
filepath,
cache: gitCache.current,
});
} catch (err) {
console.error(`Failed to restore ${filepath}:`, err);
@@ -209,6 +218,7 @@ ${commitsToRevert.map(c => {
await git.commit({
dir: projectPath,
message: revertMessage,
cache: gitCache.current,
});
toast({
@@ -228,18 +238,18 @@ ${commitsToRevert.map(c => {
variant: "destructive",
});
} finally {
queryClient.invalidateQueries({ queryKey: ['git-sync', projectPath] })
setIsRollingBack(null);
}
}, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]);
}, [fs, projectsPath, projectId, git, toast, setIsOpen, navigate, queryClient]);
const resetToHead = useCallback(async () => {
if (!fs) return;
const projectPath = `${projectsPath}/${projectId}`;
setIsRollingBack('HEAD');
try {
const projectPath = `${projectsPath}/${projectId}`;
// Get the current HEAD commit
const headCommit = await git.resolveRef({
dir: projectPath,
@@ -250,11 +260,13 @@ ${commitsToRevert.map(c => {
const headFiles = await git.listFiles({
dir: projectPath,
ref: 'HEAD',
cache: gitCache.current,
});
// Get current files in working directory
const currentFiles = await git.listFiles({
dir: projectPath,
cache: gitCache.current,
});
// Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files)
@@ -275,6 +287,7 @@ ${commitsToRevert.map(c => {
dir: projectPath,
oid: headCommit,
filepath,
cache: gitCache.current,
});
// Ensure directory exists
@@ -294,6 +307,7 @@ ${commitsToRevert.map(c => {
// Get git status to find untracked files
const status = await git.statusMatrix({
dir: projectPath,
cache: gitCache.current,
});
const untrackedFiles = status
@@ -327,9 +341,10 @@ ${commitsToRevert.map(c => {
variant: "destructive",
});
} finally {
queryClient.invalidateQueries({ queryKey: ['git-sync', projectPath] })
setIsRollingBack(null);
}
}, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]);
}, [fs, projectsPath, projectId, git, toast, setIsOpen, navigate, queryClient]);
useEffect(() => {
if (isOpen) {
@@ -5,14 +5,14 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { cn } from '@/lib/utils';
import { DeploySteps } from './DeploySteps';
interface DeployPopoverProps {
interface DeployButtonProps {
projectId: string;
projectName: string;
className?: string;
disabled?: boolean;
}
export function DeployPopover({ projectId, projectName, className, disabled }: DeployPopoverProps) {
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
const [open, setOpen] = useState(false);
return (
@@ -21,11 +21,11 @@ export function DeployPopover({ projectId, projectName, className, disabled }: D
<Button
variant="ghost"
size="sm"
className={cn("h-8 w-8 p-0", className)}
className={cn("size-8 p-0 group", className)}
aria-label="Deploy project"
disabled={disabled}
>
<Rocket className="size-5 text-muted-foreground" />
<Rocket className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
</Button>
</PopoverTrigger>
<PopoverContent
@@ -33,10 +33,10 @@ export function DeployPopover({ projectId, projectName, className, disabled }: D
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<DeploySteps
projectId={projectId}
<DeploySteps
projectId={projectId}
projectName={projectName}
onClose={() => setOpen(false)}
onClose={() => setOpen(false)}
/>
</PopoverContent>
</Popover>
+54 -68
View File
@@ -13,9 +13,10 @@ 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, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } from '@/contexts/DeploySettingsContext';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
@@ -23,55 +24,37 @@ import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
import { NsiteAdapter } from '@/lib/deploy/NsiteAdapter';
import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
/**
* Helper function to get provider URL for favicon
* Normalize a URL string to ensure it has a protocol
*/
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 'cloudflare':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://cloudflare.com';
case 'deno':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://deno.com';
case 'nsite':
return null;
default:
return null;
function normalizeUrl(url: string): string {
if (/^https?:\/\//i.test(url)) {
return url;
}
return `https://${url}`;
}
/**
* Render provider icon using favicon or fallback
*/
function renderProviderIcon(provider: DeployProvider, size = 14) {
const url = getProviderUrl(provider);
function renderProviderIcon(provider: DeployProvider, preset: PresetDeployProvider | undefined, size = 14) {
// Use baseURL from configured provider, falling back to preset baseURL
const baseURL = ('baseURL' in provider && provider.baseURL) || preset?.baseURL;
// For Shakespeare, special handling for host field
const shakespeareUrl = provider.type === 'shakespeare' && 'host' in provider && provider.host
? normalizeUrl(provider.host)
: undefined;
const url = shakespeareUrl || baseURL;
if (url) {
return (
@@ -189,7 +172,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
const shakespeareProvider = selectedProvider;
adapter = new ShakespeareAdapter({
fs,
signer: user.signer,
@@ -198,7 +181,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
const nsiteProvider = selectedProvider;
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
@@ -213,7 +196,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
blossomServers: nsiteProvider.blossomServers,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider as NetlifyProvider;
const netlifyProvider = selectedProvider;
if (!netlifyProvider.apiKey) {
throw new Error('Netlify API key is required');
}
@@ -229,7 +212,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'vercel') {
const vercelProvider = selectedProvider as VercelProvider;
const vercelProvider = selectedProvider;
if (!vercelProvider.apiKey) {
throw new Error('Vercel API key is required');
}
@@ -243,7 +226,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
const cloudflareProvider = selectedProvider;
if (!cloudflareProvider.apiKey) {
throw new Error('Cloudflare API key is required');
}
@@ -261,7 +244,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider as DenoDeployProvider;
const denoProvider = selectedProvider;
if (!denoProvider.apiKey) {
throw new Error('Deno Deploy access token is required');
}
@@ -393,7 +376,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
const shakespeareProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedSubdomain = savedConfig?.type === 'shakespeare' ? savedConfig.data.subdomain : undefined;
@@ -455,7 +438,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
}
if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
const cloudflareProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined;
@@ -475,7 +458,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
}
if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider as DenoDeployProvider;
const denoProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined;
@@ -583,23 +566,26 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<div className="space-y-2">
<Label>Select Provider</Label>
<div className="flex flex-wrap gap-2">
{settings.providers.map((provider) => (
<button
key={provider.id}
type="button"
onClick={() => setSelectedProviderId(provider.id)}
className={cn(
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
"border-2 hover:scale-105 active:scale-95",
selectedProviderId === provider.id
? "bg-primary text-primary-foreground border-primary shadow-sm"
: "bg-background text-foreground border-border hover:border-primary/50"
)}
>
{renderProviderIcon(provider, 14)}
<span>{provider.name}</span>
</button>
))}
{settings.providers.map((provider) => {
const preset = PRESET_DEPLOY_PROVIDERS.find(p => p.type === provider.type);
return (
<button
key={provider.id}
type="button"
onClick={() => setSelectedProviderId(provider.id)}
className={cn(
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
"border-2 hover:scale-105 active:scale-95",
selectedProviderId === provider.id
? "bg-primary text-primary-foreground border-primary shadow-sm"
: "bg-background text-foreground border-border hover:border-primary/50"
)}
>
{renderProviderIcon(provider, preset, 14)}
<span>{provider.name}</span>
</button>
);
})}
</div>
</div>
-8
View File
@@ -1,8 +0,0 @@
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
export { NetlifyDeployForm } from './NetlifyDeployForm';
export { VercelDeployForm } from './VercelDeployForm';
export { NsiteDeployForm } from './NsiteDeployForm';
export { CloudflareDeployForm } from './CloudflareDeployForm';
export { DenoDeployForm } from './DenoDeployForm';
export { DeployPopover } from './DeployPopover';
export { DeploySteps } from './DeploySteps';
+177 -29
View File
@@ -1,8 +1,10 @@
import { useState } from 'react';
import { CloudUpload } from 'lucide-react';
import { useState, useEffect, useRef } from 'react';
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSyncState } from '@/hooks/useGitSyncState';
import { useFSPaths } from '@/hooks/useFSPaths';
import { cn } from '@/lib/utils';
import { GitSyncSteps } from './GitSyncSteps';
@@ -13,39 +15,185 @@ interface GitSyncButtonProps {
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [open, setOpen] = useState(false);
const [syncSuccess, setSyncSuccess] = useState(false);
const [showWarningPopover, setShowWarningPopover] = useState(false);
const warningDismissed = useRef(false);
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError, getState } = useGitSyncState();
const { projectsPath } = useFSPaths();
// Determine if we have a remote configured
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
const dir = `${projectsPath}/${projectId}`;
const hasError = !!getError(dir);
const gitSyncState = getState(dir);
const isGitActionOccurring = gitSyncState?.isActive ?? false;
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
const prevProjectId = useRef(projectId);
// Determine if we need to show the indicator dot
// Show indicator if no origin remote is configured, UNLESS there are less than 2 commits
const showIndicator = !isGitStatusLoading && !hasRemote && (gitStatus?.totalCommits ?? 0) >= 2;
// Reset state when projectId changes
useEffect(() => {
if (prevProjectId.current !== projectId) {
setSyncSuccess(false);
setShowWarningPopover(false);
warningDismissed.current = false;
prevIsGitActionOccurring.current = isGitActionOccurring;
prevProjectId.current = projectId;
}
}, [projectId, isGitActionOccurring]);
// Detect when a git action completes successfully
useEffect(() => {
// If we were syncing and now we're not, and there's no error, show success
if (prevIsGitActionOccurring.current && !isGitActionOccurring && !hasError) {
setSyncSuccess(true);
const timer = setTimeout(() => setSyncSuccess(false), 2500);
return () => clearTimeout(timer);
}
prevIsGitActionOccurring.current = isGitActionOccurring;
}, [isGitActionOccurring, hasError]);
// Check if we need to show the warning popover
const needsRemote = !isGitStatusLoading && gitStatus &&
!gitStatus.remotes.find(r => r.name === 'origin') &&
gitStatus.totalCommits > 1;
// Show warning popover when purple indicator is visible (only if not dismissed)
useEffect(() => {
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
setShowWarningPopover(true);
} else {
setShowWarningPopover(false);
}
}, [gitStatus?.totalCommits, needsRemote]);
// Handle button click - dismiss warning popover permanently
const handleButtonClick = () => {
if (showWarningPopover) {
warningDismissed.current = true;
setShowWarningPopover(false);
}
setOpen(true);
};
// Determine which indicator to show (only one at a time, in priority order)
const renderIndicator = () => {
// Checkmark: sync just completed successfully - highest priority
if (syncSuccess) {
return <IndicatorCheck />;
}
// Spinner: git action occurring - second priority
if (isGitActionOccurring) {
return <IndicatorSpinner />;
}
// Red indicator: error state - second priority
if (hasError) {
return <IndicatorDot color="red" />;
}
if (isGitStatusLoading || !gitStatus) return null;
const originRemote = gitStatus.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
const { remoteBranchExists, ahead, behind, totalCommits } = gitStatus;
// Yellow indicator: unsynced changes (ahead or behind remote) - third priority
const hasUnsyncedChanges = hasRemote && remoteBranchExists && (ahead > 0 || behind > 0);
if (hasUnsyncedChanges) {
return <IndicatorDot color="yellow" />;
}
// Purple indicator: no remote configured, but has commits - lowest priority
const needsRemote = !hasRemote && totalCommits > 1;
if (needsRemote) {
return <IndicatorDot color="primary" />;
}
return null;
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("h-8 w-8 p-0 relative", className)}
aria-label="Sync with Git"
<>
{/* Warning popover - shown when purple indicator is visible */}
<Popover open={showWarningPopover} modal={false}>
<PopoverTrigger asChild>
<div className="relative">
{/* Main Git Sync popover */}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
onClick={handleButtonClick}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
</div>
</PopoverTrigger>
<PopoverContent
side="bottom"
align="center"
className="w-80 pointer-events-none z-40"
onOpenAutoFocus={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
>
<CloudUpload className="size-5 text-muted-foreground" />
{showIndicator && (
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-primary" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
<div className="space-y-3 pointer-events-auto">
<div className="flex items-center gap-2">
<AlertTriangle className="size-5 text-primary shrink-0" />
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
</div>
<p className="text-sm text-muted-foreground">
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
</p>
<Button
onClick={handleButtonClick}
className="w-full"
size="sm"
>
Continue
</Button>
</div>
</PopoverContent>
</Popover>
</>
);
}
function IndicatorDot({ color }: { color: 'primary' | 'yellow' | 'red' }) {
return (
<span className={cn(
"absolute top-1 right-1 h-2 w-2 rounded-full",
{
'bg-primary': color === 'primary',
'bg-yellow-500': color === 'yellow',
'bg-red-500': color === 'red',
},
)} />
);
}
function IndicatorSpinner() {
return (
<Loader2 className="absolute top-1 right-1 size-2.5 animate-spin text-blue-600 dark:text-blue-400" />
);
}
function IndicatorCheck() {
return (
<Check className="absolute top-1 right-1 size-2.5 text-green-600 dark:text-green-400" />
);
}
+30 -19
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from 'react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { SelectProviderStep } from './steps/SelectProviderStep';
import { ConfigureRepoStep } from './steps/ConfigureRepoStep';
@@ -14,9 +14,19 @@ interface GitSyncStepsProps {
export function GitSyncSteps({ projectId, onClose }: GitSyncStepsProps) {
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
// Determine if we have a remote configured
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
const remoteUrl = useMemo(() => {
if (originRemote) {
try {
return new URL(originRemote.url);
} catch {
return;
}
}
}, [originRemote]);
const hasRemote = !!remoteUrl;
const [currentStep, setCurrentStep] = useState<StepType>(hasRemote ? 'sync' : 'select-provider');
const [selectedProvider, setSelectedProvider] = useState<ProviderOption | null>(null);
@@ -54,6 +64,16 @@ export function GitSyncSteps({ projectId, onClose }: GitSyncStepsProps) {
setCurrentStep('init-success');
};
if (currentStep === 'init-success') {
return (
<InitSuccessStep
projectId={projectId}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
// Don't render anything while loading git status
if (isGitStatusLoading) {
return (
@@ -63,18 +83,6 @@ export function GitSyncSteps({ projectId, onClose }: GitSyncStepsProps) {
);
}
// Render the appropriate step
if (currentStep === 'select-provider') {
return (
<SelectProviderStep
projectId={projectId}
onSelectProvider={handleSelectProvider}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
if (currentStep === 'configure-repo' && selectedProvider) {
return (
<ConfigureRepoStep
@@ -88,20 +96,23 @@ export function GitSyncSteps({ projectId, onClose }: GitSyncStepsProps) {
);
}
if (currentStep === 'sync') {
// Render the appropriate step
if (!remoteUrl || currentStep === 'select-provider') {
return (
<SyncStep
<SelectProviderStep
projectId={projectId}
onSelectProvider={handleSelectProvider}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
if (currentStep === 'init-success') {
if (currentStep === 'sync') {
return (
<InitSuccessStep
<SyncStep
projectId={projectId}
remoteUrl={remoteUrl}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -18,6 +18,16 @@ import { nip19 } from 'nostr-tools';
import type { ConfigureRepoStepProps } from '../types';
import type { NostrEvent } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
import { useGitAutosync } from '@/hooks/useGitAutosync';
import { ArrowUp } from 'lucide-react';
// 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 ConfigureRepoStep({
projectId,
@@ -27,25 +37,48 @@ export function ConfigureRepoStep({
onClose,
}: ConfigureRepoStepProps) {
const [repositoryUrl, setRepositoryUrl] = useState('');
const [repoIdentifier, setRepoIdentifier] = useState(projectId);
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
const [isPushing, setIsPushing] = useState(false);
const [error, setError] = useState<string | null>(null);
const { user } = useCurrentUser();
const { git } = useGit();
const { projectsPath } = useFSPaths();
const dir = `${projectsPath}/${projectId}`;
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
const { refetch: refetchAutosync } = useGitAutosync(dir);
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const { fs } = useFS();
const { config } = useAppContext();
// Auto-update repo name when repo identifier changes (unless manually edited)
useEffect(() => {
if (!isRepoNameManuallyEdited) {
setRepoName(kebabToTitleCase(repoIdentifier));
}
}, [repoIdentifier, isRepoNameManuallyEdited]);
// Handler for repo identifier changes
const handleRepoIdentifierChange = (value: string) => {
setRepoIdentifier(value);
};
// Handler for repo name changes
const handleRepoNameChange = (value: string) => {
setRepoName(value);
setIsRepoNameManuallyEdited(true);
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
try {
const dir = `${projectsPath}/${projectId}`;
if (selectedProvider.id === 'nostr') {
if (!user) {
throw new Error('User is not logged in');
@@ -53,7 +86,7 @@ export function ConfigureRepoStep({
// Check if a NIP-34 repo announcement already exists for this project
const existingRepos = await nostr.query(
[{ kinds: [30617], authors: [user.pubkey], '#d': [projectId], limit: 1 }],
[{ kinds: [30617], authors: [user.pubkey], '#d': [repoIdentifier], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
@@ -67,11 +100,20 @@ export function ConfigureRepoStep({
const relayUrl = new URL(graspRelay.url);
relays.add(relayUrl.href);
const cloneUrl = new URL(`/${npub}/${projectId}.git`, `https://${relayUrl.host}`);
const cloneUrl = new URL(`/${npub}/${repoIdentifier}.git`, `https://${relayUrl.host}`);
cloneUrls.add(cloneUrl.href);
} catch (err) {
console.warn(`Failed to parse Nostr git relay URL: ${graspRelay.url}`, err);
} catch {
// fallthrough
}
}
for (const relay of config.relayMetadata.relays.filter(r => r.write)) {
try {
const relayUrl = new URL(relay.url);
relays.add(relayUrl.href);
} catch {
// fallthrough
}
}
@@ -87,7 +129,6 @@ export function ConfigureRepoStep({
const existingEvent = existingRepos[0];
// Extract existing data from the event
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
const webUrls = webTag ? webTag.slice(1) : undefined;
@@ -99,12 +140,12 @@ export function ConfigureRepoStep({
// Create updated repository announcement event with new clone URLs and relays
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: projectId,
name,
repoId: repoIdentifier,
name: repoName,
description,
webUrls,
cloneUrls: [...cloneUrls],
relays: [...relays],
cloneUrls: [...cloneUrls].slice(0, 10), // Limit to first 10 clone URLs
relays: [...relays].slice(0, 10), // Limit to first 10 relays
tTags: tTags.length > 0 ? tTags : undefined,
earliestCommit,
});
@@ -127,8 +168,8 @@ export function ConfigureRepoStep({
// Create the repository announcement event
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: projectId,
name: projectId,
repoId: repoIdentifier,
name: repoName,
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags,
@@ -142,7 +183,11 @@ export function ConfigureRepoStep({
await new Promise(resolve => setTimeout(resolve, 5000));
// Construct Nostr URI
const nostrURI = new NostrURI({ pubkey: repoEvent.pubkey, identifier: projectId });
const nostrURI = new NostrURI({
pubkey: repoEvent.pubkey,
identifier: repoIdentifier,
relay: [...relays][0],
});
// Configure the Nostr URI as the origin
await git.addRemote({
@@ -180,7 +225,15 @@ export function ConfigureRepoStep({
});
}
// Enable autosync by default after successfully setting up the remote
await git.setConfig({
dir,
path: 'shakespeare.autosync',
value: 'true',
});
// Refresh git status before showing success
await refetchAutosync();
await refetchGitStatus();
// Show success state
onSuccess();
@@ -268,6 +321,27 @@ export function ConfigureRepoStep({
Push your code to Nostr with one click. Your repository will be stored on public Nostr git <Link className="underline" to="/settings/nostr">servers</Link>.
</p>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-2">
<Label htmlFor="repo-identifier">Repo Identifier <span className="text-destructive">*</span></Label>
<Input
id="repo-identifier"
placeholder="my-project"
value={repoIdentifier}
onChange={(e) => handleRepoIdentifierChange(e.target.value)}
/>
</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>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
@@ -280,14 +354,10 @@ export function ConfigureRepoStep({
disabled={isPushing}
className="flex-1"
>
{isPushing ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
Pushing...
</>
) : (
'Push'
)}
{isPushing
? <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
: <ArrowUp className="h-4 w-4" />}
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
</div>
@@ -0,0 +1,68 @@
import { AlertTriangle } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface ForcePullDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
remoteName: string;
}
export function ForcePullDialog({
open,
onOpenChange,
onConfirm,
remoteName,
}: ForcePullDialogProps) {
const handleConfirm = () => {
onOpenChange(false);
onConfirm();
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Force Pull - Discard Local Changes?
</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This will <strong className="text-destructive">completely reset your local repository</strong> to match the repository pushed to <strong>{remoteName}</strong>, permanently deleting all local commits and changes that don't exist on {remoteName}.
</p>
<div className="rounded-md bg-destructive/10 p-3 text-sm border border-destructive/20">
<p className="font-medium text-destructive mb-1">What will be deleted:</p>
<ul className="list-disc list-outside space-y-1 text-muted-foreground ml-5">
<li>All local commits that haven't been pushed to {remoteName}</li>
<li>Any work not available on {remoteName}</li>
<li>All uncommitted changes</li>
</ul>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
onClick={handleConfirm}
variant="destructive"
className="gap-2"
>
<AlertTriangle className="h-4 w-4" />
Force Pull
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,68 @@
import { AlertTriangle } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface ForcePushDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
remoteName: string;
}
export function ForcePushDialog({
open,
onOpenChange,
onConfirm,
remoteName,
}: ForcePushDialogProps) {
const handleConfirm = () => {
onOpenChange(false);
onConfirm();
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Force Push to {remoteName}?
</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This will <strong className="text-destructive">completely overwrite the commit history on {remoteName}</strong> with your local version, permanently deleting any commits and changes on {remoteName} that don't exist locally.
</p>
<div className="rounded-md bg-destructive/10 p-3 text-sm border border-destructive/20">
<p className="font-medium text-destructive mb-1">What will be deleted from {remoteName}:</p>
<ul className="list-disc list-outside space-y-1 text-muted-foreground ml-5">
<li>All commits on {remoteName} that aren't in your local repository</li>
<li>Any work by other contributors not in your local copy</li>
<li>The entire commit history will be replaced with your local&nbsp;history</li>
</ul>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
onClick={handleConfirm}
variant="destructive"
className="gap-2"
>
<AlertTriangle className="h-4 w-4" />
Force Push
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+328 -110
View File
@@ -1,172 +1,259 @@
import { useState } from 'react';
import { Zap, GitBranch, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink } from 'lucide-react';
import { useState, useCallback, useEffect } from 'react';
import { Zap, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink, ChevronDown, ArrowDown, ArrowUp, LoaderCircle, History, Edit } from 'lucide-react';
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 { Switch } from '@/components/ui/switch';
import { useQueryClient } from '@tanstack/react-query';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { SyncStepError } from './SyncStepError';
import { ForcePullDialog } from './ForcePullDialog';
import { ForcePushDialog } from './ForcePushDialog';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import type { StepProps } from '../types';
import { useGitSyncState } from '@/hooks/useGitSyncState';
import { useGitAutosync } from '@/hooks/useGitAutosync';
import { useNostrRepo } from '@/hooks/useNostrRepo';
import type { SyncStepProps } from '../types';
import { cn } from '@/lib/utils';
import { NostrURI } from '@/lib/NostrURI';
import { ngitWebUrl } from '@/lib/ngitWebUrl';
import { useQueryClient } from '@tanstack/react-query';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
export function SyncStep({ projectId }: StepProps) {
export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
const queryClient = useQueryClient();
const [isSyncing, setIsSyncing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [copiedUrl, setCopiedUrl] = useState(false);
const [syncSuccess, setSyncSuccess] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [showForcePullDialog, setShowForcePullDialog] = useState(false);
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [editRepoOpen, setEditRepoOpen] = useState(false);
const [repoIdentifier, setRepoIdentifier] = useState<string | null>(null);
const { data: gitStatus } = useGitStatus(projectId);
const { settings } = useGitSettings();
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const gitSync = useGitSyncState();
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
const dir = `${projectsPath}/${projectId}`;
const ref = gitStatus?.currentBranch || 'main';
// Match origin URL to a credential
const matchedCredential = originRemote
? settings.credentials.find(c => originRemote.url.startsWith(c.origin))
: null;
// Use the new hook for autosync state
const { autosync, isLoading: isLoadingAutosync, setAutosync } = useGitAutosync(dir);
const handleSync = async () => {
if (!originRemote) return;
// Get unified sync state and error
const syncState = gitSync.getState(dir);
const isSyncing = syncState?.isActive || false;
const currentOperation = syncState?.operation || null;
const error = gitSync.getError(dir) || null;
const hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0);
const commitsAhead = gitStatus?.ahead ?? 0;
const commitsBehind = gitStatus?.behind ?? 0;
// Helper to set error for this directory
const setError = useCallback((err: Error | null) => {
gitSync.setError(dir, err);
}, [dir, gitSync]);
// Generic git operation handler with success feedback
const executeGitOperation = useCallback(async (
action: () => Promise<void>
) => {
if (!remoteUrl) return;
setIsSyncing(true);
setError(null);
setSyncSuccess(false);
try {
const dir = `${projectsPath}/${projectId}`;
// Pull first to get latest changes
await git.pull({
dir,
ref: gitStatus?.currentBranch || 'main',
singleBranch: true,
});
// Then push local changes
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
});
await action();
// Show success feedback
setSyncSuccess(true);
setTimeout(() => setSyncSuccess(false), 1500);
setTimeout(() => setSyncSuccess(false), 2500);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to sync';
setError(message);
} finally {
setIsSyncing(false);
console.warn(err);
// Error is already set by the provider
}
}, [remoteUrl, setError]);
const handleSync = async () => {
await executeGitOperation(() => gitSync.sync(dir, ref));
};
const handlePull = async () => {
await executeGitOperation(() => gitSync.pull(dir, ref));
};
const handlePush = async () => {
await executeGitOperation(() => gitSync.push(dir, ref));
};
const handleForcePull = async () => {
await executeGitOperation(() => gitSync.forcePull(dir, ref));
};
const handleForcePush = async () => {
await executeGitOperation(() => gitSync.forcePush(dir, ref));
};
// Temporary feedback state helper
const showTemporaryFeedback = useCallback((
setter: (value: boolean) => void,
duration: number
) => {
setter(true);
setTimeout(() => setter(false), duration);
}, []);
const handleCopyUrl = async () => {
if (!originRemote) return;
if (!remoteUrl) return;
try {
await navigator.clipboard.writeText(originRemote.url);
setCopiedUrl(true);
setTimeout(() => setCopiedUrl(false), 2000);
await navigator.clipboard.writeText(remoteUrl.href);
showTemporaryFeedback(setCopiedUrl, 2000);
} catch (err) {
console.error('Failed to copy URL:', err);
}
};
const handleDisconnect = async () => {
if (!originRemote) return;
if (!remoteUrl) return;
try {
const dir = `${projectsPath}/${projectId}`;
await git.deleteRemote({
dir,
remote: 'origin',
});
await git.deleteRemote({ dir, remote: 'origin' });
// Clear any errors when disconnecting
setError(null);
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to disconnect';
const message = err instanceof Error ? err : new Error('Failed to disconnect');
setError(message);
}
};
const getExternalUrl = useCallback(async (url: URL): Promise<string | null> => {
if (url.protocol === 'http:' || url.protocol === 'https:') {
return url.href;
}
if (url.protocol === 'nostr:') {
const nostrUri = await NostrURI.parse(url.href);
return ngitWebUrl(config.ngitWebUrl, nostrUri);
}
return null;
}, [config.ngitWebUrl]);
const handleOpenExternal = async () => {
if (!originRemote) return;
if (!remoteUrl) return;
try {
let externalUrl: string;
if (originRemote.url.startsWith('https://')) {
// For HTTPS URLs, open directly
externalUrl = originRemote.url;
} else if (originRemote.url.startsWith('nostr://')) {
// For Nostr URLs, parse and generate URL using the configured template
const nostrUri = await NostrURI.parse(originRemote.url);
externalUrl = ngitWebUrl(config.ngitWebUrl, nostrUri);
} else {
// Unsupported URL type
return;
const externalUrl = await getExternalUrl(remoteUrl);
if (externalUrl) {
window.open(externalUrl, '_blank', 'noopener,noreferrer');
}
window.open(externalUrl, '_blank', 'noopener,noreferrer');
} catch (err) {
console.error('Failed to open external URL:', err);
}
};
const getProviderInfo = () => {
if (!originRemote) return null;
const getProviderInfo = useCallback(() => {
if (!remoteUrl) return null;
// Check if it's a Nostr URI
if (originRemote.url.startsWith('nostr://')) {
if (remoteUrl.protocol === 'nostr:') {
return {
name: 'Nostr Git',
icon: <Zap className="h-4 w-4" />,
icon: <Zap className="size-4" />,
isNostr: true,
};
}
// Check if we have a matched credential
if (matchedCredential) {
return {
name: matchedCredential.name,
icon: (
<ExternalFavicon
url={matchedCredential.origin}
size={16}
fallback={<GitBranch className="h-4 w-4" />}
/>
),
};
}
const matchedCredential = findCredentialsForRepo(remoteUrl, settings.credentials);
// Fallback to generic Git
return {
name: 'Git',
icon: <GitBranch className="h-4 w-4" />,
name: matchedCredential? matchedCredential.name : remoteUrl.hostname,
icon: <ExternalFavicon url={remoteUrl} size={16} />,
isNostr: false,
};
};
}, [remoteUrl, settings.credentials]);
const providerInfo = getProviderInfo();
const remoteName = providerInfo?.name ?? 'the remote';
if (!originRemote) {
return null;
}
// Extract repo identifier from Nostr URI if applicable
const getRepoIdentifier = useCallback(async (): Promise<string | null> => {
if (!remoteUrl || remoteUrl.protocol !== 'nostr:') {
return null;
}
try {
const nostrUri = await NostrURI.parse(remoteUrl.href);
return nostrUri.identifier;
} catch {
return null;
}
}, [remoteUrl]);
// Warm up the Nostr repo query if this is a Nostr URI
// This prefetches the data so it's ready when the edit dialog opens
useNostrRepo({
repoIdentifier: repoIdentifier || '',
enabled: !!repoIdentifier && remoteUrl?.protocol === 'nostr:',
});
// Extract and set repo identifier on mount if it's a Nostr URI
useEffect(() => {
if (remoteUrl?.protocol === 'nostr:') {
getRepoIdentifier().then(id => {
if (id) setRepoIdentifier(id);
});
}
}, [remoteUrl, getRepoIdentifier]);
// Get the button label based on current operation
const getButtonLabel = (): string => {
if (!isSyncing) return 'Sync';
switch (currentOperation) {
case 'fetch':
return 'Fetching';
case 'pull':
return 'Pulling';
case 'push':
return 'Pushing';
default:
return 'Syncing';
}
};
const handleEditRepo = () => {
if (repoIdentifier) {
setEditRepoOpen(true);
}
};
const handleRepoEditSuccess = () => {
// Refresh git status after successful edit
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
};
return (
<div className="space-y-4">
@@ -176,14 +263,6 @@ export function SyncStep({ projectId }: StepProps) {
<h3 className="font-semibold">{providerInfo?.name}</h3>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={handleOpenExternal}
>
<ExternalLink className="h-4 w-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
@@ -191,8 +270,18 @@ export function SyncStep({ projectId }: StepProps) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleDisconnect} className="text-destructive">
<CloudOff className="h-4 w-4 mr-2" />
{providerInfo?.isNostr && (
<DropdownMenuItem onClick={handleEditRepo} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setGitHistoryOpen(true)} className="gap-2">
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDisconnect} className="text-destructive gap-2">
<CloudOff className="h-4 w-4" />
Disconnect
</DropdownMenuItem>
</DropdownMenuContent>
@@ -204,7 +293,7 @@ export function SyncStep({ projectId }: StepProps) {
<Label className="text-xs text-muted-foreground">Repository URL</Label>
<div className="flex gap-2">
<Input
value={originRemote.url}
value={remoteUrl.href}
readOnly
className="flex-1 text-sm"
/>
@@ -220,27 +309,156 @@ export function SyncStep({ projectId }: StepProps) {
<Copy className="h-4 w-4" />
)}
</Button>
<Button
size="sm"
variant="outline"
onClick={handleOpenExternal}
className="shrink-0 h-10"
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex items-center gap-1.5">
<Switch
id="autosync"
checked={autosync}
onCheckedChange={setAutosync}
disabled={isLoadingAutosync}
className="scale-75"
/>
<Label htmlFor="autosync" className="text-xs cursor-pointer font-normal text-muted-foreground">
Automatic sync
</Label>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePull={() => setShowForcePullDialog(true)}
onForcePush={() => setShowForcePushDialog(true)}
onPull={handlePull}
remoteName={remoteName}
remoteUrl={remoteUrl}
/>
)}
<Button
onClick={handleSync}
disabled={isSyncing}
className="w-full"
>
<div className="flex items-center gap-2">
{syncSuccess
? <Check className="h-4 w-4" />
: <RefreshCw className={cn("size-4", { "animate-spin": isSyncing })} />}
<span>Sync</span>
{/* Unsynced changes notification */}
{hasRemoteChanges && !error && (
<div className="rounded-md bg-yellow-500/10 border border-yellow-500/20 p-3">
<p className="text-sm text-yellow-900 dark:text-yellow-100">
This branch is{' '}
{commitsAhead > 0 && (
<>
<span className="font-medium">{commitsAhead} commit{commitsAhead !== 1 ? 's' : ''} ahead of</span>
{commitsBehind > 0 ? ' and ' : ' '}
</>
)}
{commitsBehind > 0 && (
<>
<span className="font-medium">{commitsBehind} commit{commitsBehind !== 1 ? 's' : ''} behind</span>{' '}
</>
)}
<span className="font-medium">{ref}</span> on {remoteName}.
</p>
</div>
</Button>
)}
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
<div className="space-y-2">
<div className="rounded-md bg-primary relative">
<div className="flex">
<Button
onClick={handleSync}
disabled={isSyncing}
className="flex-1 rounded-r-none bg-transparent hover:bg-white/10 transition-colors"
>
<div className="flex items-center gap-2">
{syncSuccess
? <Check className="h-4 w-4" />
: <RefreshCw className={cn("size-4", { "animate-spin": isSyncing })} />}
<span>{getButtonLabel()}</span>
</div>
</Button>
<div className="w-px bg-border/20" />
<CollapsibleTrigger asChild>
<Button className="px-3 rounded-l-none bg-transparent hover:bg-white/10 transition-colors">
<ChevronDown className={cn(
"h-4 w-4 transition-transform duration-200",
{ "rotate-180": isExpanded }
)} />
</Button>
</CollapsibleTrigger>
</div>
</div>
<CollapsibleContent className="space-y-2">
<div className="flex gap-2">
<div className="relative flex-1">
<Button
onClick={handlePull}
variant="outline"
disabled={isSyncing}
className="w-full"
>
{currentOperation === 'pull' ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<ArrowDown className="h-4 w-4" />
)}
Pull
</Button>
</div>
<div className="relative flex-1">
<Button
onClick={handlePush}
variant="outline"
disabled={isSyncing}
className="w-full"
>
{currentOperation === 'push' ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<ArrowUp className="h-4 w-4" />
)}
Push
</Button>
</div>
</div>
</CollapsibleContent>
</div>
</Collapsible>
<ForcePullDialog
open={showForcePullDialog}
onOpenChange={setShowForcePullDialog}
onConfirm={handleForcePull}
remoteName={remoteName}
/>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={remoteName}
/>
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
{repoIdentifier && (
<NostrRepoEditDialog
open={editRepoOpen}
onOpenChange={setEditRepoOpen}
repoIdentifier={repoIdentifier}
onSuccess={handleRepoEditSuccess}
/>
)}
</div>
);
}
@@ -0,0 +1,167 @@
import { Errors as GitErrors } from 'isomorphic-git';
import { X, ArrowDown, ArrowUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Link } from 'react-router-dom';
import { getSentryInstance } from '@/lib/sentry';
interface SyncStepErrorProps {
error: Error;
onDismiss: () => void;
onForcePull: () => void;
onForcePush: () => void;
onPull: () => void;
remoteUrl: URL;
remoteName: string;
}
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
const renderForcePullButton = () => (
<Button
variant="outline"
size="sm"
onClick={onForcePull}
className="w-full hover:bg-destructive-foreground/20 border-destructive-foreground/20"
>
<ArrowDown className="size-4" />
Force Pull
</Button>
);
const renderForcePushButton = () => (
<Button
variant="outline"
size="sm"
onClick={onForcePush}
className="w-full hover:bg-destructive-foreground/20 border-destructive-foreground/20"
>
<ArrowUp className="size-4" />
Force Push
</Button>
);
const renderPullButton = () => (
<Button
variant="outline"
size="sm"
onClick={onPull}
>
<ArrowDown className="size-4" />
Pull
</Button>
);
const renderDismissButton = () => (
<Button
variant="ghost"
size="icon"
className="size-5 shrink-0 hover:bg-destructive-foreground/10"
onClick={onDismiss}
>
<X className="size-4" />
</Button>
);
// MergeNotSupportedError - offer force pull or force push
if (error instanceof GitErrors.MergeNotSupportedError) {
return (
<Alert variant="destructive">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
Cannot merge changes automatically. Your local changes conflict with the remote repository.
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{renderForcePullButton()}
{renderForcePushButton()}
</div>
</div>
</Alert>
);
}
// FastForwardError - offer force pull or force push
if (error instanceof GitErrors.FastForwardError) {
return (
<Alert variant="destructive">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
Cannot fast-forward. The remote has changes that conflict with your local commits.
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{renderForcePullButton()}
{renderForcePushButton()}
</div>
</div>
</Alert>
);
}
// PushRejectedError - remote has changes
if (error instanceof GitErrors.PushRejectedError) {
return (
<Alert variant="destructive">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{renderPullButton()}
{renderForcePushButton()}
</div>
</div>
</Alert>
);
}
// HTTP errors
if (error instanceof GitErrors.HttpError) {
let message: React.ReactNode = `HTTP Error: ${error.data.statusCode} ${error.data.statusMessage}`;
if (remoteUrl.protocol === 'nostr:') {
// This should never happen
getSentryInstance()?.captureException(error);
message = `There was an HTTP (${error.data.statusCode}) error communicating with Nostr Git servers.`
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
switch (error.data.statusCode) {
case 401:
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
break;
case 403:
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
break;
}
}
return (
<Alert variant="destructive">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
{message}
</AlertDescription>
{renderDismissButton()}
</div>
</Alert>
);
}
// Generic error fallback
return (
<Alert variant="destructive">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1 whitespace-pre overflow-x-auto">
{error.message}
</AlertDescription>
{renderDismissButton()}
</div>
</Alert>
);
}
+4
View File
@@ -21,6 +21,10 @@ export interface StepProps {
onClose: () => void;
}
export interface SyncStepProps extends StepProps {
remoteUrl: URL;
}
export interface SelectProviderStepProps extends StepProps {
onSelectProvider: (provider: ProviderOption) => void;
}
+1 -1
View File
@@ -123,7 +123,7 @@ export function BrowserAddressBar({
variant="ghost"
size="sm"
onClick={onRefresh}
className="size-6 absolute right-1 top-1/2 -translate-y-1/2 hover:bg-muted/50 rounded-full transition-colors group"
className="size-6 absolute right-1 top-1/2 -translate-y-1/2 hover:bg-muted/50 rounded-full transition-colors group px-1.5"
title="Refresh"
>
<RefreshCw className="size-3 text-muted-foreground transition-colors group-hover:text-foreground" />
+3 -3
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<X className="size-5" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
@@ -57,7 +57,7 @@ const DialogHeader = ({
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
"flex flex-col space-y-1.5",
className
)}
{...props}
@@ -71,7 +71,7 @@ const DialogFooter = ({
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
"flex flex-col-reverse sm:flex-row sm:justify-end gap-2",
className
)}
{...props}
+2
View File
@@ -38,6 +38,8 @@ export interface AppConfig {
esmUrl: string;
/** HTTP proxy used to bypass CORS for AI and Git operations */
corsProxy: string;
/** Git origins that should use the CORS proxy (e.g., ["https://github.com", "https://gitlab.com"]) */
gitProxyOrigins: string[];
/** Favicon URL template (e.g., "https://external-content.duckduckgo.com/ip3/{hostname}.ico") */
faviconUrl: string;
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
+38
View File
@@ -0,0 +1,38 @@
import { createContext } from 'react';
export type GitOperation = 'fetch' | 'pull' | 'push';
export interface GitSyncState {
dir: string;
operation: GitOperation;
isActive: boolean;
error?: Error;
}
export interface FetchResult {
defaultBranch: string | null;
fetchHead: string | null;
fetchHeadDescription: string | null;
}
export interface GitSyncContextValue {
// State access
syncStates: Map<string, GitSyncState>;
getState: (dir: string) => GitSyncState | undefined;
getError: (dir: string) => Error | undefined;
// Git operations
fetch: (dir: string, remote?: string) => Promise<FetchResult>;
pull: (dir: string, ref: string, remote?: string) => Promise<void>;
push: (dir: string, ref: string, remote?: string, force?: boolean) => Promise<void>;
sync: (dir: string, ref: string, remote?: string) => Promise<void>;
forcePull: (dir: string, ref: string, remote?: string) => Promise<void>;
forcePush: (dir: string, ref: string, remote?: string) => Promise<void>;
// Internal state management (for backward compatibility during migration)
startOperation: (dir: string, operation: GitOperation) => void;
endOperation: (dir: string, error?: Error) => void;
setError: (dir: string, error: Error | null) => void;
}
export const GitSyncContext = createContext<GitSyncContextValue | null>(null);
+69 -10
View File
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
import { useAISettings } from '@/hooks/useAISettings';
import type { AIMessage } from '@/lib/SessionManager';
import type { AIMessage, DisplayMessage } from '@/lib/SessionManager';
import type OpenAI from 'openai';
import type { Tool } from '@/lib/tools/Tool';
@@ -39,20 +39,36 @@ export function useAIChat({
// Split session state into individual variables for efficient updates
const [messages, setMessages] = useState<AIMessage[]>([]);
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
const [sessionName, setSessionName] = useState<string>('');
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [totalCost, setTotalCost] = useState<number>(0);
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
const initSession = useCallback(async () => {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
// Initialize individual state variables from existing session
setMessages([...session.messages]);
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
setIsLoading(session.isLoading);
setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0);
setIsLoadingHistory(true);
try {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
// Initialize individual state variables from existing session
setMessages([...session.messages]);
setDisplayMessages([...session.displayMessages]);
setSessionName(session.sessionName);
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
setIsLoading(session.isLoading);
setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0);
setLastFinishReason(session.lastFinishReason ?? null);
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
} finally {
setIsLoadingHistory(false);
}
}, [sessionManager, projectId, tools, customTools, maxSteps]);
// Initialize session
@@ -109,6 +125,31 @@ export function useAIChat({
}
}, [projectId]);
useSessionSubscription('finishReasonChanged', (updatedProjectId: string, finishReason: string | null) => {
if (updatedProjectId === projectId) {
setLastFinishReason(finishReason);
}
}, [projectId]);
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: DisplayMessage) => {
if (updatedProjectId === projectId) {
setDisplayMessages(prev => [...prev, message]);
}
}, [projectId]);
useSessionSubscription('displayMessagesPrepended', (updatedProjectId: string, newMessages: DisplayMessage[]) => {
if (updatedProjectId === projectId) {
setDisplayMessages(prev => [...newMessages, ...prev]);
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
}
}, [projectId, sessionManager]);
useSessionSubscription('loadingMoreHistoryChanged', (updatedProjectId: string, loading: boolean) => {
if (updatedProjectId === projectId) {
setIsLoadingMoreHistory(loading);
}
}, [projectId]);
// Actions
const sendMessage = useCallback(async (
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
@@ -150,11 +191,18 @@ export function useAIChat({
const startNewSession = useCallback(async () => {
await sessionManager.startNewSession(projectId);
// Reset individual state variables
// Get the updated session to retrieve the new session name
const session = sessionManager.getSession(projectId);
if (session) {
setSessionName(session.sessionName);
}
// Reset only AI prompt state (not display state which is handled via events)
setMessages([]);
setStreamingMessage(undefined);
setTotalCost(0);
setLastInputTokens(0);
setLastFinishReason(null);
}, [projectId, sessionManager]);
const clearMessages = useCallback(async () => {
@@ -162,18 +210,29 @@ export function useAIChat({
await startNewSession();
}, [startNewSession]);
const loadMoreHistory = useCallback(async () => {
await sessionManager.loadOlderSession(projectId);
}, [projectId, sessionManager]);
return {
messages,
displayMessages,
sessionName,
streamingMessage,
isLoading,
isLoadingHistory,
hasMoreHistory,
isLoadingMoreHistory,
totalCost,
lastInputTokens,
lastFinishReason,
sendMessage,
startGeneration,
stopGeneration,
clearMessages,
startNewSession,
addMessage,
loadMoreHistory,
isConfigured,
projectId
};
+2
View File
@@ -63,6 +63,7 @@ describe('useGenerateProjectInfo', () => {
templates: defaultTemplates,
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
@@ -224,6 +225,7 @@ describe('useGenerateProjectInfo', () => {
templates: [],
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
+16 -6
View File
@@ -40,6 +40,7 @@ function createWrapper(corsProxy: string) {
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
esmUrl: 'https://esm.test',
corsProxy,
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-test.dev',
@@ -93,8 +94,11 @@ describe('useGit', () => {
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
onAuth: expect.any(Function),
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
relayList: [{ url: new URL('wss://relay.test/'), read: true, write: true }],
graspList: [{ url: new URL('wss://git.shakespeare.diy/') }, { url: new URL('wss://relay.ngit.dev/') }],
credentials: [],
signer: undefined,
});
expect(result.current).toEqual({ git: expect.any(Object) });
});
@@ -108,8 +112,11 @@ describe('useGit', () => {
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://custom-cors.example.com',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
onAuth: expect.any(Function),
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
relayList: [{ url: new URL('wss://relay.test/'), read: true, write: true }],
graspList: [{ url: new URL('wss://git.shakespeare.diy/') }, { url: new URL('wss://relay.ngit.dev/') }],
credentials: [],
signer: undefined,
});
expect(result.current).toEqual({ git: expect.any(Object) });
});
@@ -123,8 +130,11 @@ describe('useGit', () => {
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
onAuth: expect.any(Function),
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
relayList: [{ url: new URL('wss://relay.test/'), read: true, write: true }],
graspList: [{ url: new URL('wss://git.shakespeare.diy/') }, { url: new URL('wss://relay.ngit.dev/') }],
credentials: [],
signer: undefined,
});
// Rerender with a different wrapper (different CORS proxy)
+22 -15
View File
@@ -1,9 +1,8 @@
import { useCallback, useMemo } from 'react';
import { useMemo } from 'react';
import { Git } from '@/lib/git';
import { useFS } from '@/hooks/useFS';
import { useNostr } from '@nostrify/react';
import { useAppContext } from '@/hooks/useAppContext';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { useGitSettings } from './useGitSettings';
import { useCurrentUser } from './useCurrentUser';
@@ -17,34 +16,42 @@ export function useGit(): { git: Git } {
const { nostr } = useNostr();
const { config } = useAppContext();
const { settings } = useGitSettings();
const { corsProxy, graspMetadata } = config;
const { corsProxy, gitProxyOrigins, relayMetadata, graspMetadata } = config;
const ngitServers = useMemo(() => {
const relayList = useMemo(() => {
// Extract hostnames from grasp relay URLs for backwards compatibility with Git class
return graspMetadata.relays.map(r => {
return relayMetadata.relays.map(r => {
try {
const url = new URL(r.url);
return url.hostname;
return { ...r, url: new URL(r.url) };
} catch {
return undefined;
}
}).filter((hostname): hostname is string => Boolean(hostname));
}, [graspMetadata.relays]);
}).filter((url): url is { url: URL, read: boolean; write: boolean; } => Boolean(url));
}, [relayMetadata.relays]);
const onAuth = useCallback((url: string) => {
return findCredentialsForRepo(url, settings.credentials);
}, [settings.credentials]);
const graspList = useMemo(() => {
// Extract hostnames from grasp relay URLs for backwards compatibility with Git class
return graspMetadata.relays.map(r => {
try {
return { url: new URL(r.url) };
} catch {
return undefined;
}
}).filter((relay): relay is { url: URL } => Boolean(relay));
}, [graspMetadata.relays]);
const git = useMemo(() => {
return new Git({
fs,
nostr,
corsProxy,
ngitServers,
onAuth,
gitProxyOrigins,
relayList,
graspList,
credentials: settings.credentials,
signer: user?.signer,
});
}, [fs, nostr, corsProxy, ngitServers, onAuth, user?.signer]);
}, [fs, nostr, corsProxy, gitProxyOrigins, relayList, graspList, settings.credentials, user?.signer]);
return { git };
}
+58
View File
@@ -0,0 +1,58 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useGit } from './useGit';
export function useGitAutosync(dir: string | undefined) {
const { git } = useGit();
const queryClient = useQueryClient();
const query = useQuery({
queryKey: ['git-autosync', dir],
queryFn: async (): Promise<boolean> => {
if (!dir) return false;
try {
const value = await git.getConfig({
dir,
path: 'shakespeare.autosync',
});
return value === 'true';
} catch {
// Config not set, default to false
return false;
}
},
enabled: !!dir,
staleTime: Infinity, // This value rarely changes, keep it cached
});
const mutation = useMutation({
mutationFn: async (enabled: boolean) => {
if (!dir) throw new Error('No directory specified');
await git.setConfig({
dir,
path: 'shakespeare.autosync',
value: String(enabled),
});
return enabled;
},
onSuccess: (enabled) => {
// Update the cached value immediately
queryClient.setQueryData(['git-autosync', dir], enabled);
// If enabling autosync, trigger an immediate sync
if (enabled) {
queryClient.invalidateQueries({ queryKey: ['git-sync', dir] });
}
},
});
return {
autosync: query.data ?? false,
isLoading: query.isLoading,
setAutosync: mutation.mutateAsync,
isUpdating: mutation.isPending,
refetch: query.refetch,
};
}
+126
View File
@@ -0,0 +1,126 @@
import { useQuery } from '@tanstack/react-query';
import { useGit } from './useGit';
import { useGitSyncState } from './useGitSyncState';
import { useProjectSessionStatus } from './useProjectSessionStatus';
interface GitSyncResult {
defaultBranch: string | null;
fetchHead: string | null;
fetchHeadDescription: string | null;
didPull?: boolean;
didPush?: boolean;
}
export function useGitSync(dir: string | undefined, remote = 'origin') {
const { git } = useGit();
const gitSync = useGitSyncState();
// Extract project ID from directory path
const projectId = dir?.split('/').pop() || '';
const { hasRunningSessions } = useProjectSessionStatus(projectId);
const query = useQuery({
queryKey: ['git-sync', dir],
queryFn: async (): Promise<GitSyncResult> => {
// Don't sync if project is currently generating
if (hasRunningSessions) {
return {
defaultBranch: null,
fetchHead: null,
fetchHeadDescription: null,
};
}
const remotes = await git.listRemotes({ dir });
const hasOrigin = !!remotes.find(r => r.remote === remote);
if (!dir || !hasOrigin) {
return {
defaultBranch: null,
fetchHead: null,
fetchHeadDescription: null,
};
}
try {
// Check if autosync is enabled
const autosync = await git.getConfig({
dir,
path: 'shakespeare.autosync',
});
let didPull = false;
let didPush = false;
// If autosync is enabled, perform pull and push
// (pull does fetch internally, so no separate fetch needed)
if (autosync === 'true') {
try {
// Get current branch
const currentBranch = await git.currentBranch({ dir });
if (currentBranch) {
// Pull changes from remote (this does fetch internally)
try {
await gitSync.pull(dir, currentBranch, remote);
didPull = true;
// Clear any previous errors on successful pull
gitSync.setError(dir, null);
} catch (pullError) {
// Pull might fail if there are conflicts or diverged branches
// Error is already set by the provider - just log and continue
console.warn('Auto-pull failed:', pullError);
}
// Push local changes to remote
try {
await gitSync.push(dir, currentBranch, remote);
didPush = true;
// Clear any previous errors on successful push
gitSync.setError(dir, null);
} catch (pushError) {
// Push might fail if there are conflicts or no changes
// Error is already set by the provider - just log and continue
console.warn('Auto-push failed:', pushError);
}
}
} catch (error) {
// Error getting current branch or other unexpected error
console.warn('Auto-sync failed:', error);
}
// Return result without fetch data since pull already fetched
return {
defaultBranch: null,
fetchHead: null,
fetchHeadDescription: null,
didPull,
didPush,
};
} else {
// Only fetch when autosync is not enabled (since pull isn't being called)
const fetchResult = await gitSync.fetch(dir, remote);
return {
...fetchResult,
didPull,
didPush,
};
}
} catch (error) {
// Fetch/sync failed, but don't throw - just log and return null
// Error is already set by the provider
console.warn('Git sync failed:', error);
return {
defaultBranch: null,
fetchHead: null,
fetchHeadDescription: null,
};
}
},
enabled: !!dir && !hasRunningSessions, // Don't sync while project is generating
refetchInterval: 5 * 60 * 1000, // Sync every 5 minutes
staleTime: 1 * 60 * 1000, // Consider data stale after 1 minute
retry: false, // Don't retry on failure
});
return query;
}
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { GitSyncContext } from '@/contexts/GitSyncContext';
export function useGitSyncState() {
const context = useContext(GitSyncContext);
if (!context) {
throw new Error('useGitSyncState must be used within GitSyncProvider');
}
return context;
}
+25
View File
@@ -0,0 +1,25 @@
import { useGitSyncState } from './useGitSyncState';
import { useFSPaths } from './useFSPaths';
/**
* Hook to get the current git sync status for a project
*/
export function useGitSyncStatus(projectId: string | undefined) {
const { getState } = useGitSyncState();
const { projectsPath } = useFSPaths();
if (!projectId) {
return {
isActive: false,
operation: null,
};
}
const dir = `${projectsPath}/${projectId}`;
const state = getState(dir);
return {
isActive: state?.isActive || false,
operation: state?.operation || null,
};
}
+33
View File
@@ -0,0 +1,33 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { useCurrentUser } from '@/hooks/useCurrentUser';
interface UseNostrRepoOptions {
repoIdentifier: string;
enabled?: boolean;
}
/**
* Hook to fetch a Nostr repository announcement event (kind 30617) by identifier.
* The query is cached for 30 seconds and can be prefetched for better UX.
*/
export function useNostrRepo({ repoIdentifier, enabled = true }: UseNostrRepoOptions) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr-repo', user?.pubkey, repoIdentifier],
queryFn: async () => {
if (!user) return null;
const events = await nostr.query(
[{ kinds: [30617], authors: [user.pubkey], '#d': [repoIdentifier], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
return events.length > 0 ? events[0] : null;
},
enabled: enabled && !!user && !!repoIdentifier,
staleTime: 30000, // Cache for 30 seconds
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
export interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel';
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
clientId: string;
clientSecret: string;
authorizeUrl: string;
+164
View File
@@ -0,0 +1,164 @@
import { useState, useCallback } from 'react';
import { useAISettings } from './useAISettings';
import type { AIProvider } from '@/contexts/AISettingsContext';
interface OpenRouterTokenResponse {
key: string;
}
/**
* Hook for OpenRouter OAuth authentication with PKCE.
* OpenRouter uses a custom OAuth flow that differs from standard OAuth 2.0.
* It uses PKCE without requiring client credentials.
*/
export function useOpenRouterOAuth() {
const { setProvider, isLoading: isSettingsLoading } = useAISettings();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// OpenRouter doesn't require client credentials - it uses PKCE only
const isOAuthConfigured = true;
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
// Create SHA-256 hash of the code verifier for PKCE code challenge
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
/**
* Initiates the OAuth flow by redirecting to OpenRouter's authorization page.
*/
const initiateOAuth = useCallback(async () => {
try {
// Generate a random state parameter for security
const state = crypto.randomUUID();
const storagePrefix = 'openrouter_oauth';
// Store state for later verification
localStorage.setItem(`${storagePrefix}_state`, state);
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
// Build authorization URL
const redirectUri = window.location.origin + '/oauth/openrouter';
const params = new URLSearchParams({
callback_url: redirectUri,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
// Redirect to OpenRouter's authorization page
window.location.href = `https://openrouter.ai/auth?${params.toString()}`;
} catch (error) {
console.error('Failed to initiate OpenRouter OAuth:', error);
setError('Failed to generate PKCE parameters. Please try again.');
}
}, []);
/**
* Handles the OAuth callback after the user authorizes the application.
* Exchanges the authorization code for an API key.
*/
const handleCallback = useCallback(async (
code: string,
_state: string
): Promise<boolean> => {
setIsLoading(true);
setError(null);
const storagePrefix = 'openrouter_oauth';
try {
// Get PKCE code verifier
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
if (!codeVerifier) {
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
}
// Clean up stored values
localStorage.removeItem(`${storagePrefix}_state`);
localStorage.removeItem(`${storagePrefix}_code_verifier`);
// Exchange code for API key using OpenRouter's custom endpoint
const tokenResponse = await fetch('https://openrouter.ai/api/v1/auth/keys', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: code,
code_verifier: codeVerifier,
code_challenge_method: 'S256',
}),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
throw new Error(`OpenRouter token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
}
const tokenData: OpenRouterTokenResponse = await tokenResponse.json();
if (!tokenData.key) {
throw new Error('No API key received from OpenRouter');
}
// Wait for settings to be initialized before storing
if (isSettingsLoading) {
throw new Error('Settings not initialized. Please try again.');
}
// Create a new OpenRouter provider with the OAuth token
const newProvider: AIProvider = {
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: tokenData.key,
};
// Add or update the OpenRouter provider in settings
setProvider(newProvider);
setIsLoading(false);
return true;
} catch (error) {
console.error('OpenRouter OAuth error:', error);
// Clean up any remaining OAuth data on error
localStorage.removeItem(`${storagePrefix}_state`);
localStorage.removeItem(`${storagePrefix}_code_verifier`);
setError(error instanceof Error ? error.message : 'OAuth authentication failed');
setIsLoading(false);
return false;
}
}, [setProvider, isSettingsLoading]);
return {
isLoading,
error,
isOAuthConfigured,
initiateOAuth,
handleCallback,
};
}
-67
View File
@@ -27,73 +27,6 @@ describe('DotAI', () => {
dotAI = new DotAI(mockFS, '/test-project');
});
describe('readLastSessionHistory', () => {
it('should return null when history directory does not exist', async () => {
// Mock historyDirExists to return false
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when no session files exist', async () => {
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return empty array
vi.mocked(mockFS.readdir).mockResolvedValue([]);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return messages and session name from most recent file', async () => {
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue([
'2024-08-24T16-30-45Z-abc.jsonl',
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
'2024-08-24T15-00-00Z-xyz.jsonl'
]);
// Mock readFile to return JSONL content
const mockContent = `{"role":"user","content":"Hello"}
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
expect(result?.messages).toHaveLength(2);
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
it('should handle malformed JSON lines gracefully', async () => {
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
// Mock readFile to return content with malformed JSON
const mockContent = `{"role":"user","content":"Hello"}
invalid json line
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
});
describe('setHistory', () => {
it('should create history directory if it does not exist', async () => {
// Mock historyDirExists to return false initially
+69 -50
View File
@@ -216,66 +216,50 @@ export class DotAI {
}
/**
* Read the most recent session history
* @returns Object containing messages array and session name, or null if no history found
* List all session names sorted chronologically (oldest first)
* Fast operation - does not load message content
* @returns Array of session names (filenames without .jsonl extension)
*/
async readLastSessionHistory(): Promise<{
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
sessionName: string;
} | null> {
async listSessionNames(): Promise<string[]> {
try {
// Check if history directory exists
if (!(await this.historyDirExists())) {
return null;
return [];
}
// Find the most recent session file
try {
const files = await this.fs.readdir(this.historyDir);
const sessionFiles = files
.filter(file => file.endsWith('.jsonl'))
.sort()
.reverse(); // Most recent first
const files = await this.fs.readdir(this.historyDir);
return files
.filter(file => file.endsWith('.jsonl'))
.map(file => file.replace('.jsonl', ''))
.sort(); // Chronological order (oldest first) - filenames contain timestamps
} catch {
return [];
}
}
if (sessionFiles.length === 0) {
return null;
}
const latestSessionFile = sessionFiles[0];
const sessionPath = join(this.historyDir, latestSessionFile);
/**
* Read messages for a single session
* @param sessionName The session name (filename without .jsonl)
* @returns Array of messages, or empty array if session not found
*/
async readSessionHistory(sessionName: string): Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
try {
const sessionPath = join(this.historyDir, sessionName + '.jsonl');
const content = await this.fs.readFile(sessionPath, 'utf8');
const lines = content.trim().split('\n').filter(line => line.trim());
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
for (const line of lines) {
try {
const content = await this.fs.readFile(sessionPath, 'utf8');
const lines = content.trim().split('\n').filter(line => line.trim());
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
for (const line of lines) {
try {
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch (parseError) {
console.warn('Failed to parse message from history:', parseError);
}
}
// Return session name without .jsonl extension
const sessionName = latestSessionFile.replace('.jsonl', '');
return {
messages,
sessionName
};
} catch (readError) {
console.warn('Failed to read session file:', readError);
return null;
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch {
// Skip malformed lines
}
} catch (readdirError) {
console.warn('Failed to read history directory:', readdirError);
return null;
}
} catch (error) {
console.warn('Failed to read last session history:', error);
return null;
return messages;
} catch {
return [];
}
}
@@ -358,4 +342,39 @@ export class DotAI {
console.warn(`Failed to write .git/shakespeare/template.json file: ${error}`);
}
}
/**
* Read the last finish reason from .git/ai/FINISH_REASON file
* @returns The finish reason string, or null if file doesn't exist or is empty
*/
async readFinishReason(): Promise<string | null> {
try {
const finishReasonPath = join(this.workingDir, ".git", "ai", "FINISH_REASON");
const content = await this.fs.readFile(finishReasonPath, "utf8");
const trimmed = content.trim();
return trimmed || null;
} catch {
return null;
}
}
/**
* Write the finish reason to .git/ai/FINISH_REASON file
* @param finishReason The finish reason string, or null to clear
*/
async writeFinishReason(finishReason: string | null): Promise<void> {
const aiDir = join(this.workingDir, ".git", "ai");
const finishReasonPath = join(aiDir, "FINISH_REASON");
try {
// Ensure .git/ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Write the finish reason (empty string if null)
const content = finishReason ? finishReason.trim() + "\n" : "";
await this.fs.writeFile(finishReasonPath, content);
} catch (error) {
console.warn(`Failed to write .git/ai/FINISH_REASON file: ${error}`);
}
}
}
-397
View File
@@ -1,397 +0,0 @@
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
/**
* Electron filesystem adapter that implements JSRuntimeFS interface
* This adapter communicates with Electron's main process via IPC to perform
* filesystem operations on the actual OS filesystem.
*
* Note: This adapter should only be instantiated when running in Electron.
*/
export class ElectronFSAdapter implements JSRuntimeFS {
// Cache for stat results to avoid repeated IPC calls
private statCache = new Map<string, { result: Awaited<ReturnType<typeof this.electron.fs.stat>>; timestamp: number }>();
private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache
// Cache for ENOENT results to avoid repeated failed reads (especially for git objects)
private enoentCache = new Set<string>();
private readonly ENOENT_CACHE_MAX_SIZE = 5000;
private get electron() {
if (!window.electron) {
throw new Error('ElectronFSAdapter can only be used in Electron environment');
}
return window.electron;
}
/**
* Unwrap Electron IPC errors to preserve error codes.
* Electron wraps errors in "Error invoking remote method..." messages,
* but we need to preserve the original error code for isomorphic-git.
*/
private unwrapElectronError(error: unknown): Error {
if (!(error instanceof Error)) {
return error as Error;
}
// Extract error code from the error object if it exists
const code = (error as NodeJS.ErrnoException).code;
// If there's already a code, preserve it
if (code) {
const err = new Error(error.message);
(err as NodeJS.ErrnoException).code = code;
return err;
}
// If no code property, try to extract from the message
// Messages look like: "Error invoking remote method 'fs:stat': Error: Failed to stat /path: ENOENT: no such file or directory"
const match = error.message.match(/:\s*(E[A-Z]+):/);
if (match) {
const err = new Error(error.message);
(err as NodeJS.ErrnoException).code = match[1];
return err;
}
return error;
}
async readFile(path: string): Promise<Uint8Array<ArrayBufferLike>>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>> {
try {
// Validate path is not empty (isomorphic-git sometimes passes empty strings during ref resolution)
if (!path || path.trim() === '') {
const err = new Error(`EINVAL: invalid path ''`);
(err as NodeJS.ErrnoException).code = 'EINVAL';
throw err;
}
// Check if we've already seen ENOENT for this path (common for git packed objects)
if (this.enoentCache.has(path)) {
const err = new Error(`ENOENT: no such file or directory, open '${path}'`);
(err as NodeJS.ErrnoException).code = 'ENOENT';
throw err;
}
const encoding = typeof options === 'string' ? options : options?.encoding;
const result = await this.electron.fs.readFile(path, encoding);
// If no encoding, convert array to Uint8Array
if (!encoding && Array.isArray(result)) {
return new Uint8Array(result);
}
return result as string;
} catch (error) {
const unwrapped = this.unwrapElectronError(error);
// Cache ENOENT errors to avoid repeated IPC calls for missing files
// This is especially important for git packed objects that isomorphic-git tries to read
if ((unwrapped as NodeJS.ErrnoException).code === 'ENOENT') {
this.enoentCache.add(path);
// Limit cache size to prevent memory leaks
if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) {
// Clear oldest entries (first 1000)
const entries = Array.from(this.enoentCache);
entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry));
}
}
throw unwrapped;
}
}
async writeFile(path: string, data: string | Uint8Array<ArrayBufferLike>, options?: string | { encoding?: string }): Promise<void> {
try {
const encoding = typeof options === 'string' ? options : options?.encoding;
// Convert Uint8Array to regular array for IPC serialization
const dataToWrite = data instanceof Uint8Array ? Array.from(data) : data;
const result = await this.electron.fs.writeFile(path, dataToWrite, encoding);
// Invalidate caches for this path and its parent directory
this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`);
this.enoentCache.delete(path); // File now exists
const parentDir = path.substring(0, path.lastIndexOf('/'));
if (parentDir) {
this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`);
}
return result;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
try {
// Fast path: check if this is a file first (common case causing errors)
// Use cached stat if available to avoid extra IPC call
const cached = this.statCache.get(path);
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
if (cached.result.isFile) {
// This is a file, not a directory - throw ENOTDIR immediately
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
throw err;
}
}
const result = await this.electron.fs.readdir(path, options?.withFileTypes);
if (options?.withFileTypes) {
// Convert plain objects to DirectoryEntry format
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({
name: entry.name,
isDirectory: () => entry.isDirectory,
isFile: () => entry.isFile,
}));
}
return result as string[];
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
try {
// Default to recursive: true for isomorphic-git compatibility
// isomorphic-git expects mkdir to behave like 'mkdir -p'
const recursive = options?.recursive !== false;
const result = await this.electron.fs.mkdir(path, recursive);
// Invalidate cache for this path and parent
this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`);
const parentDir = path.substring(0, path.lastIndexOf('/'));
if (parentDir) {
this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`);
}
return result;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
mtime: Date;
ctime: Date;
atime: Date;
}> {
try {
// Check cache first
const cached = this.statCache.get(path);
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
return cached.result;
}
const result = await this.electron.fs.stat(path);
const now = Date.now();
const statResult = {
isDirectory: () => result.isDirectory,
isFile: () => result.isFile,
isBlockDevice: () => result.isBlockDevice,
isCharacterDevice: () => result.isCharacterDevice,
isSymbolicLink: () => result.isSymbolicLink,
isFIFO: () => result.isFIFO,
isSocket: () => result.isSocket,
size: result.size ?? 0,
mtimeMs: result.mtimeMs ?? now,
ctimeMs: result.ctimeMs ?? now,
atimeMs: result.atimeMs ?? now,
// Convert timestamps back to Date objects
mtime: new Date(result.mtime ?? now),
ctime: new Date(result.ctime ?? now),
atime: new Date(result.atime ?? now),
};
// Cache the result
this.statCache.set(path, { result: statResult, timestamp: Date.now() });
// Limit cache size to prevent memory leaks
if (this.statCache.size > 10000) {
// Remove oldest entries (first 1000)
const entries = Array.from(this.statCache.entries());
entries.slice(0, 1000).forEach(([key]) => this.statCache.delete(key));
}
return statResult;
} catch (error) {
// Electron IPC wraps errors, extract the original error code
throw this.unwrapElectronError(error);
}
}
async lstat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
mtime: Date;
ctime: Date;
atime: Date;
}> {
try {
// Check cache first (use separate cache key for lstat)
const cacheKey = `lstat:${path}`;
const cached = this.statCache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
return cached.result;
}
const result = await this.electron.fs.lstat(path);
const now = Date.now();
const statResult = {
isDirectory: () => result.isDirectory,
isFile: () => result.isFile,
isBlockDevice: () => result.isBlockDevice,
isCharacterDevice: () => result.isCharacterDevice,
isSymbolicLink: () => result.isSymbolicLink,
isFIFO: () => result.isFIFO,
isSocket: () => result.isSocket,
size: result.size ?? 0,
mtimeMs: result.mtimeMs ?? now,
ctimeMs: result.ctimeMs ?? now,
atimeMs: result.atimeMs ?? now,
// Convert timestamps back to Date objects
mtime: new Date(result.mtime ?? now),
ctime: new Date(result.ctime ?? now),
atime: new Date(result.atime ?? now),
};
// Cache the result
this.statCache.set(cacheKey, { result: statResult, timestamp: Date.now() });
// Limit cache size to prevent memory leaks
if (this.statCache.size > 10000) {
// Remove oldest entries (first 1000)
const entries = Array.from(this.statCache.entries());
entries.slice(0, 1000).forEach(([key]) => this.statCache.delete(key));
}
return statResult;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async unlink(path: string): Promise<void> {
try {
const result = await this.electron.fs.unlink(path);
// Invalidate cache for this path and parent
this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`);
const parentDir = path.substring(0, path.lastIndexOf('/'));
if (parentDir) {
this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`);
}
return result;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async rmdir(path: string): Promise<void> {
try {
const result = await this.electron.fs.rmdir(path);
// Invalidate cache for this path and parent
this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`);
const parentDir = path.substring(0, path.lastIndexOf('/'));
if (parentDir) {
this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`);
}
return result;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async rename(oldPath: string, newPath: string): Promise<void> {
try {
const result = await this.electron.fs.rename(oldPath, newPath);
// Invalidate cache for both paths and their parents
this.statCache.delete(oldPath);
this.statCache.delete(`lstat:${oldPath}`);
this.statCache.delete(newPath);
this.statCache.delete(`lstat:${newPath}`);
const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/'));
if (oldParent) {
this.statCache.delete(oldParent);
this.statCache.delete(`lstat:${oldParent}`);
}
const newParent = newPath.substring(0, newPath.lastIndexOf('/'));
if (newParent) {
this.statCache.delete(newParent);
this.statCache.delete(`lstat:${newParent}`);
}
return result;
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async readlink(path: string): Promise<string> {
try {
return await this.electron.fs.readlink(path);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
async symlink(target: string, path: string): Promise<void> {
try {
return await this.electron.fs.symlink(target, path);
} catch (error) {
throw this.unwrapElectronError(error);
}
}
/**
* Clear all caches. Useful when switching projects or after major filesystem changes.
*/
clearCaches(): void {
this.statCache.clear();
this.enoentCache.clear();
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ export interface NostrURIParts {
* const uri = new NostrURI({
* pubkey: 'abc123...',
* identifier: 'my-repo',
* relay: 'relay.example.com'
* relay: 'wss://relay.example.com/'
* });
*
* // Parse from string
+13 -6
View File
@@ -114,11 +114,10 @@ export class ProjectsManager {
* exactly match the remote.
*/
private async forcePullTemplate(templatePath: string): Promise<void> {
// Fetch the latest changes from remote (shallow fetch for efficiency)
// Fetch the latest changes from remote
const fetchResult = await this.git.fetch({
dir: templatePath,
singleBranch: true,
depth: 1,
});
// Get the current branch name (e.g., "refs/heads/main")
@@ -147,13 +146,12 @@ export class ProjectsManager {
force: true,
});
// Directly checkout the remote commit to update working directory
// This bypasses merge entirely and just makes the working directory
// match the remote commit exactly. Safe for templates.
// Checkout the branch (not the commit SHA) to update working directory
// This keeps the repository on the branch instead of entering detached HEAD state
// Using force: true to overwrite any local changes
await this.git.checkout({
dir: templatePath,
ref: remoteOid,
ref: branchName,
force: true,
});
}
@@ -524,6 +522,15 @@ export class ProjectsManager {
remote: fork ? 'upstream' : undefined, // Use 'upstream' for forks, otherwise defaults to 'origin'
});
if (!fork) {
// Set up 'shakespeare.autosync' config for non-forked repositories
await this.git.setConfig({
dir: projectPath,
path: 'shakespeare.autosync',
value: 'true',
});
}
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
+1
View File
@@ -43,6 +43,7 @@ const testConfig: AppConfig = {
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
+181 -30
View File
@@ -1,4 +1,5 @@
import OpenAI from 'openai';
import type { Decimal } from 'decimal.js';
import type { JSRuntimeFS } from './JSRuntime';
import { DotAI } from './DotAI';
import { parseProviderModel } from './parseProviderModel';
@@ -14,6 +15,7 @@ import { isEmptyMessage } from './isEmptyMessage';
import { Git } from './git';
import type { NPool } from '@nostrify/nostrify';
import type { AppConfig } from '@/contexts/AppContext';
import { getSentryInstance } from './sentry';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
@@ -22,12 +24,20 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
/** AIMessage with session tracking for UI display */
export type DisplayMessage = AIMessage & {
sessionId?: string; // Session identifier for grouping messages in UI
};
export interface SessionState {
projectId: string;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools: Record<string, Tool<unknown>>;
maxSteps?: number;
messages: AIMessage[];
messages: AIMessage[]; // Current session messages (sent to AI)
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with sessionId)
availableSessionNames: string[]; // All session names (for lazy loading)
loadedSessionCount: number; // How many sessions loaded from the end
streamingMessage?: {
role: 'assistant';
content: string;
@@ -35,23 +45,29 @@ export interface SessionState {
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
isLoading: boolean;
isLoadingMoreHistory: boolean; // Loading older sessions
sessionName: string;
lastActivity: Date;
abortController?: AbortController;
totalCost?: number; // Total cost in USD for this session
lastInputTokens?: number; // Input tokens from the last AI request
imagesNotSupported?: boolean; // Track if this session's model doesn't support images
lastFinishReason?: string | null; // Last finish reason from AI generation
}
export interface SessionManagerEvents {
sessionCreated: (projectId: string) => void;
sessionDeleted: (projectId: string) => void;
messageAdded: (projectId: string, message: AIMessage) => void;
displayMessageAdded: (projectId: string, message: DisplayMessage) => void;
displayMessagesPrepended: (projectId: string, messages: DisplayMessage[]) => void;
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (projectId: string, isLoading: boolean) => void;
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
costUpdated: (projectId: string, totalCost: number) => void;
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
fileChanged: (projectId: string, filePath: string) => void;
finishReasonChanged: (projectId: string, finishReason: string | null) => void;
}
/**
@@ -66,7 +82,7 @@ export class SessionManager {
private getSettings: () => { providers: AIProvider[]; imageModel?: string };
private getConfig: () => AppConfig;
private getDefaultConfig: () => AppConfig;
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: Decimal; completion: Decimal } }>;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
constructor(
@@ -75,7 +91,7 @@ export class SessionManager {
getSettings: () => { providers: AIProvider[]; imageModel?: string },
getConfig: () => AppConfig,
getDefaultConfig: () => AppConfig,
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: Decimal; completion: Decimal } }>,
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
) {
this.fs = fs;
@@ -93,7 +109,7 @@ export class SessionManager {
}
/**
* Create a new session for a project
* Create a new session for a project (lazy loading - only loads most recent session)
*/
async loadSession(
projectId: string,
@@ -101,18 +117,43 @@ export class SessionManager {
customTools: Record<string, Tool<unknown>>,
maxSteps?: number
): Promise<SessionState> {
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
const messages: AIMessage[] = [];
const displayMessages: DisplayMessage[] = [];
let sessionName = DotAI.generateSessionName();
let availableSessionNames: string[] = [];
let loadedSessionCount = 0;
let lastFinishReason: string | null | undefined;
// Try to load existing history
// Try to load existing history (lazy - only load last session)
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
sessionName = lastSession.sessionName;
// Get all available session names (fast - no content loading)
availableSessionNames = await dotAI.listSessionNames();
if (availableSessionNames.length > 0) {
// Only load the most recent session
const lastSessionName = availableSessionNames[availableSessionNames.length - 1];
const lastSessionMessages = await dotAI.readSessionHistory(lastSessionName);
if (lastSessionMessages.length > 0) {
// Add messages with sessionId annotation
for (const msg of lastSessionMessages) {
displayMessages.push({
...msg as AIMessage,
sessionId: lastSessionName,
});
}
messages.push(...lastSessionMessages as AIMessage[]);
sessionName = lastSessionName;
loadedSessionCount = 1;
}
}
// Load last finish reason
lastFinishReason = await dotAI.readFinishReason();
} catch (error) {
console.warn('Failed to load session history:', error);
}
@@ -123,20 +164,33 @@ export class SessionManager {
customTools,
maxSteps,
isLoading: false,
isLoadingMoreHistory: false,
lastActivity: new Date(),
totalCost: 0,
lastInputTokens: 0,
lastFinishReason,
...this.sessions.get(projectId),
messages,
displayMessages,
availableSessionNames,
loadedSessionCount,
sessionName,
};
// Update session configuration
session.projectId = projectId;
session.tools = tools;
session.customTools = customTools;
session.maxSteps = maxSteps;
// Update messages from loaded history if not already set by an existing session
if (!this.sessions.has(projectId)) {
session.messages = messages;
session.displayMessages = displayMessages;
session.availableSessionNames = availableSessionNames;
session.loadedSessionCount = loadedSessionCount;
session.sessionName = sessionName;
}
this.sessions.set(projectId, session);
@@ -178,11 +232,69 @@ export class SessionManager {
const session = this.sessions.get(projectId);
if (!session) return;
// Add to current session messages (for AI prompts)
session.messages.push(message);
// Also add to display messages with session ID annotation (for UI)
const displayMessage: DisplayMessage = { ...message, sessionId: session.sessionName };
session.displayMessages.push(displayMessage);
session.lastActivity = new Date();
await this.saveSessionHistory(projectId);
this.emit('messageAdded', projectId, message);
this.emit('displayMessageAdded', projectId, displayMessage);
}
/**
* Check if there are more historical sessions to load
*/
hasMoreHistory(projectId: string): boolean {
const session = this.sessions.get(projectId);
if (!session) return false;
return session.loadedSessionCount < session.availableSessionNames.length;
}
/**
* Load the next older session and prepend to displayMessages
*/
async loadOlderSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
if (!session || !this.hasMoreHistory(projectId) || session.isLoadingMoreHistory) return;
session.isLoadingMoreHistory = true;
this.emit('loadingMoreHistoryChanged', projectId, true);
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
// Get the next older session (counting from the end)
const nextIndex = session.availableSessionNames.length - session.loadedSessionCount - 1;
if (nextIndex < 0) return;
const olderSessionName = session.availableSessionNames[nextIndex];
const olderMessages = await dotAI.readSessionHistory(olderSessionName);
if (olderMessages.length > 0) {
// Create display messages with sessionId
const newDisplayMessages: DisplayMessage[] = olderMessages.map(msg => ({
...msg as AIMessage,
sessionId: olderSessionName,
}));
// Prepend to displayMessages
session.displayMessages = [...newDisplayMessages, ...session.displayMessages];
session.loadedSessionCount++;
this.emit('displayMessagesPrepended', projectId, newDisplayMessages);
}
} catch (error) {
console.warn('Failed to load older session:', error);
} finally {
session.isLoadingMoreHistory = false;
this.emit('loadingMoreHistoryChanged', projectId, false);
}
}
/**
@@ -289,13 +401,14 @@ export class SessionManager {
baseURL: provider.baseURL,
};
// Get imageModel from settings
const cwd = `${config.fsPathProjects}/${projectId}`;
const commits = await this.git.log({ dir: cwd });
const settings = this.getSettings();
const systemPrompt = await makeSystemPrompt({
cwd: `${config.fsPathProjects}/${projectId}`,
cwd,
fs: this.fs,
mode: "agent",
mode: commits.length > 1 ? "agent" : "init",
tools: Object.values(session.tools),
config,
defaultConfig,
@@ -440,7 +553,7 @@ export class SessionManager {
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
let finishReason: string | null = null;
// Process the stream
@@ -481,20 +594,29 @@ export class SessionManager {
const toolCallDelta = delta.tool_calls[i];
const index = toolCallDelta.index ?? i; // Fix for Gemini models
accumulatedToolCalls[index] ??= {
id: '',
type: 'function',
function: { name: '', arguments: '' }
};
let toolCall = accumulatedToolCalls.get(index);
if (!toolCall) {
toolCall = {
id: '',
type: 'function',
function: { name: '', arguments: '' },
};
}
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
accumulatedToolCalls.set(index, toolCall);
}
if (session.streamingMessage) {
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
const sortedToolCalls = [...accumulatedToolCalls.entries()]
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
session.streamingMessage.tool_calls = sortedToolCalls;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
@@ -518,7 +640,7 @@ export class SessionManager {
}
// Fix tool calls with empty arguments or names
for (const toolCall of accumulatedToolCalls) {
for (const toolCall of accumulatedToolCalls.values()) {
if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}';
@@ -539,11 +661,11 @@ export class SessionManager {
role: 'assistant',
content: accumulatedContent,
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
};
// Check if the assistant message is empty (no content, reasoning, or tool calls)
if (isEmptyMessage(assistantMessage)) {
if (isEmptyMessage(assistantMessage) && finishReason !== 'stop') {
console.error('Empty assistant message detected', {
projectId,
providerModel,
@@ -565,8 +687,8 @@ export class SessionManager {
}
// Handle tool calls
if (accumulatedToolCalls?.length) {
for (const toolCall of accumulatedToolCalls) {
if (accumulatedToolCalls?.size) {
for (const toolCall of accumulatedToolCalls.values()) {
if (toolCall.type !== 'function') continue;
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
@@ -628,6 +750,11 @@ export class SessionManager {
}
}
// Update and save the finish reason
session.lastFinishReason = finishReason;
this.emit('finishReasonChanged', projectId, finishReason);
await this.saveFinishReason(projectId, finishReason);
// Check if we should stop
if (finishReason === 'stop') {
break;
@@ -641,6 +768,11 @@ export class SessionManager {
return; // User cancelled
}
// Log unexpected TypeErrors to Sentry for investigation
if (error instanceof TypeError) {
getSentryInstance()?.captureException(error);
}
// Re-throw service errors to be handled at the UI level
throw error;
} finally {
@@ -670,7 +802,7 @@ export class SessionManager {
}
/**
* Start a new session (clear messages but keep configuration)
* Start a new session (clear AI messages but keep display history)
*/
async startNewSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
@@ -678,15 +810,21 @@ export class SessionManager {
this.stopGeneration(projectId);
// Generate new session name - new messages will automatically get this sessionId
const newSessionName = DotAI.generateSessionName();
// Clear only the AI prompt messages (not display messages)
session.messages = [];
session.streamingMessage = undefined;
session.sessionName = DotAI.generateSessionName();
session.sessionName = newSessionName;
session.lastActivity = new Date();
session.totalCost = 0;
session.lastInputTokens = 0;
session.lastFinishReason = null;
this.emit('costUpdated', projectId, 0);
this.emit('contextUsageUpdated', projectId, 0);
this.emit('finishReasonChanged', projectId, null);
}
/**
@@ -773,6 +911,19 @@ export class SessionManager {
}
}
/**
* Save finish reason to file
*/
private async saveFinishReason(projectId: string, finishReason: string | null): Promise<void> {
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
await dotAI.writeFinishReason(finishReason);
} catch (error) {
console.warn('Failed to save finish reason:', error);
}
}
/**
* Accumulate request cost to the project's total cost file
*/
+41 -4
View File
@@ -58,14 +58,51 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
= openai.chat.completions.create.bind(openai.chat.completions);
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// OpenRouter usage accounting
// https://openrouter.ai/docs/use-cases/usage-accounting
if (provider.id === 'openrouter') {
// OpenRouter-specific hacks
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
// Usage accounting field to get token usage and cost per request
// https://openrouter.ai/docs/use-cases/usage-accounting
(body as { usage?: { include?: boolean } }).usage = { include: true };
// Prompt caching for Claude models
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
if (body.model.startsWith("anthropic/")) {
// First normalize the message history to use content blocks
body.messages = structuredClone(body.messages);
body.messages = body.messages.map((m) => {
if (m.role !== "function" && typeof m.content === "string") {
return { ...m, content: [{ type: "text", text: m.content }] };
} else {
return m;
}
});
const systemMessage = body.messages.find((m) => m.role === "system");
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
const lastTwoMessages = nonSystemMessages.slice(-2);
if (systemMessage) {
addCacheControl(systemMessage);
}
for (const msg of lastTwoMessages) {
addCacheControl(msg);
}
}
}
return createCompletion(body, options);
}) as typeof createCompletion;
return openai;
}
}
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
if (Array.isArray(msg.content)) {
const lastTextBlock = msg.content.findLast((b) => b.type === "text");
if (lastTextBlock) {
(lastTextBlock as { cache_control?: { type: "ephemeral" } })
.cache_control = { type: "ephemeral" };
}
}
};
+8
View File
@@ -23,6 +23,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "opencode",
name: "OpenCode Zen",
baseURL: "https://opencode.ai/zen/v1",
apiKeysURL: "https://opencode.ai/auth",
tosURL: "https://opencode.ai/legal/terms-of-service",
proxy: true,
},
{
id: "ppq",
name: "PayPerQ",
+3 -1
View File
@@ -62,7 +62,7 @@ export function createRepositoryAnnouncementEvent(
): EventTemplate {
// Build tags array per NIP-34
const tags: string[][] = [
['d', data.repoId.trim()], // Required: repository identifier
['d', data.repoId], // Required: repository identifier
];
if (data.name?.trim()) {
@@ -110,6 +110,8 @@ export function createRepositoryAnnouncementEvent(
tags.push(['r', data.earliestCommit.trim(), 'euc']);
}
tags.push(['alt', `git repository: ${data.repoId}`]);
// Create repository announcement event (kind 30617)
return {
kind: 30617,
+210
View File
@@ -0,0 +1,210 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { MockFS } from '@/test/MockFS';
import { Git } from '@/lib/git';
import { GitLogCommand } from './log';
import type { NPool, NostrEvent } from '@nostrify/nostrify';
const createMockNostr = (): NPool => {
const events: NostrEvent[] = [];
return {
req: vi.fn(),
query: vi.fn(async () => events),
event: vi.fn(async (event: NostrEvent) => { events.push(event); }),
group: vi.fn().mockReturnValue({ query: vi.fn(async () => events) }),
relay: vi.fn(),
relays: new Map(),
close: vi.fn(),
} as unknown as NPool;
};
describe('GitLogCommand', () => {
let fs: MockFS;
let git: Git;
let logCommand: GitLogCommand;
beforeEach(async () => {
fs = new MockFS();
git = new Git({
fs,
nostr: createMockNostr(),
});
logCommand = new GitLogCommand({ git, fs });
// Initialize a git repository
await git.init({ dir: '/test-repo' });
// Configure git
await git.setConfig({ dir: '/test-repo', path: 'user.name', value: 'Test User' });
await git.setConfig({ dir: '/test-repo', path: 'user.email', value: '[email protected]' });
// Create some commits
await fs.writeFile('/test-repo/file1.txt', 'content 1');
await git.add({ dir: '/test-repo', filepath: 'file1.txt' });
await git.commit({
dir: '/test-repo',
message: 'First commit',
});
await fs.writeFile('/test-repo/file2.txt', 'content 2');
await git.add({ dir: '/test-repo', filepath: 'file2.txt' });
await git.commit({
dir: '/test-repo',
message: 'Second commit',
});
await fs.writeFile('/test-repo/file3.txt', 'content 3');
await git.add({ dir: '/test-repo', filepath: 'file3.txt' });
await git.commit({
dir: '/test-repo',
message: 'Third commit',
});
});
it('should show all commits by default (no limit)', async () => {
const result = await logCommand.execute([], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('First commit');
expect(result.stdout).toContain('Second commit');
expect(result.stdout).toContain('Third commit');
});
it('should limit commits with -n flag', async () => {
const result = await logCommand.execute(['-n', '1'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Third commit');
expect(result.stdout).not.toContain('Second commit');
expect(result.stdout).not.toContain('First commit');
});
it('should limit commits with -n= syntax', async () => {
const result = await logCommand.execute(['-n=2'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Third commit');
expect(result.stdout).toContain('Second commit');
expect(result.stdout).not.toContain('First commit');
});
it('should limit commits with --max-count flag', async () => {
const result = await logCommand.execute(['--max-count', '2'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Third commit');
expect(result.stdout).toContain('Second commit');
expect(result.stdout).not.toContain('First commit');
});
it('should limit commits with -<number> syntax', async () => {
const result = await logCommand.execute(['-2'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Third commit');
expect(result.stdout).toContain('Second commit');
expect(result.stdout).not.toContain('First commit');
});
it('should format with --oneline', async () => {
const result = await logCommand.execute(['--oneline'], '/test-repo');
expect(result.exitCode).toBe(0);
// Oneline format should have short hash and message on same line
const lines = result.stdout.trim().split('\n');
expect(lines.length).toBe(3);
expect(lines[0]).toMatch(/^[0-9a-f]{7} Third commit$/);
expect(lines[1]).toMatch(/^[0-9a-f]{7} Second commit$/);
expect(lines[2]).toMatch(/^[0-9a-f]{7} First commit$/);
});
it('should format with --format=oneline', async () => {
const result = await logCommand.execute(['--format=oneline'], '/test-repo');
expect(result.exitCode).toBe(0);
const lines = result.stdout.trim().split('\n');
expect(lines.length).toBe(3);
expect(lines[0]).toMatch(/^[0-9a-f]{7} Third commit$/);
});
it('should format with --format=short', async () => {
const result = await logCommand.execute(['--format=short'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('commit');
expect(result.stdout).toContain('Author:');
expect(result.stdout).not.toContain('Date:'); // Short format doesn't include date
});
it('should format with --format=full', async () => {
const result = await logCommand.execute(['--format=full'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('commit');
expect(result.stdout).toContain('Author:');
expect(result.stdout).toContain('Date:');
});
it('should format with --format=fuller', async () => {
const result = await logCommand.execute(['--format=fuller'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('commit');
expect(result.stdout).toContain('Author:');
expect(result.stdout).toContain('AuthorDate:');
});
it('should format with --format=raw', async () => {
const result = await logCommand.execute(['--format=raw'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('commit');
expect(result.stdout).toContain('author');
expect(result.stdout).toMatch(/author .+ <.+> \d+ \+0000/);
});
it('should show graph with --graph', async () => {
const result = await logCommand.execute(['--graph', '--oneline'], '/test-repo');
expect(result.exitCode).toBe(0);
const lines = result.stdout.trim().split('\n');
expect(lines[0]).toMatch(/^\* [0-9a-f]{7} Third commit$/);
});
it('should combine --graph with full format', async () => {
const result = await logCommand.execute(['--graph'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('* commit');
});
it('should error when not in a git repository', async () => {
const result = await logCommand.execute([], '/not-a-repo');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('not a git repository');
});
it('should show more than 50 commits when no limit is specified', async () => {
// Create 60 commits
for (let i = 4; i <= 60; i++) {
await fs.writeFile(`/test-repo/file${i}.txt`, `content ${i}`);
await git.add({ dir: '/test-repo', filepath: `file${i}.txt` });
await git.commit({
dir: '/test-repo',
message: `Commit ${i}`,
});
}
const result = await logCommand.execute(['--oneline'], '/test-repo');
expect(result.exitCode).toBe(0);
const lines = result.stdout.trim().split('\n');
expect(lines.length).toBe(60); // Should show all 60 commits, not just 50
expect(result.stdout).toContain('Commit 60');
expect(result.stdout).toContain('Commit 1');
});
it('should respect limit even with many commits', async () => {
// Create 60 commits
for (let i = 4; i <= 60; i++) {
await fs.writeFile(`/test-repo/file${i}.txt`, `content ${i}`);
await git.add({ dir: '/test-repo', filepath: `file${i}.txt` });
await git.commit({
dir: '/test-repo',
message: `Commit ${i}`,
});
}
const result = await logCommand.execute(['-10', '--oneline'], '/test-repo');
expect(result.exitCode).toBe(0);
const lines = result.stdout.trim().split('\n');
expect(lines.length).toBe(10); // Should show only 10 commits
expect(result.stdout).toContain('Commit 60');
expect(result.stdout).not.toContain('Commit 1');
});
});
+161 -48
View File
@@ -7,7 +7,7 @@ import type { Git } from "../../git";
export class GitLogCommand implements GitSubcommand {
name = 'log';
description = 'Show commit logs';
usage = 'git log [--oneline] [--graph] [-n <number>] [<since>..<until>]';
usage = 'git log [--oneline] [--graph] [--format=<format>] [-n <number>] [--all] [<ref>]';
private git: Git;
private fs: JSRuntimeFS;
@@ -26,23 +26,27 @@ export class GitLogCommand implements GitSubcommand {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { options, limit } = this.parseArgs(args);
const { options, limit, ref } = this.parseArgs(args);
try {
const commits = await this.git.log({
dir: cwd,
depth: limit,
});
const logOptions: { dir: string; depth?: number; ref?: string } = { dir: cwd };
if (limit !== undefined) {
logOptions.depth = limit;
}
if (ref !== undefined) {
logOptions.ref = ref;
}
const commits = await this.git.log(logOptions);
if (commits.length === 0) {
return createErrorResult('fatal: your current branch does not have any commits yet');
}
if (options.oneline) {
return this.formatOnelineLog(commits, cwd);
} else {
return this.formatFullLog(commits, options.graph, cwd);
}
// Determine format based on options
const format = options.format || (options.oneline ? 'oneline' : 'full');
return this.formatLog(commits, format, options.graph, cwd);
} catch (error) {
if (error instanceof Error && error.message.includes('does not exist')) {
@@ -57,11 +61,16 @@ export class GitLogCommand implements GitSubcommand {
}
private parseArgs(args: string[]): {
options: { oneline: boolean; graph: boolean };
limit: number
options: { oneline: boolean; graph: boolean; format?: string };
limit: number | undefined;
ref?: string;
} {
const options = { oneline: false, graph: false };
let limit = 50; // Default limit
const options: { oneline: boolean; graph: boolean; format?: string } = {
oneline: false,
graph: false
};
let limit: number | undefined = undefined; // No default limit - show all commits
let ref: string | undefined = undefined;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
@@ -70,6 +79,18 @@ export class GitLogCommand implements GitSubcommand {
options.oneline = true;
} else if (arg === '--graph') {
options.graph = true;
} else if (arg === '--all') {
// --all is not directly supported by isomorphic-git log
// We'll just ignore it for now
} else if (arg === '--format' || arg === '--pretty') {
if (i + 1 < args.length) {
options.format = args[i + 1];
i++; // Skip next argument
}
} else if (arg.startsWith('--format=')) {
options.format = arg.substring(9);
} else if (arg.startsWith('--pretty=')) {
options.format = arg.substring(9);
} else if (arg === '-n' || arg === '--max-count') {
if (i + 1 < args.length) {
const num = parseInt(args[i + 1], 10);
@@ -94,58 +115,150 @@ export class GitLogCommand implements GitSubcommand {
if (!isNaN(num) && num > 0) {
limit = num;
}
} else if (!arg.startsWith('-')) {
// Treat as a ref (branch name, commit hash, etc.)
ref = arg;
}
}
return { options, limit };
return { options, limit, ref };
}
private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>, _cwd: string): ShellCommandResult {
const lines: string[] = [];
for (const commit of commits) {
const shortHash = commit.oid.substring(0, 7);
const message = commit.commit.message.split('\n')[0]; // First line only
lines.push(`${shortHash} ${message}`);
}
return createSuccessResult(lines.join('\n') + '\n');
}
private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean, _cwd: string): ShellCommandResult {
private formatLog(
commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }>,
format: string,
showGraph: boolean,
_cwd: string
): ShellCommandResult {
const lines: string[] = [];
for (let i = 0; i < commits.length; i++) {
const commit = commits[i];
const isLast = i === commits.length - 1;
const graphPrefix = showGraph ? '* ' : '';
if (showGraph) {
lines.push('* commit ' + commit.oid);
} else {
lines.push('commit ' + commit.oid);
}
// Format based on the specified format
switch (format) {
case 'oneline':
lines.push(this.formatOneline(commit, graphPrefix));
break;
// Author information
const author = commit.commit.author;
const authorDate = new Date(author.timestamp * 1000);
const authorDateStr = authorDate.toUTCString();
case 'short':
lines.push(this.formatShort(commit, graphPrefix));
if (!isLast) lines.push('');
break;
lines.push(`Author: ${author.name} <${author.email}>`);
lines.push(`Date: ${authorDateStr}`);
lines.push('');
case 'medium':
case 'full':
default:
lines.push(this.formatFull(commit, graphPrefix));
if (!isLast) lines.push('');
break;
// Commit message (indented)
const messageLines = commit.commit.message.split('\n');
for (const messageLine of messageLines) {
lines.push(` ${messageLine}`);
}
case 'fuller':
lines.push(this.formatFuller(commit, graphPrefix));
if (!isLast) lines.push('');
break;
if (!isLast) {
lines.push('');
case 'raw':
lines.push(this.formatRaw(commit));
if (!isLast) lines.push('');
break;
}
}
return createSuccessResult(lines.join('\n') + '\n');
}
private formatOneline(commit: { oid: string; commit: { message: string } }, graphPrefix: string): string {
const shortHash = commit.oid.substring(0, 7);
const message = commit.commit.message.split('\n')[0]; // First line only
return `${graphPrefix}${shortHash} ${message}`;
}
private formatShort(commit: { oid: string; commit: { message: string; author: { name: string; email: string } } }, graphPrefix: string): string {
const lines: string[] = [];
const shortHash = commit.oid.substring(0, 7);
lines.push(`${graphPrefix}commit ${shortHash}`);
lines.push(`Author: ${commit.commit.author.name} <${commit.commit.author.email}>`);
lines.push('');
const messageLines = commit.commit.message.split('\n');
for (const messageLine of messageLines) {
lines.push(` ${messageLine}`);
}
return lines.join('\n');
}
private formatFull(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }, graphPrefix: string): string {
const lines: string[] = [];
lines.push(`${graphPrefix}commit ${commit.oid}`);
const author = commit.commit.author;
const authorDate = new Date(author.timestamp * 1000);
const authorDateStr = authorDate.toUTCString();
lines.push(`Author: ${author.name} <${author.email}>`);
lines.push(`Date: ${authorDateStr}`);
lines.push('');
const messageLines = commit.commit.message.split('\n');
for (const messageLine of messageLines) {
lines.push(` ${messageLine}`);
}
return lines.join('\n');
}
private formatFuller(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }, graphPrefix: string): string {
const lines: string[] = [];
lines.push(`${graphPrefix}commit ${commit.oid}`);
const author = commit.commit.author;
const authorDate = new Date(author.timestamp * 1000);
lines.push(`Author: ${author.name} <${author.email}>`);
lines.push(`AuthorDate: ${authorDate.toUTCString()}`);
// Include committer info if available
if (commit.commit.committer) {
const committer = commit.commit.committer;
const commitDate = new Date(committer.timestamp * 1000);
lines.push(`Commit: ${committer.name} <${committer.email}>`);
lines.push(`CommitDate: ${commitDate.toUTCString()}`);
}
lines.push('');
const messageLines = commit.commit.message.split('\n');
for (const messageLine of messageLines) {
lines.push(` ${messageLine}`);
}
return lines.join('\n');
}
private formatRaw(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }): string {
const lines: string[] = [];
lines.push(`commit ${commit.oid}`);
const author = commit.commit.author;
lines.push(`author ${author.name} <${author.email}> ${author.timestamp} +0000`);
if (commit.commit.committer) {
const committer = commit.commit.committer;
lines.push(`committer ${committer.name} <${committer.email}> ${committer.timestamp} +0000`);
}
lines.push('');
lines.push(commit.commit.message);
return lines.join('\n');
}
}
+40 -42
View File
@@ -40,7 +40,7 @@ describe('GitShowCommand', () => {
throw new Error(`Reference ${ref} does not exist`);
}
}),
// Mock readCommit to return commit objects
readCommit: vi.fn().mockImplementation(async ({ oid }) => {
switch (oid) {
@@ -136,7 +136,7 @@ describe('GitShowCommand', () => {
throw new Error(`Commit ${oid} not found`);
}
}),
// Mock log to return commit history
log: vi.fn().mockImplementation(async ({ ref }) => {
switch (ref) {
@@ -232,7 +232,7 @@ describe('GitShowCommand', () => {
return [];
}
}),
// Mock readTree to return file trees
readTree: vi.fn().mockImplementation(async ({ oid }) => {
switch (oid) {
@@ -288,7 +288,7 @@ describe('GitShowCommand', () => {
return { oid, tree: [] };
}
}),
// Mock readBlob to return file contents
readBlob: vi.fn().mockImplementation(async ({ filepath, oid }) => {
// Return different content based on blob ID or filepath
@@ -309,7 +309,7 @@ describe('GitShowCommand', () => {
} else if (filepath === 'binary.bin') {
return { blob: new TextEncoder().encode(binaryFileContent), oid: 'blob-binary' };
}
// Default case
return { blob: new TextEncoder().encode('default content'), oid: 'default-blob' };
}),
@@ -324,7 +324,7 @@ describe('GitShowCommand', () => {
it('should show basic commit information', async () => {
const result = await showCommand.execute(['simple-commit'], mockPwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('commit simple-commit');
expect(result.stdout).toContain('Author: Test User');
@@ -333,10 +333,10 @@ describe('GitShowCommand', () => {
it('should handle initial commits properly', async () => {
const result = await showCommand.execute(['initial-commit'], mockPwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Initial commit');
// The implementation should detect this is an initial commit
expect(result.stdout).toContain('initial commit');
});
@@ -344,38 +344,38 @@ describe('GitShowCommand', () => {
it('should resolve HEAD~1 correctly', async () => {
// First, check that the implementation correctly resolves HEAD~1
const result = await showCommand.execute(['HEAD~1'], mockPwd);
// Verify that resolveRef was called with HEAD
expect(mockGit.resolveRef).toHaveBeenCalledWith({
dir: mockPwd,
ref: 'HEAD',
});
// Verify that readCommit was called with the resolved HEAD commit
expect(mockGit.readCommit).toHaveBeenCalledWith({
dir: mockPwd,
oid: 'merge-commit',
});
// Check that the result contains the parent commit info
expect(result.stdout).toContain('Simple changes');
});
it('should resolve HEAD^2 correctly', async () => {
const result = await showCommand.execute(['HEAD^2'], mockPwd);
// Verify that resolveRef was called with HEAD
expect(mockGit.resolveRef).toHaveBeenCalledWith({
dir: mockPwd,
ref: 'HEAD',
});
// Verify that readCommit was called with the resolved HEAD commit
expect(mockGit.readCommit).toHaveBeenCalledWith({
dir: mockPwd,
oid: 'merge-commit',
});
// Check that the result contains the second parent commit info
expect(result.stdout).toContain('Branch commit');
});
@@ -383,10 +383,10 @@ describe('GitShowCommand', () => {
it('should show file changes between commits', async () => {
// This test verifies that the diff output includes file changes
// We need to ensure our mocks provide the necessary data for the diff algorithm
// Reset the call counts
vi.clearAllMocks();
// Force the readTree mock to return different trees for parent and current commit
vi.mocked(mockGit.readTree!).mockImplementation(async ({ oid }) => {
if (oid === 'simple-commit' || oid === 'simple-tree') {
@@ -408,33 +408,33 @@ describe('GitShowCommand', () => {
}
return { oid, tree: [] };
});
// Execute the command
const result = await showCommand.execute(['simple-commit'], mockPwd);
// Check that the command output contains the commit message
expect(result.stdout).toContain('Simple changes');
// Verify that the necessary methods were called
expect(mockGit.readTree).toHaveBeenCalled();
// Check that the output mentions the files that were changed
expect(result.stdout).toContain('file1.txt');
expect(result.stdout).toContain('file3.txt');
// Check for file status indicators
expect(result.stdout).toContain('added');
expect(result.stdout).toContain('modified');
});
it('should show line-by-line diffs with proper formatting', async () => {
// Reset the call counts
vi.clearAllMocks();
// Set up specific file content for diffing
const oldContent = 'line 1\nline 2\nline 3\nline 4\nline 5\n';
const newContent = 'line 1\nmodified line 2\nline 3\nnew line\nline 5\n';
// Mock log to return a commit with a parent
vi.mocked(mockGit.log!).mockImplementation(async ({ ref }) => {
if (ref === 'diff-test-commit') {
@@ -462,7 +462,7 @@ describe('GitShowCommand', () => {
}
return [];
});
// Mock readCommit for the parent commit
vi.mocked(mockGit.readCommit!).mockImplementation(async ({ oid }) => {
if (oid === 'diff-test-commit') {
@@ -512,7 +512,7 @@ describe('GitShowCommand', () => {
}
throw new Error(`Commit ${oid} not found`);
});
// Force the readTree mock to return trees with different content
vi.mocked(mockGit.readTree!).mockImplementation(async ({ oid }) => {
if (oid === 'diff-test-tree') {
@@ -546,7 +546,7 @@ describe('GitShowCommand', () => {
}
return { oid, tree: [] };
});
// Mock readBlob to return our test content
vi.mocked(mockGit.readBlob!).mockImplementation(async ({ filepath, oid }) => {
if (filepath === 'diff-test.txt') {
@@ -558,7 +558,7 @@ describe('GitShowCommand', () => {
}
return { blob: new TextEncoder().encode('default content'), oid: 'default-blob' };
});
// Mock resolveRef to handle our test commit
vi.mocked(mockGit.resolveRef!).mockImplementation(async ({ ref }) => {
if (ref === 'diff-test-commit') {
@@ -566,46 +566,44 @@ describe('GitShowCommand', () => {
}
throw new Error(`Reference ${ref} does not exist`);
});
// Execute the command
const result = await showCommand.execute(['diff-test-commit'], mockPwd);
// Debug output
console.log('Test output:', result.stdout);
// Check for unified diff format with hunk headers
expect(result.stdout).toMatch(/@@ -\d+,\d+ \+\d+,\d+ @@/);
// Check for context lines (unchanged lines)
expect(result.stdout).toContain(' line 1');
expect(result.stdout).toContain(' line 3');
expect(result.stdout).toContain(' line 5');
// Check for removed lines (with - prefix and red color)
// Check for removed lines (with - prefix)
expect(result.stdout).toContain('-line 2');
expect(result.stdout).toContain('\x1b[31m'); // Red color
// Check for added lines (with + prefix and green color)
// Check for added lines (with + prefix)
expect(result.stdout).toContain('+modified line 2');
expect(result.stdout).toContain('+new line');
expect(result.stdout).toContain('\x1b[32m'); // Green color
// Verify that readBlob was called to get file contents for diffing
expect(mockGit.readBlob).toHaveBeenCalled();
});
it('should return an error for invalid references', async () => {
const result = await showCommand.execute(['non-existent-ref'], mockPwd);
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('bad revision');
});
it('should return an error when not in a git repository', async () => {
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
const result = await showCommand.execute([], mockPwd);
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('not a git repository');
});
+92 -92
View File
@@ -64,38 +64,38 @@ export class GitShowCommand implements GitSubcommand {
if (tildeMatch) {
const [, baseRef, steps] = tildeMatch;
const numSteps = parseInt(steps, 10);
if (numSteps === 0) {
// ~0 is the commit itself
return this.resolveCommitRef(baseRef, cwd);
}
// First resolve the base reference
const baseCommit = await this.resolveCommitRef(baseRef, cwd);
if (!baseCommit) {
throw new Error(`Could not resolve base reference: ${baseRef}`);
}
// Walk back N steps in history
return this.walkBackNCommits(baseCommit, numSteps, cwd);
}
// Handle HEAD^N syntax (Nth parent)
const caretMatch = ref.match(/^(.+)\^(\d*)$/);
if (caretMatch) {
const [, baseRef, parentNum] = caretMatch;
const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent
// First resolve the base reference
const baseCommit = await this.resolveCommitRef(baseRef, cwd);
if (!baseCommit) {
throw new Error(`Could not resolve base reference: ${baseRef}`);
}
// Get the specified parent
return this.getNthParent(baseCommit, parentIndex, cwd);
}
// Handle simple reference (direct resolution)
try {
return await this.git.resolveRef({
@@ -113,37 +113,37 @@ export class GitShowCommand implements GitSubcommand {
return null;
}
}
/**
* Walk back N commits from the given commit
*/
private async walkBackNCommits(startCommit: string, steps: number, cwd: string): Promise<string | null> {
try {
let currentCommit = startCommit;
for (let i = 0; i < steps; i++) {
// Get the commit object
const commit = await this.git.readCommit({
dir: cwd,
oid: currentCommit,
});
// Check if the commit has parents
if (!commit.commit.parent || commit.commit.parent.length === 0) {
throw new Error(`Commit ${currentCommit.substring(0, 7)} has no parent, cannot go back further`);
}
// Move to the first parent
currentCommit = commit.commit.parent[0];
}
return currentCommit;
} catch (error) {
console.error('Error walking back commits:', error);
return null;
}
}
/**
* Get the Nth parent of the given commit
*/
@@ -154,17 +154,17 @@ export class GitShowCommand implements GitSubcommand {
dir: cwd,
oid: commit,
});
// Check if the commit has parents
if (!commitObj.commit.parent || commitObj.commit.parent.length === 0) {
throw new Error(`Commit ${commit.substring(0, 7)} has no parents`);
}
// Check if the requested parent index is valid
if (parentIndex < 0 || parentIndex >= commitObj.commit.parent.length) {
throw new Error(`Commit ${commit.substring(0, 7)} does not have a parent at index ${parentIndex + 1}`);
}
// Return the specified parent
return commitObj.commit.parent[parentIndex];
} catch (error) {
@@ -215,7 +215,7 @@ export class GitShowCommand implements GitSubcommand {
// If there's no parent, this is the first commit - show the entire tree
if (!commit.commit.parent || commit.commit.parent.length === 0) {
lines.push('(This is the initial commit)');
// Get the tree for this commit
const tree = await this.git.readTree({
dir: cwd,
@@ -232,18 +232,18 @@ export class GitShowCommand implements GitSubcommand {
} else {
// Get the parent commit to compare with
const parentCommit = commit.commit.parent[0];
// Get the trees for both commits
const parentTree = await this.git.readTree({
dir: cwd,
oid: parentCommit,
});
const commitTree = await this.git.readTree({
dir: cwd,
oid: commit.oid,
});
// Define types for tree entries
interface TreeEntry {
mode: string;
@@ -251,33 +251,33 @@ export class GitShowCommand implements GitSubcommand {
oid: string;
type?: string;
}
// Compare the trees manually
const parentFiles = new Map<string, TreeEntry>();
const commitFiles = new Map<string, TreeEntry>();
// Populate the maps
for (const entry of parentTree.tree) {
parentFiles.set(entry.path, entry as TreeEntry);
}
for (const entry of commitTree.tree) {
commitFiles.set(entry.path, entry as TreeEntry);
}
type ChangeType = 'add' | 'modify' | 'delete';
interface Change {
type: ChangeType;
path: string;
}
const changes: Change[] = [];
// Helper function to check if a path is a directory
const isDirectory = (entry: TreeEntry): boolean => {
return entry.mode === '040000';
};
// Helper function to recursively list files in a directory
const listFilesInDirectory = async (oid: string, prefix: string = ''): Promise<Map<string, TreeEntry>> => {
const result = new Map<string, TreeEntry>();
@@ -286,11 +286,11 @@ export class GitShowCommand implements GitSubcommand {
dir: cwd,
oid,
});
for (const entry of tree.tree) {
const entryWithType = entry as TreeEntry;
const path = prefix ? `${prefix}/${entry.path}` : entry.path;
if (isDirectory(entryWithType)) {
// Recursively list files in subdirectory
const subFiles = await listFilesInDirectory(entry.oid, path);
@@ -308,7 +308,7 @@ export class GitShowCommand implements GitSubcommand {
}
return result;
};
// Expand directory entries to include all files within them
const expandDirectories = async (): Promise<void> => {
// Process parent files
@@ -323,7 +323,7 @@ export class GitShowCommand implements GitSubcommand {
}
}
}
// Process commit files
for (const [path, entry] of [...commitFiles.entries()]) {
if (isDirectory(entry)) {
@@ -337,10 +337,10 @@ export class GitShowCommand implements GitSubcommand {
}
}
};
// Expand directories to get all files
await expandDirectories();
// Find added and modified files
for (const [path, entry] of commitFiles.entries()) {
const parentEntry = parentFiles.get(path);
@@ -350,14 +350,14 @@ export class GitShowCommand implements GitSubcommand {
changes.push({ type: 'modify', path });
}
}
// Find deleted files
for (const path of parentFiles.keys()) {
if (!commitFiles.has(path)) {
changes.push({ type: 'delete', path });
}
}
// Sort changes by type and path
const filteredChanges = changes.sort((a, b) => {
if (a.type !== b.type) {
@@ -367,67 +367,67 @@ export class GitShowCommand implements GitSubcommand {
}
return a.path.localeCompare(b.path);
});
if (filteredChanges.length > 0) {
// Group changes by type
const added = filteredChanges.filter(c => c.type === 'add');
const modified = filteredChanges.filter(c => c.type === 'modify');
const deleted = filteredChanges.filter(c => c.type === 'delete');
lines.push('');
// Show summary
const changeDetails: string[] = [];
if (added.length > 0) changeDetails.push(`${added.length} file${added.length !== 1 ? 's' : ''} added`);
if (modified.length > 0) changeDetails.push(`${modified.length} file${modified.length !== 1 ? 's' : ''} modified`);
if (deleted.length > 0) changeDetails.push(`${deleted.length} file${deleted.length !== 1 ? 's' : ''} deleted`);
lines.push(`\x1b[1mChanges: ${changeDetails.join(', ')}\x1b[0m`); // Bold summary line
lines.push(`Changes: ${changeDetails.join(', ')}`);
lines.push('');
// List changed files
if (added.length > 0) {
lines.push('\x1b[1mAdded files:\x1b[0m');
lines.push('Added files:');
for (const change of added) {
lines.push(` \x1b[32mnew file: ${change.path}\x1b[0m`); // Green for new files
lines.push(` new file: ${change.path}`);
}
lines.push('');
}
if (modified.length > 0) {
lines.push('\x1b[1mModified files:\x1b[0m');
lines.push('Modified files:');
for (const change of modified) {
lines.push(` \x1b[33mmodified: ${change.path}\x1b[0m`); // Yellow for modified files
lines.push(` modified: ${change.path}`);
}
lines.push('');
}
if (deleted.length > 0) {
lines.push('\x1b[1mDeleted files:\x1b[0m');
lines.push('Deleted files:');
for (const change of deleted) {
lines.push(` \x1b[31mdeleted: ${change.path}\x1b[0m`); // Red for deleted files
lines.push(` deleted: ${change.path}`);
}
lines.push('');
}
// Show actual diffs for modified files (up to 3 files to avoid excessive output)
if (modified.length > 0) {
lines.push('Diffs:');
lines.push('');
// We've already expanded directories, so all entries are files now
const filesToShow = modified.slice(0, 3); // Limit to 3 files
if (filesToShow.length === 0) {
lines.push('(Only directory structure changes, no file content to show)');
lines.push('');
}
for (const change of filesToShow) {
lines.push(`\x1b[1mdiff --git a/${change.path} b/${change.path}\x1b[0m`); // Bold
lines.push(`\x1b[1;31m--- a/${change.path}\x1b[0m`); // Bold red
lines.push(`\x1b[1;32m+++ b/${change.path}\x1b[0m`); // Bold green
lines.push(`diff --git a/${change.path} b/${change.path}`);
lines.push(`--- a/${change.path}`);
lines.push(`+++ b/${change.path}`)
try {
// Get file content from parent commit
let parentContent = '';
@@ -442,7 +442,7 @@ export class GitShowCommand implements GitSubcommand {
console.error(`Error reading parent blob for ${change.path}:`, e);
// File might not exist in parent
}
// Get file content from current commit
let currentContent = '';
try {
@@ -456,22 +456,22 @@ export class GitShowCommand implements GitSubcommand {
console.error(`Error reading current blob for ${change.path}:`, e);
// File might not exist in current commit
}
// Check if we have content to diff
if (parentContent === '' && currentContent === '') {
lines.push('(Unable to read file contents)');
lines.push('');
continue;
}
// Generate a unified diff
const parentLines = parentContent.split('\n');
const currentLines = currentContent.split('\n');
// Improved diff algorithm that generates unified diffs
const diffLines: string[] = [];
const contextSize = 3; // Number of context lines before and after changes
// Find changed regions (hunks)
const hunks: Array<{
startOld: number;
@@ -479,11 +479,11 @@ export class GitShowCommand implements GitSubcommand {
startNew: number;
endNew: number;
}> = [];
let oldIndex = 0;
let newIndex = 0;
let hunkStart: { old: number; new: number } | null = null;
// Use a simple LCS-based diff algorithm to find matching lines
const matches: boolean[] = [];
for (let i = 0; i < parentLines.length; i++) {
@@ -495,7 +495,7 @@ export class GitShowCommand implements GitSubcommand {
}
}
}
// Process the diff and identify hunks
while (oldIndex < parentLines.length || newIndex < currentLines.length) {
if (oldIndex < parentLines.length && newIndex < currentLines.length && parentLines[oldIndex] === currentLines[newIndex]) {
@@ -517,7 +517,7 @@ export class GitShowCommand implements GitSubcommand {
if (!hunkStart) {
hunkStart = { old: oldIndex, new: newIndex };
}
// Handle deletions and additions
if (oldIndex < parentLines.length && (!matches[oldIndex] || newIndex >= currentLines.length)) {
oldIndex++;
@@ -526,7 +526,7 @@ export class GitShowCommand implements GitSubcommand {
}
}
}
// Add the final hunk if there is one
if (hunkStart) {
hunks.push({
@@ -536,7 +536,7 @@ export class GitShowCommand implements GitSubcommand {
endNew: Math.min(currentLines.length, newIndex + contextSize)
});
}
// Merge overlapping hunks
for (let i = 0; i < hunks.length - 1; i++) {
if (hunks[i].endOld >= hunks[i + 1].startOld - 2 * contextSize) {
@@ -546,40 +546,40 @@ export class GitShowCommand implements GitSubcommand {
i--;
}
}
const foundDifference = hunks.length > 0;
// Generate the diff output for each hunk
for (const hunk of hunks) {
const oldSize = hunk.endOld - hunk.startOld;
const newSize = hunk.endNew - hunk.startNew;
// Add the hunk header with additional context
// Get a snippet of the surrounding code to provide context
const contextLine = hunk.startOld < parentLines.length ? parentLines[hunk.startOld] : hunk.startNew < currentLines.length ? currentLines[hunk.startNew] : '';
// Trim the context line to a reasonable length and remove leading whitespace
const trimmedContext = contextLine.trim().substring(0, 40) + (contextLine.length > 40 ? '...' : '');
// Add the hunk header with the context
diffLines.push(`\x1b[36m@@ -${hunk.startOld + 1},${oldSize} +${hunk.startNew + 1},${newSize} @@ \x1b[1;36m${trimmedContext}\x1b[0m`);
diffLines.push(`@@ -${hunk.startOld + 1},${oldSize} +${hunk.startNew + 1},${newSize} @@ ${trimmedContext}`);
// Process the hunk content with improved visual grouping
let oldLine = hunk.startOld;
let newLine = hunk.startNew;
// Track consecutive additions/deletions for better visual grouping
let inAdditionBlock = false;
let inDeletionBlock = false;
const addSeparator = () => {
if (inAdditionBlock || inDeletionBlock) {
diffLines.push(`\x1b[90m~\x1b[0m`); // Gray separator
diffLines.push(`~`);
inAdditionBlock = false;
inDeletionBlock = false;
}
};
while (oldLine < hunk.endOld || newLine < hunk.endNew) {
if (oldLine < hunk.endOld && newLine < hunk.endNew && parentLines[oldLine] === currentLines[newLine]) {
// Context line (unchanged)
@@ -594,26 +594,26 @@ export class GitShowCommand implements GitSubcommand {
deletions.push(parentLines[oldLine]);
oldLine++;
}
// Collect consecutive additions
const additions: string[] = [];
while (newLine < hunk.endNew && (oldLine >= hunk.endOld || parentLines[oldLine] !== currentLines[newLine])) {
additions.push(currentLines[newLine]);
newLine++;
}
// If we have both deletions and additions, it might be a modification
if (deletions.length > 0 && additions.length > 0) {
addSeparator();
// Output deletions
for (const line of deletions) {
diffLines.push(`\x1b[31m-${line}\x1b[0m`);
diffLines.push(`-${line}`);
}
// Output additions
for (const line of additions) {
diffLines.push(`\x1b[32m+${line}\x1b[0m`);
diffLines.push(`+${line}`);
}
} else {
// Handle pure deletions
@@ -622,28 +622,28 @@ export class GitShowCommand implements GitSubcommand {
addSeparator();
}
inDeletionBlock = true;
for (const line of deletions) {
diffLines.push(`\x1b[31m-${line}\x1b[0m`);
diffLines.push(`-${line}`);
}
}
// Handle pure additions
if (additions.length > 0) {
if (!inAdditionBlock && inDeletionBlock) {
addSeparator();
}
inAdditionBlock = true;
for (const line of additions) {
diffLines.push(`\x1b[32m+${line}\x1b[0m`);
diffLines.push(`+${line}`);
}
}
}
}
}
}
// Add the diff lines if we found changes
if (foundDifference && diffLines.length > 0) {
lines.push(...diffLines);
@@ -661,7 +661,7 @@ export class GitShowCommand implements GitSubcommand {
lines.push('');
}
}
const remainingFiles = modified.length - filesToShow.length;
if (remainingFiles > 0) {
lines.push(`... and ${remainingFiles} more modified files`);
+16
View File
@@ -74,3 +74,19 @@ export interface DenoDeployConfig {
projectName?: string;
corsProxy?: string;
}
export interface PresetDeployProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
name: string;
description: string;
baseURL?: string;
requiresNostr?: boolean;
apiKeyLabel?: string;
apiKeyURL?: string;
accountIdLabel?: string;
accountIdURL?: string;
organizationIdLabel?: string;
organizationIdURL?: string;
proxy?: boolean;
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more