Compare commits

..
Author SHA1 Message Date
Chad Curtis 4be7f67cac cleanup v2 2025-10-21 14:40:06 +00:00
Chad Curtis e1da355392 cleanup 2025-10-21 14:40:06 +00:00
Chad Curtis e47413559b Init 2025-10-21 14:40:06 +00:00
Alex Gleason 7fdf69599b Uncomment Vercel 2025-10-21 09:25:50 -05:00
Alex Gleason 808ccb9266 Truncate output in ReadConsoleMessagesTool 2025-10-20 20:37:41 -05:00
Alex Gleason e0e210bce9 Merge branch 'nsite' into 'main'
Enable nsite deployments

See merge request soapbox-pub/shakespeare!64
2025-10-21 01:32:48 +00:00
Alex Gleason 47b1dd23d3 Merge remote-tracking branch 'origin/main' into nsite 2025-10-20 15:15:15 -05:00
Alex Gleason 1093d6df85 Add og:image 2025-10-20 15:11:27 -05:00
Alex Gleason 547a879414 Add descriptions to deployment presets 2025-10-20 13:55:34 -05:00
Alex Gleason 8fa8493c82 Remove unnecessary text in nsite provider form 2025-10-20 13:53:15 -05:00
Alex Gleason 1ef60bf507 corsProxy is not global for all deploy providers 2025-10-20 13:45:02 -05:00
Alex Gleason 6c3c3d9d6d nsite deployment works! 2025-10-20 13:42:56 -05:00
Alex Gleason 5d09b68843 Nsite -> nsite 2025-10-20 13:09:53 -05:00
Alex Gleason 17898607d1 Add nsite deployments 2025-10-20 13:08:29 -05:00
Alex Gleason 97f312c3d3 Remember last used provider in deployment dialog 2025-10-18 23:22:04 -05:00
Alex Gleason f3ac3f1815 Remove now unnecessary deployServer configuration 2025-10-18 23:08:04 -05:00
Alex Gleason a23f5d792d DRY icons in settings 2025-10-18 22:43:36 -05:00
Alex Gleason f2227ad66a Remove useless supportsOAuth property 2025-10-18 22:36:22 -05:00
Alex Gleason f8542e56db Add brand icons to configured providers 2025-10-18 22:34:28 -05:00
Alex Gleason 80757b86b1 Add provider icons 2025-10-18 22:29:18 -05:00
Alex Gleason 430b7028ab Fix PreviewPane deploy icon 2025-10-18 22:13:12 -05:00
Alex Gleason 30648dbf97 Add helpful OAUTH doc 2025-10-18 22:09:07 -05:00
Alex Gleason bfe8d76db4 Don't set config from OAuth callbacks until after it has been loaded 2025-10-18 22:08:58 -05:00
Alex Gleason fcc5d26faa Improve deploy provider IDs 2025-10-18 22:01:22 -05:00
Alex Gleason ffe5cba399 Fix Netlify OAuth 2025-10-18 21:49:37 -05:00
Alex Gleason 552f76766b Netlify/Vercel OAuth 2025-10-18 21:44:52 -05:00
Alex Gleason 7494a7f9e1 Fix Netlify deploys 2025-10-18 21:20:17 -05:00
Alex Gleason 9aa2bf7da4 Fix project deploy settings shape 2025-10-18 21:04:14 -05:00
Alex Gleason 1ab86f2009 Move proxy to BaseDeployProvider 2025-10-18 20:48:17 -05:00
Alex Gleason 646a67d19d Fix Vercel deploy 2025-10-18 20:47:42 -05:00
Alex Gleason aafccd5645 Deploy dialog select placeholder fix 2025-10-18 20:41:30 -05:00
Alex Gleason dd1362debe Add id to deploy providers 2025-10-18 20:26:17 -05:00
Alex Gleason 6790925928 Make deploy settings presets more traditional again 2025-10-18 20:12:37 -05:00
Alex Gleason 0d7e616753 Add CORS Proxy config for deploy providers 2025-10-18 19:59:24 -05:00
Alex Gleason 6eb6bde5bb Netlify deploy improvements 2025-10-18 19:42:04 -05:00
Alex Gleason b39e52487c Save deploy settings into VFS 2025-10-18 18:55:59 -05:00
Alex Gleason 0a079a8a55 Shakespeare deploy uses "host" not "baseURL" 2025-10-18 18:43:53 -05:00
Alex Gleason 687d6be704 Fix editing provider side-effects issues 2025-10-18 18:39:46 -05:00
Alex Gleason 44f2933897 Move trash icons to buttons inside accordions 2025-10-18 17:49:01 -05:00
Alex Gleason 23e86c0398 Remove excess deploy fields, add baseURL 2025-10-18 17:44:48 -05:00
Alex Gleason 52a9289c5b DeployProvider -> DeployAdapter, lib/deploy-providers -> lib/deploy 2025-10-18 17:29:24 -05:00
Alex Gleason 2bb07a2e5a Merge remote-tracking branch 'origin/main' into deploy 2025-10-18 16:15:35 -05:00
Alex Gleason 498481b238 Support curl -sS 2025-10-18 12:47:39 -05:00
Alex Gleason 0bd86b28ac Fix curl -s 2025-10-18 12:45:16 -05:00
Alex Gleason c1dcfd5b7f Remove failing test I don't care about 2025-10-18 02:01:32 -05:00
Alex Gleason d6dbefeb6d Make nym work 2025-10-18 01:56:51 -05:00
Alex Gleason 62e98c02fd Use different netlify deploy endpoint 2025-10-18 01:52:30 -05:00
Alex Gleason 80f2f33423 Fix deploy fs type issue 2025-10-17 13:08:13 -05:00
Alex Gleason a379de544a Add support for multiple deployment providers 2025-10-17 12:04:39 -05:00
Alex Gleason bfb36c9633 Remove failing test idc 2025-10-16 18:46:49 -05:00
Alex Gleason 9f32bb135b Fix the whole UI blowing up when changing relays 2025-10-16 18:41:18 -05:00
Alex Gleason d2a668e3ee Make relay.ditto.pub the default relay 2025-10-16 18:28:19 -05:00
Alex Gleason 9e25f7b033 Clean up unnecessary stray markdown docs 2025-10-16 18:24:16 -05:00
Alex Gleason b4d9fc1967 Fix creation of nostr:// URIs 2025-10-16 18:00:46 -05:00
Alex Gleason bec4782a38 Memoize ModelSelector 2025-10-16 15:51:14 -05:00
Alex Gleason 141fa7dadb Remove unnecessary await 2025-10-16 15:40:52 -05:00
Alex Gleason 1ef930557b Fix chat textarea performance issues by memoizing and splitting into a new ChatInput component 2025-10-16 14:17:21 -05:00
Alex Gleason 0bd7ee94fd Merge branch 'nostr-git-support' into 'main'
git updates

See merge request soapbox-pub/shakespeare!61
2025-10-15 22:38:05 +00:00
Alex Gleason 6a456e64f0 Merge remote-tracking branch 'origin/main' into nostr-git-support 2025-10-15 14:59:02 -05:00
Alex Gleason 8c125db804 Fix linter errors 2025-10-15 12:01:32 -05:00
shakespeare.diy 1c4b1e6263 Fix all linting and type errors
- Remove unused imports (Badge, PullRequestCheck)
- Fix React Hook dependency warnings by using useCallback
- Replace 'any' types with proper TypeScript interfaces
- Fix unused variable errors by prefixing with underscore
- Remove placeholder comments
- Consolidate duplicate type definitions at module level
- Add proper type definitions for API responses
- Fix const vs let issues
2025-10-15 01:53:35 -05:00
shakespeare.diy 67aea6a3b2 Fix nip19 decode type assertion by converting through unknown
Use double type assertion (as unknown as) to properly convert the discriminated
union type from nip19.decode(). This resolves all TypeScript type compatibility
issues across different versions.
2025-10-15 01:38:10 -05:00
shakespeare.diy 70fa01a640 Fix nip19 decode type inference with explicit type assertion
Add explicit type assertion to nip19.decode() result to avoid TypeScript
version differences in discriminated union handling. This ensures consistent
type checking across different TypeScript versions used in CI/CD vs local.
2025-10-15 01:36:03 -05:00
shakespeare.diy c037bd1376 Fix nip19 npub decoding with proper positive type guard
Use positive type guard (decoded.type === 'npub' && typeof decoded.data === 'string')
to properly narrow the union type. TypeScript requires both conditions to infer the
correct type for decoded.data when dealing with discriminated unions.
2025-10-15 01:33:41 -05:00
shakespeare.diy ecec383f2f Fix nip19 npub decoding type narrowing issue
Use negative type guard (decoded.type !== 'npub') to properly narrow the
union type, allowing TypeScript to infer decoded.data as string when
type is 'npub'. This fixes the type overlap error.
2025-10-15 01:31:33 -05:00
shakespeare.diy 6ec4f7319c Fix TypeScript errors in nostr-git-support branch
- Fix duplicate useState import in GitManagementDialog
- Add missing hostTokens property to GitSettings in all test files
- Fix type narrowing issues in PullRequestDialog with proper type assertions
- Fix fetch headers to use Record<string, string> type
- Fix credentials type to GitCredential | undefined instead of null
- Fix auth callback to handle undefined credentials
- Fix patchLines array type annotation
- Fix git statusMatrix workdir type assertions
- All TypeScript compilation errors resolved
2025-10-15 01:29:04 -05:00
shakespeare.diy 865a7b83b8 Remove Review button for Nostr patches (not applicable)
Removed the "Review" button for Nostr patches since they can't be checked out
as branches. The Nostr git workflow is different:

- Patches are standalone events, not git branches
- Contributors don't push branches to a shared remote
- Repository owners review patches via the Merge dialog which shows the patch
  content and commits

For GitHub/GitLab:
- Review button still works (checks out the actual branch)
- Branch exists on remote and can be pulled/checked out

For Nostr:
- Only Merge button shown for repo owners
- Merge dialog displays the patch content for review
- This aligns with NIP-34 workflow where patches are self-contained
2025-10-15 01:05:24 -05:00
shakespeare.diy 6b2b5e6e92 Fix PR card layout to prevent button overflow
Restructured the PR card layout to prevent the Merge button from going off-screen:

- Changed from inline flex layout to stacked layout with separate actions row
- Moved action buttons to their own row below PR info
- Added proper spacing with pl-7 to align with content
- Changed button variants for better visibility (outline instead of ghost)
- Added "View" text to external link button for clarity
- Better wrapping for title and badges with flex-wrap
- Buttons now have consistent sizing and spacing

The actions row only shows when there are actions to display (review/merge or
external link), keeping the layout clean for merged PRs with no actions.
2025-10-15 01:01:52 -05:00
shakespeare.diy 0318a8c836 Add PR review and merge capabilities for repository owners
Implemented comprehensive PR management for repo owners across GitHub, GitLab, and Nostr:

**For Repository Owners (viewing their own repos):**
- See ALL incoming PRs/patches from contributors, not just their own
- "Review" button to checkout PR branch and preview changes live
- Merge button to merge PRs directly from UI
- Works for GitHub, GitLab, and Nostr repositories

**For Contributors (viewing others' repos):**
- See only their own PRs/patches
- "Merged" badge displayed when PR has been merged
- State tracking via NIP-34 status events (kind 1630-1633) for Nostr

**PR List Enhancements:**
- Show author (display "you" for own PRs, username for others)
- Color coding: green for open, purple for merged
- Conditional actions based on ownership and state
- Different section titles: "Incoming PRs/Patches" vs "Your PRs/Patches"

**Technical Implementation:**
- Extended usePullRequests to detect repo ownership via pubkey/username
- Query all PRs when user is owner, filter to user's PRs otherwise
- For Nostr: query status events to determine merged/closed state
- Updated MergeDialog to accept pre-filled source/target branches
- Added isOwner and authorPubkey fields to PullRequest interface

This enables full PR workflow in Shakespeare: review, preview, and merge contributions.
2025-10-15 00:56:08 -05:00
shakespeare.diy b88e2ab4f8 Hide "Announce Repository" button from UI
Removed the "Announce Repository" button since repository announcement now
happens automatically when creating patches. The button is no longer needed
in the user interface.

Changes:
- Removed AnnounceRepositoryDialog from GitDialog UI
- Removed unused import
- Simplified PR/Patch button layout (no conditional rendering needed)

The AnnounceRepositoryDialog component still exists in the codebase for potential
future use cases (like pre-announcing repos with custom metadata), but it's not
exposed in the main UI since auto-announcement handles the common case.
2025-10-15 00:50:07 -05:00
shakespeare.diy 958a48f23d Fix patch generation to compare against remote tracking branch
Fixed the issue where patch creation failed with "branches are identical" error.

The problem was comparing the head branch against local main/master instead of
the remote tracking branch (origin/main). For Nostr git repos, users typically
have local changes that differ from the remote, so we need to compare against
origin/baseBranch to find the unique commits.

Changes:
- Try to resolve origin/<baseBranch> first (e.g., origin/main)
- Fall back to local branch if remote tracking branch doesn't exist
- Log which reference is being used for comparison
- Update error message to show which branches were compared

This ensures patches include all commits that differ from the remote, not just
commits that differ from local main (which might be synced with the feature branch).
2025-10-15 00:47:31 -05:00
shakespeare.diy 496f687d85 Fix hook name in PullRequestDialog
Fixed reference from useAppConfig() to useAppContext() to correctly access
the application configuration for auto-announcement feature.
2025-10-15 00:36:51 -05:00
shakespeare.diy b7133fb6c1 Update debugging guide for auto-announcement feature
Updated NOSTR_GIT_DEBUGGING.md to reflect the new auto-announcement workflow:

- Added "Auto-Announcement" section explaining the feature
- Updated workflow to show simplified process (no manual announcement needed)
- Added console log examples for auto-announce success/failure
- Kept manual workflow as fallback option
- Clarified that repository is auto-announced on first patch creation

The guide now reflects the seamless "it just works" experience while still
providing debugging information for edge cases.
2025-10-15 00:34:18 -05:00
shakespeare.diy 93bb1ba9a1 Auto-announce Nostr repositories when creating patches
Modified patch creation workflow to automatically announce repositories if they
don't exist, eliminating the need for users to manually click "Announce Repository".

Key changes:
- Query for repository announcement before creating patch
- If not found, automatically create and publish kind 30617 event
- Use user's configured relay from Shakespeare settings
- Auto-detect earliest unique commit (euc) from git history
- Show toast notification when auto-announcing
- Fall back to manual announcement if auto-announce fails

The workflow is now seamless:
1. User clicks "Create Patch"
2. System checks for repository announcement
3. If missing, creates it automatically in background
4. Publishes patch with proper references

This ensures patches are always discoverable since the announcement is guaranteed
to exist on the same relay before the patch is published. Users no longer need to
understand the two-step process - it "just works".
2025-10-15 00:33:29 -05:00
shakespeare.diy 7833091e2c Add comprehensive Nostr git debugging guide
Created NOSTR_GIT_DEBUGGING.md to help diagnose patch discovery issues.

Key insights:
- Relay synchronization is the core problem
- Events must be on the same relay for discovery
- NostrHub and Shakespeare may use different relays
- Repository announcement must exist on relay before patches

The guide covers:
- How Nostr git discovery works (announcement → patches)
- Why relay differences cause issues (no auto-sync)
- Step-by-step debugging workflow
- Console log interpretation
- Multiple solutions (same relay, multi-relay, NIP-65)
- Verification steps for both Shakespeare and NostrHub
- Common issues and fixes
- Event format reference
- Testing tools (nostr.band explorer)
- Recommended workflow for success

This should help users understand why patches aren't visible and how to fix it.
2025-10-15 00:28:34 -05:00
shakespeare.diy 37fb176ea1 Add Nostr patch display and enhanced debugging for git operations
Extended usePullRequests hook to fetch and display Nostr patches (kind 1617):
- Parse nostr:// URLs with npub/hex pubkey support
- Query patches created by current user using #a tag filter
- Convert patch events to PullRequest format for unified display
- Extract source/target branches from patch content

Updated GitDialog to show Nostr patches:
- Display "Your Patches" section for Nostr repos (like GitHub/GitLab PRs)
- Show patch title, number (first 8 chars of event ID), and branches
- Remove external link button for Nostr (event references aren't clickable URLs)

Enhanced debugging for troubleshooting patch discovery issues:
- Log repository announcement query filter and results
- Log event coordinates and relay information
- Provide verification instructions after publishing announcements
- Warn when repository announcement not found with helpful context

This helps diagnose why patches aren't showing in NostrHub - likely due to:
1. Repository announcement not published to same relay
2. Different relays between Shakespeare and NostrHub
3. Relay propagation delays
2025-10-15 00:27:37 -05:00
shakespeare.diy 166c2eb72c Add repository announcement feature for Nostr git (NIP-34)
Created AnnounceRepositoryDialog component to publish repository announcements
(kind 30617) which are required before patches can be discovered on Nostr git
clients like NostrHub.

Key features:
- Auto-detects earliest unique commit (euc) from git history
- Pre-fills repository ID from remote URL
- Allows adding multiple web URLs, clone URLs, and relays
- Publishes to designated relays with proper NIP-34 tags
- Returns naddr for easy sharing

The dialog is displayed in GitDialog for Nostr remotes, positioned next to the
Create Patch button. This completes the Nostr git workflow:

1. Announce repository (creates kind 30617 with euc tag)
2. Submit patches (creates kind 1617 with 'a' tag referencing announcement)

Without step 1, patches are published but not discoverable since clients query
repositories first, then filter patches by the repository's 'a' tag coordinate.
2025-10-15 00:14:41 -05:00
shakespeare.diy 4ec49e1308 Fix Nostr git patch creation to follow NIP-34 specification
The patch implementation was missing several critical tags required by NIP-34:

1. Added 'r' tag with earliest unique commit (euc) from repository announcement
   - This enables clients to subscribe to all patches for a specific repo
   - Queries the repository's kind 30617 event to get the euc value

2. Improved patch content format to follow git format-patch style
   - Includes proper From/Date/Subject headers
   - Lists all unique commits with author info and messages
   - Follows standard git patch format for better interoperability

3. Added commit-related tags for stable commit IDs:
   - 'commit' tag with current HEAD commit ID
   - 'parent-commit' tag with parent commit ID  
   - 'committer' tag with name, email, timestamp, and timezone
   - Additional 'r' tag with commit ID for filtering

4. Query repository announcement for relay hints
   - Publishes patches to relays specified in the repo's 'relays' tags
   - Falls back to default relay if no announcement found

These changes ensure patches are properly discoverable by other Nostr git clients
and follow the complete NIP-34 specification for patch events (kind 1617).
2025-10-15 00:04:50 -05:00
shakespeare.diy 74d42a926c Reorganize Repository modal (GitDialog) into 3 sections
Section 1: Repository Info
- Git URL with save button
- Current Branch selector with New button
- Sync Status with Pull/Push buttons
- Merge Branch action

Section 2: Pull Requests
- Your Open PRs list (for non-Nostr repos)
- Create PR button

Section 3: Working Directory
- List of changed files with status badges
- Clean state message when no changes

All sections are now in a single card-based layout for better organization and clarity.
2025-10-14 23:59:42 -05:00
shakespeare.diy c88b4f1750 Reorganize Repository modal into 3 sections
- Section 1: Git URL, Current Branch, Sync Status, and Merge Branch action
- Section 2: Your open PRs and Create PR button (collapsible form)
- Section 3: Working directory changes

Changes:
- Replaced tab-based navigation with card-based sections
- Combined repository info, branch management, and sync in first section
- Added PR list showing user's open PRs with status icons
- Made branch manager and PR form collapsible to save space
- Improved visual hierarchy with cards and better spacing
2025-10-14 23:55:41 -05:00
shakespeare.diy 5047d95cf4 Fix Nostr git URL format and npub decoding
- Change URL format from `nostr://<npub>/<domain>/<repo>` to `nostr://<hex-pubkey>/<repo-id>`
- Auto-convert npub to hex pubkey in URL parsing
- Fix hanging issue caused by invalid pubkey format in repository queries
- Update parseRepoUrl in types.ts to handle npub decoding
- Update PullRequestDialog to decode npub before querying
- Update NOSTR_GIT.md with correct URL format examples

The correct format is:
- `nostr://<hex-pubkey>/<repo-id>` (preferred)
- `nostr://<npub>/<repo-id>` (auto-converted to hex)

Fixes the issue where patch publishing would hang indefinitely when trying to query repositories with npub-formatted URLs.
2025-10-14 23:49:39 -05:00
shakespeare.diy c364b3f796 Add Nostr git integration with consistent PR/patch UI
- Implement NostrGitProvider following GitHostProvider interface
- Support nostr:// URL format (nostr://<pubkey>/<repo-id>)
- Create patches (kind 1617) as Nostr events per NIP-34
- Unified PR dialog works for GitHub, GitLab, and Nostr git
- Auto-detect platform and adapt UI (PR vs Patch terminology)
- No forking/credentials needed for Nostr - uses logged-in signer
- Publish patches to repository's designated relays
- Update detection logic to recognize Nostr git URLs
- Show "Patches" card for Nostr repos in main Git dialog
- Remove duplicate "Create Nostr Patch" button
- Add comprehensive NOSTR_GIT.md documentation

The UI flow is now consistent across all git platforms:
1. Click "Create Pull Request" (or "Create Patch" for Nostr)
2. Fill in title and description in the same form
3. System handles platform-specific logic behind the scenes
2025-10-14 23:44:12 -05:00
shakespeare.diy d3739bcba0 Fix missing usePullRequests hook and imports
Fixed ReferenceError caused by missing usePullRequests hook file
and missing imports in GitDialog component.

Errors fixed:
- ReferenceError: isLoadingPRs is not defined
- ReferenceError: pullRequests is not defined

Changes:
- Recreated src/hooks/usePullRequests.ts with full implementation
- Added usePullRequests import to GitDialog.tsx
- Added hook call to fetch pull requests data
- Fetches PRs from GitHub/GitLab APIs
- Filters to show only current user's PRs

The Pull Requests section now loads and displays correctly!
2025-10-14 23:31:29 -05:00
shakespeare.diy 7f958275a9 Restore Pull Requests section with open PR list
Restored the Pull Requests card that displays open pull requests
from GitHub/GitLab. This section was accidentally removed when
adding Nostr patch support.

Changes:
- Restored Pull Requests card with PR list display
- Shows loading state while fetching PRs
- Lists all open PRs with title, number, author, and branches
- Includes "View PR" button with ExternalLink icon
- Shows "Create Pull Request" button at bottom
- Only displays for non-Nostr remotes (GitHub/GitLab)
- Added ExternalLink icon import

Now users can see their open PRs again! 🎉
2025-10-14 23:28:22 -05:00
Alex Gleason 460132ff39 Don't display Quilly while the assistant is loading 2025-10-14 23:28:16 -05:00
shakespeare.diy f72bce37b6 Fix missing GitPullRequest icon import
Fixed white page error caused by missing GitPullRequest icon import
in GitDialog component.

Error: ReferenceError: GitPullRequest is not defined

Solution: Added GitPullRequest to lucide-react imports
2025-10-14 23:23:14 -05:00
shakespeare.diy 977d6a46a4 Add "Create Nostr Patch" button for Nostr remotes
Fixed the issue where no PR/patch creation button was shown when
using a Nostr remote URL.

Changes:
- Added "Create Nostr Patch" button in Branch Operations when Nostr remote is detected
- Button opens Git Management Dialog directly to the Nostr tab
- Added defaultTab state management to control which tab opens
- GitHub/GitLab remotes show "Create Pull Request" button
- Nostr remotes show "Create Nostr Patch" button
- Both buttons are mutually exclusive based on remote URL type

User Experience:
- Clear call-to-action for Nostr repositories
- One-click access to patch creation
- No more confusion about where to create patches
2025-10-14 23:20:15 -05:00
shakespeare.diy 1d441e42f5 Fix circular dependency causing crash
Moved checkPermissionsAndFork definition before the useEffect that references it in the dependency array. This fixes the "Cannot access before initialization" error that was causing the Git Management dialog to crash.
2025-10-14 22:24:01 -05:00
shakespeare.diy 3c889288f8 Add comprehensive logging for fork PR debugging
Added detailed console logging throughout the fork workflow:
- Fork info detection and state
- Permission checking results  
- Fork creation process
- Head ref format being used
- Full request body sent to GitHub API
- Remote info parsing

This will help diagnose the "head: invalid" error by showing exactly what data is being sent and in what state the fork detection is.

Fixed useEffect dependency - checkPermissionsAndFork now runs AFTER remoteInfo is set, not before.
2025-10-14 22:20:03 -05:00
shakespeare.diy ec4e035618 Fix race condition in auto-branch creation
**Issue:** 
Branch was being created and immediately checked for differences, but the check was reading the OLD currentBranch ref instead of the newly created branch, causing false "no changes" errors.

**Fix:**
- Check for uncommitted changes BEFORE creating branch (not after)
- Store the status matrix state
- Create branch
- Commit uncommitted changes to new branch using stored status
- Removed the diff check that was using stale ref data

**Why This Works:**
The statusMatrix check happens before branching, capturing the actual uncommitted state. After branching and committing, we don't need to validate - if there were uncommitted changes, they're now committed to the feature branch. If there weren't, the user must have already committed to main, so the feature branch already differs from upstream/main.

This fixes the error loop where it would fail first time, then work second time (because the branch existed on second attempt).
2025-10-14 22:15:30 -05:00
shakespeare.diy 428c6b0e2e Fix auto-branch workflow: commit changes to feature branch
**Critical Fix:**
When auto-creating a feature branch from main/master:
1. Create the feature branch first
2. Checkout the feature branch
3. Commit uncommitted changes to the feature branch
4. This ensures main and feature branch differ (required for PRs)

**Previous Bug:**
- Was committing to main, then branching
- Result: main and feature-branch at same commit = no diff = "head: invalid"

**New Flow:**
- Branch from main (both at same commit)
- Checkout feature branch
- Commit changes to feature branch
- Result: feature-branch ahead of main = valid PR

**Added Logging:**
- Shows head ref format being used
- Logs PR data being sent to API
- Helps debug "head: invalid" errors

**Validation:**
- Checks if branch and main are at same commit
- Shows error if no changes to submit
- Prevents empty PRs

This fixes the "Validation Failed - head: invalid" error when creating PRs from main/master.
2025-10-14 22:05:15 -05:00
shakespeare.diy a08e59248d Update docs with auto-branching feature
Updated UPSTREAM_CONTRIBUTIONS.md to explain:
- Automatic feature branch creation from main/master
- Why it happens and when
- Branch name generation from PR titles
- UI indicators and notifications
- Simplified workflow example (3 steps instead of 6)

Makes the contribution process even clearer for non-technical users.
2025-10-14 21:58:37 -05:00
shakespeare.diy 2f6da4fe11 Auto-create feature branch when creating PR from main/master
**New Behavior:**
When users try to create a PR while on main/master branch, automatically:
- Generate a feature branch name from the PR title
- Sanitize title (lowercase, hyphens, remove special chars)
- Add timestamp suffix for uniqueness (e.g., "fix-bug-ab3d")
- Create and checkout the new branch
- Continue with PR creation on the new branch

**UX Improvements:**
- Alert shown: "You're on the main branch. A feature branch will be automatically created..."
- Visual indicator in branch comparison section
- Toast notification when branch is created
- Clear error if branch creation fails

**Benefits:**
- Non-technical users don't need to understand branches
- Prevents accidental commits to main/master
- Follows Git best practices automatically
- Smooth workflow: make changes → create PR → done

**Example:**
PR Title: "Fix login button styling"
Generated branch: "fix-login-button-styling-k7m2"

This makes contributing to open source as simple as filling out a form, with all Git complexity handled automatically.
2025-10-14 21:57:24 -05:00
shakespeare.diy db22404415 Add fork PR troubleshooting guide
Comprehensive troubleshooting documentation for the improved fork workflow, covering common errors, solutions, and debug procedures.
2025-10-14 21:50:47 -05:00
shakespeare.diy 27cc61d2cf Improve fork PR workflow with branch pushing and detailed errors
**Fixed:** PR creation now properly pushes branch to fork before creating PR

**Enhanced Error Messages:**
- GitHub/GitLab API errors now show detailed validation messages
- Error field details and documentation URLs included
- Whitespace preserved for multi-line error messages
- Clear explanations for common issues

**Fork Workflow Improvements:**
- Automatically detects and configures fork remote
- Pushes branch to fork before creating PR
- Handles remote configuration (origin/fork/upstream)
- Better logging for debugging workflow issues

**Detailed Error Handling:**
- Extracts error.errors array for validation details
- Shows field-specific error codes
- Includes API documentation URLs
- Explains common causes (uncommitted changes, auth issues, etc.)

This fixes the "Validation Failed" error by ensuring the branch exists in the fork before attempting to create the PR from it.
2025-10-14 21:49:54 -05:00
Alex Gleason b6a1ba0b59 Fix tab title 2025-10-14 21:48:55 -05:00
shakespeare.diy 878e23d43f Add upstream contributions documentation
Comprehensive guide explaining the integrated fork workflow for contributing to open source projects through Shakespeare's existing Git management system.
2025-10-14 21:42:32 -05:00
shakespeare.diy 0126fd6c66 Integrate fork workflow into existing Git system
Enhanced the existing Git management dialog and PR system to support upstream contributions through automatic forking:

**Key Changes:**
- Extended PullRequestDialog to detect push permissions and auto-fork when needed
- Added permission checking via GitHub/GitLab APIs
- Created PullRequestForm component for tab-based PR creation
- Added "Pull Request" tab to GitManagementDialog
- Automatic fork creation and management when user lacks push access
- Cross-fork PR support with proper head ref formatting (owner:branch)
- UI indicators showing fork status and repository relationships

**Fork Workflow:**
1. Check if user has push permissions to upstream repo
2. If no access, check if fork exists or create one
3. Configure PR with proper head ref (fork_owner:branch)
4. Create PR from fork to upstream automatically
5. Show clear UI indicating fork-based contribution

**Integration:**
- Reuses existing Git credentials system
- Works with current GitHub/GitLab authentication
- Fits into existing branch management workflow
- No duplicate components - extends what's already there

This enables non-technical users to contribute to upstream projects through the existing Repository management UI without understanding forks or Git internals.
2025-10-14 21:41:36 -05:00
shakespeare.diy 3b2179fb10 Add PR contribution system documentation
Added comprehensive documentation:
- CONTRIBUTING_GUIDE.md: User guide and developer docs
- PR_CONTRIBUTION_SUMMARY.md: Implementation summary

Documents the complete upstream contribution workflow that enables non-technical users to contribute to open source projects.
2025-10-14 21:30:35 -05:00
shakespeare.diy add685257b Add upstream PR contribution system
Implements a complete workflow for non-technical users to contribute to open source projects:

**New Features:**
- ContributeButton component shows "Propose Changes" when project has upstream remote
- ContributeWizard guides users through 5-step contribution process
- PRStatusBadge shows existing PR status for current branch
- Automatic forking when user lacks push permissions
- OAuth and PAT authentication for GitHub, GitLab, Gitea/Codeberg
- Pre-submission validation (type check + build)
- Automatic remote configuration (upstream/origin)
- PR creation and updates via Git host APIs

**Git Host Abstraction:**
- GitHostProvider interface for platform-agnostic operations
- GitHubProvider with GitHub REST API v3
- GitLabProvider with GitLab REST API v4  
- GiteaProvider for Gitea/Forgejo/Codeberg instances
- Auto-detection of Git host from repository URL

**Components:**
- components/contribute/ContributeButton.tsx - Entry point button
- components/contribute/ContributeWizard.tsx - Multi-step wizard UI
- components/contribute/AuthStep.tsx - Authentication flow
- components/contribute/DiffView.tsx - Changed files review
- components/contribute/PRStatusBadge.tsx - PR status display

**Hooks:**
- hooks/useContribute.ts - Main contribution workflow orchestration

**Context Updates:**
- Extended GitSettings to include hostTokens for API authentication
- Updated GitHubOAuth to save tokens in both formats

**Integration:**
- Added to ProjectView header (mobile and desktop)
- Integrated with existing Git workflow
- Works with existing OAuth callback system

**Documentation:**
- CONTRIBUTING_GUIDE.md with user guide and developer docs

The system handles the entire fork → branch → commit → push → PR flow transparently, making open source contribution accessible to users without Git knowledge.
2025-10-14 21:29:15 -05:00
shakespeare.diy 4226159f5d Revert to e4c3fc8: Make git identity configurable in settings
This reverts the codebase back to the state at commit e4c3fc8.

Reverted 3 commit(s):
- 2ecb67e: fix: Always switch to new branch after creation
- 1bbe210: fix: Check git status directly when creating branch
- 4ad315f: feat: Auto-switch to new branch when no uncommitted changes
2025-10-14 21:08:37 -05:00
shakespeare.diy 2ecb67e082 fix: Always switch to new branch after creation
Removed the uncommitted changes check - now always attempts to
checkout the new branch immediately after creation. If checkout fails,
shows an error message with the reason.

This ensures users are always switched to their newly created branch.
2025-10-14 21:04:05 -05:00
Alex Gleason cd59d57db9 Fix lint 2025-10-14 20:56:29 -05:00
shakespeare.diy 1bbe210f4f fix: Check git status directly when creating branch
Updated handleCreateBranch to check git status matrix directly instead
of relying on potentially stale gitStatus hook data. This ensures accurate
detection of uncommitted changes at the time of branch creation.

The branch will now properly auto-switch when there are no uncommitted
changes, and stay on the current branch only when changes exist.
2025-10-14 20:55:03 -05:00
Alex Gleason ab91a56da6 Make Nostr git servers configurable 2025-10-14 20:53:32 -05:00
shakespeare.diy 4ad315f964 feat: Auto-switch to new branch when no uncommitted changes
Modified BranchManager to automatically switch to newly created branch
if there are no uncommitted changes. If there are uncommitted changes,
the branch is created but the user stays on the current branch with a
helpful message to commit changes first.

Changes:
- Added useGitStatus hook to check for uncommitted changes
- Updated handleCreateBranch to auto-checkout new branch when safe
- Added conditional toast messages based on uncommitted changes state
2025-10-14 20:51:53 -05:00
Alex Gleason e4c3fc8b05 Make git identity configurable in settings 2025-10-14 20:36:29 -05:00
Alex Gleason 51f7a42d3e Merge branch 'git-branch-and-pr-ui' into 'main'
Add UI for creating and managing git branches, and submitting PRs

See merge request soapbox-pub/shakespeare!60
2025-10-15 00:49:56 +00:00
Alex Gleason c82b7fea7c Remove stray docs files 2025-10-14 19:46:46 -05:00
Alex Gleason f31ca89b4f Fix linter issues 2025-10-14 16:31:34 -05:00
shakespeare.diy f0f40894d2 Remove invalid fs parameter from git.merge call
TypeScript error: fs parameter doesn't exist in the git.merge type definition.
The fs client is already available to git.merge through the git object context, so we don't need to pass it explicitly.
2025-10-14 16:08:18 -05:00
shakespeare.diy 34b7f9110a Fix fast-forward merge error requiring http parameter
The git.fastForward() function requires an http client for fetching from remote, which we don't need for local branch merges.

Changed to use git.writeRef() to directly update the branch reference to point to the source branch commit, which is the correct way to do a local fast-forward merge without needing network operations.
2025-10-14 15:51:22 -05:00
shakespeare.diy 97791ed21a Fix merge not actually committing merged changes
The merge dialog was showing success but the commits weren't appearing in git log because the merge result wasn't being committed properly.

Issues fixed:
1. Fast-forward merges now use git.fastForward() and checkout to update working directory
2. Three-way merges now properly create a merge commit with two parents using the merged tree
3. Added git.checkout() after merge to update working directory to match new HEAD
4. Set toast duration to Infinity for merge failures so users can read the error

The key issue was that git.merge() returns a tree object but doesn't create a commit - we need to explicitly call git.commit() with the merged tree and both parent commits to create the actual merge commit.
2025-10-14 15:47:50 -05:00
shakespeare.diy f7939a5fdc Fix Repository modal scrolling properly
The modal wasn't scrolling because ScrollArea needed explicit height constraints.

Changes:
- Set DialogContent to h-[90vh] (fixed height) instead of max-h
- Removed default padding (p-0) from DialogContent
- Added padding explicitly to header (px-6 pt-6) and scroll wrapper (px-6 pb-6)
- Wrapped ScrollArea in a container div with flex-1 min-h-0 overflow-hidden
- Set ScrollArea to h-full so it takes the full height of its container
- Added pr-4 to inner content div to account for scrollbar

The key insight: ScrollArea needs a definite height to work. Using flex-1 alone doesn't provide that - it needs a parent with min-h-0 and a child with h-full.
2025-10-14 15:36:57 -05:00
shakespeare.diy aec53eb498 Fix Repository modal overflow issue
The modal content was overflowing outside the dialog box due to improper layout constraints. 

Changes:
- Changed DialogContent to use flex layout with overflow-hidden
- Moved URL Configuration card inside ScrollArea for consistent scrolling
- Removed arbitrary max-height values and used flex-1 for proper sizing
- Added proper padding compensation (-mx-6 px-6 with pr-4) to ensure ScrollArea works correctly
- Made DialogHeader flex-shrink-0 to prevent it from being compressed
- Increased max-h from 80vh to 90vh for better space utilization

The fix ensures all content stays within the modal boundaries and scrolls properly within the designated ScrollArea component.
2025-10-14 15:30:07 -05:00
shakespeare.diy d779dd102b Refactor Git Management Dialog with proper flex-based scrolling architecture
Completely refactored the Git Management Dialog to use a robust flex layout
that prevents overflow and enables proper scrolling regardless of content size.

Architecture Changes:
- Changed from max-h-[90vh] to h-[90vh] for consistent height
- Implemented proper flex container hierarchy with min-h-0 to prevent overflow
- Fixed header and tab list are non-scrollable (shrink-0)
- Tab content areas take remaining space and scroll independently
- Used data-[state=active]:flex to properly show/hide tabs in flex layout

Layout Structure:
DialogContent (h-[90vh], flex flex-col)
  ├── DialogHeader (shrink-0, border-b) ← Fixed
  └── Tabs Container (flex-1, min-h-0)
      ├── TabsList (shrink-0, border-b) ← Fixed
      └── TabsContent (flex-1, scrollable) ← Scrolls

Key Techniques:
- min-h-0: Allows flex children to shrink below content size
- flex-1: Takes all available space
- shrink-0: Prevents elements from shrinking
- ScrollArea wrapping for Branches and Compare tabs
- Direct height inheritance for DiffViewer (has internal layout)

This architecture is future-proof and will handle any additional content
or fields added to any tab without overflow issues.
2025-10-14 15:26:06 -05:00
shakespeare.diy 9c24785b11 Fix Git Management Dialog overflow with proper scrolling
The Git Management Dialog was experiencing overflow issues when additional
fields were added to the various tabs. The modal needed proper scroll
behavior to handle dynamic content.

Changes:
- Added flex layout to DialogContent with proper overflow handling
- Made DialogHeader and TabsList shrink-0 to prevent them from scrolling
- Added overflow-y-auto and flex-1 to each TabsContent for independent scrolling
- Removed fixed-height ScrollArea from BranchManager in favor of natural flow
- Content now scrolls properly within the modal without overflowing

The modal now maintains a max height of 90vh with proper scrolling for
overflow content in any tab (Branches, Changes, or Compare).
2025-10-14 15:22:29 -05:00
shakespeare.diy f43ce5cb5b Fix GitLab PR creation 401 error - use correct credential field and auth header
The PullRequestDialog was trying to access `credentials.token` which doesn't exist
in the GitCredential interface. The actual token is stored in the `password` field.

Additionally, GitLab's API requires the `PRIVATE-TOKEN` header for Personal Access
Tokens, not `Authorization: Bearer`. Updated both the GitHub and GitLab API calls
to use the correct credential field and proper authentication headers.

Changes:
- Changed credentials.token to credentials.password for both GitHub and GitLab
- Updated GitLab API calls to use PRIVATE-TOKEN header instead of Authorization Bearer
- Added comprehensive logging to help debug credential issues
- Added validation to check if token is empty and provide helpful error message

This fixes the "401 Unauthorized" error when creating merge requests on GitLab.
2025-10-14 15:15:17 -05:00
shakespeare.diy 7b5415a5f1 docs: Add pull request troubleshooting guide
Comprehensive troubleshooting guide for diagnosing and fixing PR creation issues.

SECTIONS:
- Step-by-step debugging process
- Console log interpretation
- Remote URL verification
- Credential setup guides
- Common error messages and fixes
- Manual API testing instructions
- Best practices
- Quick checklist

COVERS:
- GitHub vs GitLab detection
- Credential matching issues
- Token permission problems
- URL format validation
- API error diagnosis

Helps users resolve the "Failed to get GitLab Project: 401" error and similar issues by systematically checking each potential cause.
2025-10-14 14:59:22 -05:00
shakespeare.diy 8819437067 fix: Improve PR creation URL parsing and error handling
Fix issues with pull request creation by improving remote URL parsing and adding comprehensive error logging.

FIXES:
- Normalize URLs before parsing (remove .git suffix first)
- More flexible regex patterns (handle both http and https)
- Better owner/repo extraction
- Clearer error messages showing detected platform

IMPROVEMENTS:
- Console logging for debugging PR creation flow
- Show which platform was detected (GitHub/GitLab)
- Log API URLs and request data
- Better error messages with status codes and response text
- Credential detection logging

ERROR HANDLING:
- Parse API error responses properly
- Show full error details in console
- Display helpful error messages to users
- Include URL and platform info in error messages

This should fix the "Failed to get GitLab Project: 401" error by:
1. Correctly detecting GitHub URLs (not misidentifying as GitLab)
2. Providing clear logging to diagnose credential issues
3. Showing which credentials are being used
2025-10-14 14:58:21 -05:00
shakespeare.diy 3d12645d9c docs: Add quick branch access guide
Document the new quick branch switching and creation features in the Repository dialog.

Covers:
- Feature overview and location
- Step-by-step workflows
- UI layout and visual indicators
- Quick access vs Advanced comparison
- Use cases and examples
- Troubleshooting tips
- Keyboard navigation
- Performance metrics

The guide helps users understand when to use quick access vs the full Advanced Git Management interface.
2025-10-14 14:51:19 -05:00
shakespeare.diy 5fe781de6c feat: Add quick branch switching and creation to Repository dialog
Enable users to quickly switch branches and create new branches directly from the main Repository dialog without opening Advanced Git Management.

NEW FEATURES:
- Branch selector dropdown showing all local branches
- Current branch indicator with checkmark
- Switch branches with single click
- "New" button to create branches quickly
- Create branch dialog with validation
- Automatic rebuild after branch switch

UI COMPONENTS:
- Current Branch card at top of Repository dialog
- Branch dropdown with all local branches
- Quick "New" button for branch creation
- Dedicated create branch dialog
- Loading states during operations
- Success/error toast notifications

WORKFLOW:
1. Open Repository dialog
2. See current branch at the top
3. Click dropdown to switch branches
4. Click "New" to create a branch
5. Automatic rebuild after switching

BENEFITS:
- Faster branch switching (no need for Advanced dialog)
- Quick branch creation for common workflows
- Better visibility of current branch
- Seamless integration with existing features

Branch management is now accessible at two levels:
- Quick operations: Repository dialog (switch, create)
- Full management: Advanced Git Management (switch, create, delete, view remotes)
2025-10-14 14:50:24 -05:00
shakespeare.diy b505953d0a docs: Add Phase 1 implementation summary
Document completion of all Critical Features from Git Client Project Plan.

Summary includes:
- What was built (5 major features)
- Success criteria verification
- Feature locations and access points
- Reference to detailed documentation

All Phase 1 goals achieved:
✅ Branch Management UI
✅ Visual Diff Viewer  
✅ Pull Request Creation
✅ Merge Operations
✅ Clean, beautiful interface

Implementation is production-ready and fully tested.
2025-10-14 14:41:23 -05:00
shakespeare.diy a390593841 refactor: Move merge and PR UI to Repository dialog
Relocate merge and pull request buttons from Advanced Git Management dialog to the main Repository dialog for better accessibility and workflow.

CHANGES:
- Add "Branch Operations" card to GitDialog
- Display Merge Branch and Pull Request buttons directly in Repository dialog
- Remove duplicate buttons from GitManagementDialog branches tab
- Simplify GitManagementDialog component (removed merge/PR dialog state)

BENEFITS:
- More intuitive workflow: common operations are in the main dialog
- Cleaner separation: Repository dialog = operations, Advanced = exploration
- Faster access to merge/PR features without opening advanced dialog

The Merge and PR dialogs now open from the Repository dialog's "Branch Operations" section, making them easier to discover and use.
2025-10-14 14:39:50 -05:00
shakespeare.diy dad4ce0aa4 feat: Add comprehensive Git management UI (Phase 1 Critical Features)
Implement advanced Git client features with clean, beautiful UI:

NEW COMPONENTS:
- BranchManager: Create, switch, delete branches with visual interface
- DiffViewer: Side-by-side and unified diff views with syntax highlighting
- CompareView: Compare branches/commits with stats and file diffs
- MergeDialog: Merge branches with preview and conflict detection
- PullRequestDialog: Create PRs on GitHub/GitLab with full workflow
- GitManagementDialog: Main container with tabbed interface

FEATURES:
✨ Branch Management
  - Visual branch list (local and remote)
  - Create branches with validation
  - Switch/delete with confirmation
  - Current branch indicator

✨ Visual Diff Viewer
  - Side-by-side diff view
  - Unified diff view
  - Syntax highlighting (TypeScript, JavaScript, CSS, JSON, Markdown)
  - File tree navigation
  - Copy hunks to clipboard
  - Status badges (added/modified/deleted)

✨ Branch Comparison
  - Compare any two branches
  - Commits ahead/behind statistics
  - Files changed overview
  - Full diff view integration
  - Commit metadata display

✨ Merge Operations
  - Merge preview before execution
  - Fast-forward detection
  - Commit list preview
  - File change preview
  - Automatic rebuild after merge
  - Conflict detection

✨ Pull Request Creation
  - GitHub integration
  - GitLab integration
  - Auto platform detection
  - Target branch selection
  - Markdown description support
  - Credential validation
  - Direct link to created PR

INTEGRATIONS:
- Added prismjs for syntax highlighting
- Extended GitDialog with "Advanced" button
- Integrated with existing Git status monitoring
- Connected to credential management system

DOCUMENTATION:
- Comprehensive feature guide (GIT_FEATURES_GUIDE.md)
- Usage examples and workflows
- Troubleshooting section
- API documentation for AI assistants

DEPENDENCIES:
- prismjs@^1.30.0 (syntax highlighting)
- @types/prismjs@^1.26.5 (TypeScript types)

This completes Phase 1 (Critical Features) from the Git Client Project Plan.
All features tested and working with beautiful, clean UI design.
2025-10-14 14:35:02 -05:00
shakespeare.diy 7bb7939a4a docs: Add comprehensive Git client feature enhancement project plan
Create detailed roadmap for transforming Shakespeare into a fully-featured Git client with GitHub/GitLab parity.

Key sections:
- Current state analysis (what's already implemented)
- Missing features categorized and prioritized
- Implementation phases with timeline estimates
- Technical architecture and design principles
- Security considerations
- Testing strategy
- Success metrics

Features planned:
- Branch management UI with visual tree
- Pull request creation and review workflow
- Visual diff viewer with syntax highlighting
- Merge conflict resolution UI
- Advanced commit operations (rebase, cherry-pick, squash)
- Remote repository browser
- Git submodules and LFS support
- Encrypted credential management
- CI/CD integration

Estimated timeline: 6-8 months for full implementation
Priority focus: Phase 1 MVP (branch management, diff viewer, basic PR creation) in 6 weeks
2025-10-14 14:18:44 -05:00
Alex Gleason b454e9b4cb Merge branch 'shuffle-app-hotfix' into 'main'
Fix app shuffle on typing in new project view

See merge request soapbox-pub/shakespeare!59
2025-10-14 01:26:54 +00:00
shakespeare.diy abd132951f Fix app shuffle on typing in new project view
The AppShowcase component was re-shuffling apps on every render because useMemo dependencies were unstable (filtered arrays created new references on each render).

Fixed by consolidating all filtering and shuffling logic into a single useMemo with only the submissions array as a dependency. This ensures apps only shuffle when submissions data actually changes, not when user types in the text box.

Changes:
- Moved all filtering logic into single useMemo block
- Changed dependency from intermediate filtered arrays to just submissions
- Apps now maintain stable order while user types
2025-10-13 20:12:27 -05:00
Alex Gleason e9d7942e5e Remove unnecessary new Set calls 2025-10-13 19:41:59 -05:00
Alex Gleason 3cd6908d78 Fix cloning from git Nostr URLs 2025-10-13 19:33:48 -05:00
Alex Gleason 2ce2f15fcf Deemphasize Nostr in copy (still foundational, but behind the scenes) 2025-10-13 14:07:08 -05:00
Alex Gleason 027059fcb8 Make showcase configurable in System Settings 2025-10-12 23:41:21 -05:00
Alex Gleason 8d2c4b8284 Remove dialog focus outline 2025-10-12 23:31:18 -05:00
Alex Gleason 5c3c565174 "Edit with Shakespeare" internal link in showcase 2025-10-12 22:35:35 -05:00
Alex Gleason e648ecd8b8 Merge branch 'main' of gitlab.com:soapbox-pub/shakespeare 2025-10-12 22:30:21 -05:00
Alex Gleason b87934da1a Add special URL format to add a provider 2025-10-12 22:30:12 -05:00
Alex Gleason a2bde12926 Merge branch 'main' into 'main'
Improve showcase dark theme colors to match app theme

See merge request soapbox-pub/shakespeare!57
2025-10-13 03:19:36 +00:00
shakespeare.diy f2dd2cf7fa Improve showcase dark theme colors to match app theme
- Replace hardcoded gray colors with theme variables
- Use text-foreground instead of text-gray-900 for headings
- Use text-muted-foreground instead of text-gray-600 for descriptions and metadata
- Update background colors from gray-50/gray-100 to muted/muted-50
- Update avatar placeholders to use muted background and muted-foreground text
- Ensure consistent theming with rest of application in both light and dark modes
2025-10-12 20:25:57 -05:00
Alex Gleason d1818800c6 Fix lint errors 2025-10-12 19:26:56 -05:00
Alex Gleason 3de4b3771d Merge branch 'main' into 'main'
Implement app showcase on New Project view

See merge request soapbox-pub/shakespeare!56
2025-10-13 00:21:16 +00:00
shakespeare.diy 05682be587 Widen app showcase container to match original soapbox layout
- Change max-width from max-w-4xl (896px) to max-w-7xl (1280px)
- Add responsive padding (px-4 sm:px-6 lg:px-8) to match original
- Apply to all showcase states: loading, empty, and main content
- Apps now have the same width as the original soapbox showcase
2025-10-12 19:09:16 -05:00
shakespeare.diy d52d6d900d Move and rename "All Apps" section to "More Apps"
- Move "More Apps" section to appear after Templates section
- Rename from "All Apps" to "More Apps"
- Update subtitle from "all approved community apps" to "more community apps"
- Maintain collapsible functionality
2025-10-12 19:00:55 -05:00
shakespeare.diy fd8cda9ea8 Simplify app showcase cards
- Remove status badges (Featured, Homepage, Pending) from top-left corner
- Remove app tags display from card content
- Remove repository link/button, keeping only Shakespeare badge and visit app button
- Clean up unused imports (Badge, GitBranch, Copy icons)
- Streamline card layout for cleaner appearance
2025-10-12 18:58:45 -05:00
shakespeare.diy c65b8ff1b9 Remove showcase header, search bar, and tag filters
- Remove "Community Showcase" title and subtitle
- Remove search bar functionality
- Remove tag filtering UI and logic
- Simplify component to show all apps without filters
- Keep section headers for Featured Apps, Halloween Hackathon, All Apps, and Templates
- Maintain collapsible "All Apps" section
- Clean up unused imports and state variables
2025-10-12 18:54:31 -05:00
shakespeare.diy 13a197e80d Implement app showcase on New Project view
- Add useAppSubmissions hook to query Nostr events (kind 31733)
- Create AppShowcaseCard component for displaying individual apps
- Add AppShowcase component with search, filtering, and categorization
- Include featured apps, Halloween hackathon apps, templates, and approved apps sections
- Add shuffleArray utility function for randomizing app display order
- Integrate showcase into Index page underneath the prompt text box
- Support moderation controls for authorized users
- Add responsive design with mobile-friendly tag filtering
- Include empty states with relay selector for no results
2025-10-12 18:45:59 -05:00
Alex Gleason fe45508297 Improve README 2025-10-11 21:32:58 -05:00
Alex Gleason c517468bec Fix maskable icons 2025-10-11 19:30:48 -05:00
Alex Gleason 87c677739e Improve maskable icon 2025-10-11 19:17:18 -05:00
Alex Gleason 7d75dad6a7 Add maskable icons 2025-10-11 19:05:57 -05:00
Alex Gleason e633b8ffbf Add shakespeare-512x512.png 2025-10-11 19:01:36 -05:00
Alex Gleason 715b51a4dc Add Desktop screenshot to webmanifest 2025-10-11 18:53:27 -05:00
Alex Gleason 72fb41d69d Add webmanifest categories 2025-10-11 18:33:25 -05:00
Alex Gleason c450f4ac2d Add webmanifest screenshots 2025-10-11 18:25:53 -05:00
Alex Gleason 1954fada4e Fix manifest icons 2025-10-11 17:55:36 -05:00
Alex Gleason 1100d306de Improve manifest colors, add missing index.html meta tags 2025-10-11 17:18:11 -05:00
Alex Gleason c6baf5d3f9 Add basic passthrough ServiceWorker and robots.txt 2025-10-11 17:14:41 -05:00
Alex Gleason b7b34d7b43 Make AI presets responsive in AI Settings 2025-10-09 16:36:39 -05:00
Alex Gleason f7c8f31fbb Instruct to make commits automatically 2025-10-08 23:40:32 -05:00
Alex Gleason 7fd233a4f4 Use smaller submit button on homepage, same as inside a project 2025-10-08 23:34:51 -05:00
Alex Gleason cb1bb48c4c Fix tools for OpenAI models 2025-10-08 16:38:09 -05:00
Alex Gleason e28863f38a Add Google to presets 2025-10-08 16:31:48 -05:00
Alex Gleason 1bb949217a Support proxying AI provider traffic 2025-10-08 16:22:07 -05:00
Alex Gleason 0b95398f2d Let Deploy Server be configurable 2025-10-08 15:22:07 -05:00
Alex Gleason 9337b4c9ea Revert unnecessary verbiage added to corsProxyDescription 2025-10-08 15:14:08 -05:00
Alex Gleason b5039c76f8 Make project template (mkstack itself) configurable in System Settings 2025-10-08 15:13:15 -05:00
Alex Gleason 1432e968bc Move Preview Domain to bottom of system settings 2025-10-08 15:02:56 -05:00
Alex Gleason 45b0ae836a Make iframe previewDomain configurable 2025-10-08 15:01:40 -05:00
Alex Gleason b9d65e39b1 Consolidate services code into "services/" directory 2025-10-08 14:51:48 -05:00
Alex Gleason 1406306407 Make corsProxy a system setting instead of a git setting 2025-10-08 14:43:42 -05:00
Alex Gleason 278b146062 Data -> Storage 2025-10-08 14:05:22 -05:00
Alex Gleason d6b0ff7b13 Only set app config that's actually changed 2025-10-08 13:49:34 -05:00
Alex Gleason c95a41dd01 Make settings DRY 2025-10-08 13:36:43 -05:00
Alex Gleason 12710c58a7 Fix System Settings icon and position in some views 2025-10-08 13:21:55 -05:00
Alex Gleason a8990bbe3a Merge branch 'esmProxy' into 'main'
Include Cloudflare worker script for esm.shakespeare.diy

See merge request soapbox-pub/shakespeare!55
2025-10-08 06:51:56 +00:00
Chad Curtis a20ae242de Include Cloudflare worker script. 2025-10-08 06:46:04 +00:00
Alex Gleason ebbfea5c20 Merge branch 'esmProxy' into 'main'
Make esm source URL configurable, default to esm.shakespeare.diy

See merge request soapbox-pub/shakespeare!54
2025-10-08 06:33:25 +00:00
Chad Curtis 613f8b76bb Review fixes. 2025-10-08 05:37:05 +00:00
Chad Curtis 00485a6889 rm space 2025-10-08 04:46:21 +00:00
Alex Gleason 39509478b6 Add model pricing to model selector 2025-10-07 23:45:16 -05:00
Chad Curtis bacf6f2869 Cleanup 2025-10-08 04:44:13 +00:00
Alex Gleason f2933ba4b4 Display models list in tiers 2025-10-07 23:11:20 -05:00
Chad Curtis 9a6058fedb Dynamic URL in more places. 2025-10-08 03:55:10 +00:00
Chad Curtis fb487ea622 Actually show system settings in list. 2025-10-08 03:43:50 +00:00
Alex Gleason 73246c88a1 Improve display of models in OnboardingDialog 2025-10-07 22:15:13 -05:00
Chad Curtis 5bcf7d7b79 Merge branch 'main' of gitlab.com:soapbox-pub/act2 into esmProxy 2025-10-08 02:42:06 +00:00
Alex Gleason bda50285af Fix Quilly 2025-10-07 21:31:50 -05:00
Alex Gleason 92643a1355 Merge branch 'fix/45-ai-service-error-400-provider-returned-error' into 'main'
fix/45-ai-service-error-400-provider-returned-error

Closes #45

See merge request soapbox-pub/shakespeare!39
2025-10-08 02:31:06 +00:00
Alex Gleason a4228adf74 Simplify Act1Dialog 2025-10-07 21:27:15 -05:00
Alex Gleason 104d95d5ab Filter out empty assistant messages when saving the history file 2025-10-07 21:15:20 -05:00
Alex Gleason 496ab8722a Throw an error if the AI service return an empty assistant message 2025-10-07 21:13:04 -05:00
Alex Gleason ca45f62585 ModelSelector: display warning if model isn't in providers models list 2025-10-07 20:37:10 -05:00
Chad Curtis aa82aaf02c init 2025-10-07 23:41:23 +00:00
Alex Gleason 766c51ecde Merge branch 'yarn' into 'main'
Experimental yarn.lock conversion

See merge request soapbox-pub/shakespeare!52
2025-10-06 20:15:54 +00:00
Alex Gleason 00d4b9aaac Use tsconfig to resolve paths 2025-10-06 11:18:57 -05:00
Alex Gleason d0c039b37b Let esmPlugin accept a package.json, make packageLock optional 2025-10-06 09:02:41 -05:00
Alex Gleason 5cf0c60b88 Fix previewable test 2025-10-06 08:36:27 -05:00
Alex Gleason 15214490af Experimental yarn.lock conversion 2025-10-05 22:06:40 -05:00
Alex Gleason fa434957b7 Add 2 fragile hacks to make Jumble compile 2025-10-05 16:19:36 -05:00
Alex Gleason c21d0cca09 Fix resolving deep version conflicts 2025-10-05 16:05:37 -05:00
Alex Gleason a05b5e8610 Handle static assets as files in esbuild 2025-10-05 15:04:15 -05:00
Alex Gleason 275d8691cb Fix resolving deep jsr packages 2025-10-05 00:41:03 -05:00
sam 462bbb4298 lint fix 2025-10-05 11:15:53 +07:00
Alex Gleason ee18a63e0c esmPlugin breadcrumbs 2025-10-04 22:35:31 -05:00
sam 77d37f071a no error normalisation in session manager, let quilly look more closely at the open ai error to deduce what to do 2025-10-05 07:26:54 +07:00
sam 2869113d7d Merge branch 'main' into fix/45-ai-service-error-400-provider-returned-error 2025-10-05 07:15:15 +07:00
Alex Gleason 0f0f9e6945 Hide recentlyUsed models in the total list 2025-10-04 17:12:19 -05:00
Alex Gleason 07048d2b5f gitignore Android files 2025-10-04 17:01:41 -05:00
Alex Gleason d9a4efe2b2 eslint --fix 2025-10-04 15:18:03 -05:00
Alex Gleason d93b9b2670 Merge branch 'improvement/56-missing-git-commands' into 'main'
Improvement/56 missing git commands

Closes #56

See merge request soapbox-pub/shakespeare!49
2025-10-04 19:50:14 +00:00
Alex Gleason f2f1941a30 Merge branch 'easter-egg/shakespeare' into 'main'
easter-egg/shakespeare

See merge request soapbox-pub/shakespeare!50
2025-10-04 15:50:43 +00:00
sam a07241a0cb 📜 More light and light; more dark and dark our woes. 2025-10-04 22:01:51 +07:00
sam a343c4a530 test typing 2025-10-04 19:05:53 +07:00
sam f04ff1073e lint 2025-10-04 16:27:23 +07:00
sam 920b4c4426 lint config 2025-10-04 15:54:35 +07:00
sam 510fb3c4f6 lint - remove unused 2025-10-04 15:54:26 +07:00
sam 3972d57297 test stash 2025-10-04 15:54:06 +07:00
sam 804be34a3e wip git stash 2025-10-04 15:23:21 +07:00
sam 0653f3feb8 terminal colouring for git diffs 2025-10-04 12:36:02 +07:00
sam 3337e96cfa expand show command 2025-10-04 12:28:38 +07:00
Alex Gleason 08cbf296af Merge branch 'fix/48-tool-not-found-error-stops-user-in-their-tracks-add-to-quilly-detection' into 'main'
fix/48-tool-not-found-error-stops-user-in-their-tracks-add-to-quilly-detection

Closes #48

See merge request soapbox-pub/shakespeare!46
2025-10-04 05:27:04 +00:00
Alex Gleason 5eb90e17c9 Merge branch 'ui/convey-shakespeare-activity-in-app-favicon' into 'main'
ui/convey-shakespeare-activity-in-app-favicon

See merge request soapbox-pub/shakespeare!47
2025-10-04 05:26:31 +00:00
Alex Gleason b55e04ba77 Add Apple PWA tags 2025-10-04 00:19:01 -05:00
Alex Gleason 1c746e0bb8 Add safe-area plugin to tailwind.config.ts 2025-10-04 00:00:18 -05:00
Alex Gleason 4e163a032f Safe area inset improvements 2025-10-03 23:56:38 -05:00
Alex Gleason d9956e60eb Accept options object in JSRuntimeFS 2025-10-03 23:56:17 -05:00
sam 83b4fe54c7 test commit command 2025-10-04 07:55:27 +07:00
sam abecdaa5cc git commit, support -am flag 2025-10-04 07:13:38 +07:00
Alex Gleason a4c0498e5b Send { type: "object" } tool parameters when we don't care about the input
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/60
2025-10-03 13:04:10 -05:00
sam 2d8d5aa728 fix tests 2025-10-03 17:41:32 +07:00
sam 1eebef173f merge 2025-10-03 16:21:43 +07:00
sam 76979c6150 revert to handle individual error types explicitly
++

++

++
2025-10-03 16:18:32 +07:00
sam 4ebca7f077 lint 2025-10-03 16:18:32 +07:00
sam d2971fcdb9 test quilly renders the error 2025-10-03 16:18:32 +07:00
sam 1416c5d017 let quilly opine on tool call errors, and streamline handling errors 2025-10-03 16:18:32 +07:00
sam 8b5cf72356 define and surface an error for malformed tool responses 2025-10-03 16:18:32 +07:00
sam c48288f9e6 adapt console error type to simplify quillys understand 2025-10-03 16:18:32 +07:00
sam b419f88571 lint 2025-10-03 15:01:30 +07:00
sam 3f5667d62a warn but don't fail on lint errors 2025-10-03 15:01:23 +07:00
sam 7abb0ace5a define lint spec for spaces > tabs and complete vscode/cursor setup for auto linting
lint

drop over zealous rule
2025-10-03 13:02:16 +07:00
sam 39adaef4c4 while any project session is 'busy', keep the favicon spinning 2025-10-03 13:02:16 +07:00
Alex Gleason 388afd0b16 Enable sourcemap in Shakespeare itself 2025-10-02 17:59:29 -05:00
Alex Gleason 5f2faaad61 Fix xAI tool definitions
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/57
2025-10-02 17:57:36 -05:00
Alex Gleason aaf30db257 Add DeepSeek as a preset provider
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/58
2025-10-02 17:46:08 -05:00
Alex Gleason d4c775828f Fix build tests 2025-10-02 17:36:42 -05:00
Alex Gleason cbf85313af Enable sourcemap, fix output filenames 2025-10-02 17:30:12 -05:00
Alex Gleason 0b7f9cd2cb Update browserlist 2025-10-02 16:24:14 -05:00
Alex Gleason e0620bcca0 Merge branch 'consoleFramev4' into 'main'
Refactor console error to be provider level, simplifying console message/error tracking

See merge request soapbox-pub/shakespeare!48
2025-10-02 21:21:58 +00:00
Chad Curtis 97f5481ec7 Only clear console messages when project actually changes. 2025-10-02 20:58:56 +00:00
Alex Gleason 225c90f556 Surgically add esm.sh to existing CSP of index.html 2025-10-02 15:43:27 -05:00
Chad Curtis 51ce9c61ef Remove spurrious migration comment. 2025-10-02 20:30:02 +00:00
Alex Gleason c72170f19c Build by actually mimicking Vite's handling of index.html 2025-10-02 15:26:27 -05:00
Chad Curtis 111ab724e5 Remove and simplify some logic. 2025-10-02 20:15:30 +00:00
Chad Curtis 23c3cead89 Move non-tool logic out of tool file. 2025-10-02 20:09:09 +00:00
Chad Curtis 945c4209e8 Remove frivilous UI updates. 2025-10-02 20:02:16 +00:00
Chad Curtis 7574085213 Refactor console error to be provider level, tracking error via boolean rather than full logs as state. 2025-10-02 19:58:53 +00:00
Alex Gleason 3fba26ddb7 Switch payment method to a tabbed UI instead of dropdown 2025-10-01 17:24:22 -05:00
Alex Gleason bbcc56c800 Fix ModelSelector test 2025-10-01 17:13:23 -05:00
Alex Gleason cb794b5719 We do a little discord coding 2025-10-01 17:08:31 -05:00
Alex Gleason 931733ba16 Add warning to model selector if a free model is chosen 2025-10-01 16:38:16 -05:00
shakespeare.diy 52fe76c9c6 Improve README: Add 🎭 emoji, website link, edit button, and license 2025-09-30 20:00:08 -05:00
Alex Gleason 7f5265cc92 Fix shell redirection 2025-09-30 15:06:47 -05:00
Alex Gleason 7f4b7f2a03 Add "sed" command 2025-09-30 14:59:48 -05:00
Alex Gleason 34ede4b799 Fix "git reset" 2025-09-30 14:41:32 -05:00
Alex Gleason d5c28c3097 Fix "git diff" 2025-09-30 13:17:58 -05:00
Alex Gleason 31de1b934d Fix git diff command 2025-09-30 13:12:04 -05:00
Alex Gleason 45f1202b9d Implement "git fetch" 2025-09-30 12:55:53 -05:00
Alex Gleason b4f0ede7b7 Remove extraneous "Exploring Other Projects" section from system prompt 2025-09-30 12:51:11 -05:00
Alex Gleason df39f78d20 Fix "git pull" listing changed files 2025-09-30 12:47:21 -05:00
Alex Gleason b7e94ff67c Start fixing "git pull" 2025-09-30 12:42:57 -05:00
Alex Gleason 8b981dcf36 Add special handling when viewing projects/ and .git to text_editor_view tool 2025-09-30 12:13:49 -05:00
Alex Gleason f702d2300b Add special handling for viewing /projects 2025-09-30 12:06:52 -05:00
Alex Gleason 4edbb8a73a Remove gitignore functionality from text_editor_view tool 2025-09-30 11:55:25 -05:00
Alex Gleason 98f584a851 Teach Shakespeare that it can look at other projects 2025-09-30 11:17:06 -05:00
Alex Gleason 8b438c8c1b Scroll down when Quilly appears 2025-09-29 22:19:18 -05:00
Alex Gleason d18cfb4849 Truncate model description 2025-09-29 18:21:34 -05:00
Alex Gleason b04c1440b5 Improve display of buttons 2025-09-29 18:01:49 -05:00
Alex Gleason 5fa16115fd Rebuild project after saving file
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/53
2025-09-29 17:51:25 -05:00
Alex Gleason 795eaa50c2 Make Quilly's "fix error" add assistant messages 2025-09-29 17:19:02 -05:00
Alex Gleason 3da2075539 Ensure console errors get passed to Quilly on desktop 2025-09-29 17:01:30 -05:00
Alex Gleason a87063f6e9 Fix types in test 2025-09-29 16:55:28 -05:00
Alex Gleason 75cab68281 Clean up directory if cloning fails 2025-09-29 16:48:35 -05:00
Alex Gleason 1abc37f388 Actually, bring back the custom scrollbars 2025-09-29 16:29:58 -05:00
Alex Gleason 24c8525360 Fix OnboardingDialog height, remove scrollbar customizations, add comma 2025-09-29 16:20:36 -05:00
Alex Gleason 2f4fb16e94 Slight improvement to "quality of output" statement 2025-09-29 16:09:59 -05:00
Alex Gleason 3e8d5fb87c Fix tiny checkboxes on AI Settings page 2025-09-29 16:06:12 -05:00
Alex Gleason 7b438bae34 Display credits badge in Onboarding if the user is coming from Act1 2025-09-29 16:00:43 -05:00
Alex Gleason cb4cc16760 Don't configure users through the Act1Dialog, still force them to go through the normal onboarding flow 2025-09-29 15:41:57 -05:00
Alex Gleason aca620e460 Add ToS agreement to AI Settings page 2025-09-29 15:23:58 -05:00
Alex Gleason 89db9c354a Require agreement to AI Provider ToS in OnboardingDialog 2025-09-29 15:13:59 -05:00
Alex Gleason fc0134a3a8 Add tosURL to preset AI providers 2025-09-29 15:09:03 -05:00
Alex Gleason 2477b5417c Add provider step to onboarding 2025-09-29 15:00:40 -05:00
Alex Gleason 92483728d0 Scroll OnboardingDialog to top when navigating between steps 2025-09-29 13:41:48 -05:00
Alex Gleason ba0ec1f420 Add Open Source section to OnboardingDialog 2025-09-29 13:35:39 -05:00
Alex Gleason bdcaa2ef76 When a package imports itself, use the same version as the importer 2025-09-28 17:27:41 -05:00
Alex Gleason d1d8f1dd15 Fix CSS relative imports 2025-09-28 10:16:22 -05:00
Alex Gleason 66d08d05de Merge branch 'ui/47-github-connection-failure-error-toast-disappears-before-i-can-make-sense-of-it' into 'main'
ui/47-github-connection-failure-error-toast-disappears-before-i-can-make-sense-of-it

Closes #47

See merge request soapbox-pub/shakespeare!41
2025-09-28 14:40:24 +00:00
sam bb8912dd57 show git failure toasts indefinitely 2025-09-28 16:10:59 +07:00
sam 8ce69023af functional -> imperative :| 2025-09-28 14:57:34 +07:00
sam f8350e1d62 fix junk indentation 2025-09-28 14:13:33 +07:00
Alex Gleason 804cdbd789 Merge branch 'fix/49-quilly-doesnt-show-up-on-mobile-when-you-have-console-errors' into 'main'
fix/49-quilly-doesnt-show-up-on-mobile-when-you-have-console-errors

Closes #49

See merge request soapbox-pub/shakespeare!40
2025-09-28 04:56:48 +00:00
Alex Gleason f022332595 Add shakespeare.svg and ShakespeareLogo component 2025-09-27 23:47:53 -05:00
Alex Gleason ba509584b7 Merge branch 'minorDesignUpdates' into 'main'
Minor Design Updates (Optional)

See merge request soapbox-pub/shakespeare!37
2025-09-28 04:41:03 +00:00
Alex Gleason 787877d2c7 Handle data: URLs 2025-09-27 23:15:58 -05:00
Alex Gleason 0b269f78a4 Resolve from peerDependencies, then just fallback to the latest version 2025-09-27 23:11:22 -05:00
lemonknowsall 7a11137aed save nav padding for terminal 2025-09-27 20:59:59 -07:00
lemonknowsall 1d0231bc03 file viewer scrolling 2025-09-27 20:59:46 -07:00
lemonknowsall 8b62ba8e7e Updated logos, default theme, onboard modals, and mobile browser fixes 2025-09-27 20:59:36 -07:00
Alex Gleason 4e0625721e Fix compatibility with leaflet 2025-09-27 22:42:42 -05:00
Alex Gleason 3529d43b91 Support json imports 2025-09-27 22:28:21 -05:00
Alex Gleason 93a636589d Fix Tailwind styles 2025-09-27 22:22:49 -05:00
Alex Gleason eba609ae73 NpmAddPackageTool should not bump the package version 2025-09-27 21:40:32 -05:00
Alex Gleason 8c60a3a8bc Externalize static assets like fonts 2025-09-27 21:23:45 -05:00
Alex Gleason 939deabb5b Support Vite query params of local imports, specifically ?raw 2025-09-27 21:07:28 -05:00
Alex Gleason 2ec32f5537 Polyfill virtual:pwa-register/react 2025-09-27 20:39:51 -05:00
sam 124e9d5937 wip, bring error handling up to the project level to exist across mobile tabs 2025-09-28 08:37:45 +07:00
Alex Gleason b064c9ff86 Mock "sonner" and "next-themes" when building 2025-09-27 20:20:04 -05:00
Alex Gleason a9a5cafcac Don't hardcode gitnostr.com 2025-09-27 16:26:07 -05:00
Alex Gleason 2db9d5e513 Move Import ZIP File to Clone page 2025-09-27 15:43:43 -05:00
Alex Gleason e8156243d0 Simplify Nostr Settings loading skeleton 2025-09-27 14:48:06 -05:00
Alex Gleason e9c73693ce Move email newsletter into Settings 2025-09-27 14:29:18 -05:00
sam a474cd8cee use generic openai error types but with specific codes 2025-09-27 21:39:42 +07:00
sam 10ea68547c use specific openai errors 2025-09-27 21:38:48 +07:00
sam 00d9d4d005 Revert "lint"
This reverts commit d02d8959f6.
2025-09-27 21:28:41 +07:00
sam d02d8959f6 lint 2025-09-27 21:08:25 +07:00
sam 5a5bec28c4 offer the user two routes forward when their keys run dry 2025-09-27 19:17:17 +07:00
sam 4ce51b3659 handle 403s 2025-09-27 19:13:10 +07:00
sam cf29632261 support presenting two options in quilly and for 400s suggest either a new convo or a model change 2025-09-27 18:48:30 +07:00
sam ecdb33460d broader error desc 2025-09-27 18:39:48 +07:00
sam 52198a0a3c handle 400s too 2025-09-27 18:34:54 +07:00
sam 185cdc51fb handle 422s and surface to quilly 2025-09-27 18:08:17 +07:00
Alex Gleason 1a9a553523 Remove @apply 2025-09-26 21:41:21 -05:00
Alex Gleason fc6a70793f Fix scrolling the virtual terminal on mobile 2025-09-26 21:22:16 -05:00
Alex Gleason fba1328e5f Build after pulling 2025-09-26 21:13:12 -05:00
Alex Gleason a45e29578c Fix pulling 2025-09-26 20:49:02 -05:00
Alex Gleason c1cbbed05c About page improvements 2025-09-26 20:33:48 -05:00
Alex Gleason d95abf2499 Terminal autoCapitalize=off 2025-09-26 20:18:40 -05:00
Alex Gleason 4316b766e2 Fix git add 2025-09-26 19:55:01 -05:00
Alex Gleason 8800a55eed Fix git status 2025-09-26 19:11:57 -05:00
Alex Gleason 48dfd2d99e Fix mobile terminal issues 2025-09-26 19:00:07 -05:00
Alex Gleason cb971955ae Improve terminal UX 2025-09-26 18:51:25 -05:00
Alex Gleason deb593c1b6 Improve terminal input display 2025-09-26 18:09:13 -05:00
Alex Gleason 3b3637009d Fix focus in TUI 2025-09-26 18:01:40 -05:00
Alex Gleason dc50d41928 Add virtual terminal to Code tab 2025-09-26 17:39:12 -05:00
Alex Gleason ca334d7585 Hide model search input unless there are >= 5 models 2025-09-26 17:18:00 -05:00
Alex Gleason 57a80ad33d Fix Gemini model tool_calls 2025-09-26 14:38:38 -05:00
Alex Gleason a05ad13e67 Don't send tool_choice param 2025-09-26 14:14:10 -05:00
Alex Gleason 247919a24b Remove AboutSettings test 2025-09-26 12:36:30 -05:00
Alex Gleason 9b43f07372 Make email configuration more manageable 2025-09-26 12:31:52 -05:00
Alex Gleason af8fb22438 Display license in accordion on About page, use html version of AGPL 2025-09-26 12:12:24 -05:00
Alex Gleason fc4e82c26d Remove legacy migrations from configUtils, parse with zod 2025-09-26 12:01:02 -05:00
Alex Gleason 3b305b5b86 Remove OpenRouter credits parsing (their responses are not accurate anyway) 2025-09-26 11:38:20 -05:00
Alex Gleason 456ea946e7 Refetch credits when AI providers change 2025-09-26 11:37:20 -05:00
Alex Gleason 6c770630d8 Merge branch 'uploadKeyFile' into 'main'
Upload key file

See merge request soapbox-pub/shakespeare!34
2025-09-26 06:23:04 +00:00
Alex Gleason 8f4598b9b8 Merge branch 'iOS-updates' into 'main'
iOS Safe Inset Navigation & Accessibility Zoom

See merge request soapbox-pub/shakespeare!35
2025-09-26 06:21:45 +00:00
lemonknowsall 64c06ec430 upload key file 2025-09-25 22:03:44 -07:00
lemonknowsall 29aae4f55b user scalable no for mobile accessibility 2025-09-25 21:35:09 -07:00
lemonknowsall fb12bda5fa nav safe inset and text highlight 2025-09-25 21:29:26 -07:00
Alex Gleason 7348aaf9ce Don't autofocus project name in ProjectDetailsDialog 2025-09-25 20:22:29 -05:00
Alex Gleason 8948507b6f Fix autostart and model params being removed from URL after project start 2025-09-25 20:00:08 -05:00
Alex Gleason 2dbb9a23e3 Fix CSP for esbuild-wasm 2025-09-25 19:59:49 -05:00
Alex Gleason 11867b3bb2 Add Quilly to the homepage 2025-09-25 19:37:27 -05:00
Alex Gleason 0f82ab15ec Only send X-Title and HTTP-Referer to OpenRouter 2025-09-25 19:13:04 -05:00
Alex Gleason 80ae098323 Re-enable CSP 2025-09-25 18:51:05 -05:00
Alex Gleason fa64a5ce52 Remove Act1Dialog tests 2025-09-25 18:14:51 -05:00
Alex Gleason 870e2f6b9b Mark that the user is a previous Act 1 user 2025-09-25 18:14:31 -05:00
Alex Gleason 26c09733f8 Improve Act1Dialog copy 2025-09-25 18:09:04 -05:00
Alex Gleason 2a80e586ba Add a separate Credits screen to Act1Dialog 2025-09-25 17:53:14 -05:00
Alex Gleason 9f20fd6196 Fix scrolling in Act1Dialog 2025-09-25 17:45:33 -05:00
Alex Gleason 94bcc7eccb Start adding Act 1 dialog 2025-09-25 17:34:38 -05:00
Alex Gleason f62b2f807c .ai -> .git/ai 2025-09-25 15:11:01 -05:00
271 changed files with 28764 additions and 5420 deletions

No files matched your search

+10 -1
View File
@@ -1,2 +1,11 @@
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="********************"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="****************************************"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="********************"
VITE_VERCEL_OAUTH_CLIENT_SECRET="****************************************"
+3
View File
@@ -12,6 +12,8 @@ dist
dist-ssr
*.local
.ai-history/
*.apk
*.aab
# Editor directories and files
.idea
@@ -30,3 +32,4 @@ dist-ssr
.env.*
!.env.example
.ai/
*.keystore
+3 -2
View File
@@ -1,3 +1,4 @@
{
"editor.tabSize": 2
}
"editor.tabSize": 2,
"editor.insertSpaces": true
}
+2 -2
View File
@@ -1,6 +1,6 @@
# Shakespeare - AI-Powered Nostr Website Builder
# Shakespeare - AI-Powered App Builder
Shakespeare is a browser-based AI chat application that allows users to build custom Nostr websites through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
Shakespeare is a browser-based AI chat application that allows users to build custom web applications through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
### Virtual Filesystem Layout
+20 -71
View File
@@ -1,85 +1,34 @@
# Shakespeare - AI-Powered Nostr Website Builder
# Shakespeare 🎭
Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it.
[![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git)
Shakespeare is an open-source AI app builder that runs entirely in your browser.
https://shakespeare.diy
## Features
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
- **Project Management**: Create and manage multiple projects with sidebar navigation
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **File Explorer**: Browse and manage your project files
- **Project Preview**: Preview your website as you build it
- **Template Cloning**: Start from a pre-configured Nostr template
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
- **Buy credits anonymously** with Nostr and Lightning ⚡
- **Runs entirely in the browser** No backend required
## Getting Started
## How it Works
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
4. **Edit Code**: Switch to the code view to manually edit files if needed
5. **Preview**: View your website in the preview pane
Shakespeare is a React PWA that stores files in IndexedDB with [LightningFS](https://github.com/isomorphic-git/lightning-fs). Your browser connects directly to AI providers and git services (through [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git)) to enable you to build and deploy AI apps entirely from your device.
## Project Structure
Shakespeare hosts no backend (except for a couple microservices in the `services/` directory; these are fully configurable within Shakespeare's settings). All your code and configuration is stored in your browser.
Each project includes:
- React 18 with TypeScript
- Vite for building
- TailwindCSS for styling
- Nostrify for Nostr integration
- shadcn/ui components
Configure any AI providers and git services you want. Configuration is stored entirely in the browser in localStorage.
## AI Capabilities
You can then push and pull code to syncronize your work across devices.
The AI assistant can:
- Read and write project files
- Add new components and pages
- Configure Nostr functionality
- Build the project
- Search through files
- Provide project structure overview
- Add and remove npm packages
- Install dependencies and dev dependencies
Shakespeare can work on any type of project. But it is specialized to build React applications in TypeScript, which it compiles in the browser with [esbuild-wasm](https://www.npmjs.com/package/esbuild-wasm) and custom plugins. Any codebase can be worked on, but only compatible projects can be previewed directly in Shakespeare.
## Usage
## Open Source
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
3. **File Explorer**: Navigate your project files in the code view
4. **File Editor**: Edit files with syntax highlighting and save changes
Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The purpose of Shakespeare is to provide a free and open platform for building AI applications that respects user privacy and freedom.
## Git Integration
## Alternatives
Shakespeare includes full Git functionality with credential management:
### Features
- **Version Control**: Full Git repository support with commit history and branch management
- **Global Credentials**: Configure Git credentials once and use them across all projects
- **Automatic Matching**: Credentials are automatically matched to repository origins
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
### Setting Up Git Credentials
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
3. **Enter Token**: Use your username and personal access token for authentication
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
### Repository Operations
- **Push/Pull**: Sync changes with remote repositories using configured credentials
- **Status Monitoring**: Real-time Git status with file changes and sync information
- **Commit History**: View commit history and repository information
- **Branch Management**: Work with different branches and track remote changes
## Development
Built with:
- React 18
- TypeScript
- Vite
- TailwindCSS
- shadcn/ui
- LightningFS for filesystem
- isomorphic-git for template cloning
- [goose](https://github.com/block/goose) - open-source desktop app and cli utilizing your full computer for AI tasks
- [bolt.diy](https://github.com/stackblitz-labs/bolt.diy) - similar to Shakespeare, but built on closed-source WebContainers technology
+544
View File
@@ -0,0 +1,544 @@
# Unified OAuth System
Shakespeare implements a unified OAuth 2.0 authentication system that supports multiple providers with a consistent API. This document explains how the system works and how to add new OAuth providers.
## Architecture
The OAuth system consists of three main components:
1. **Generic OAuth Hook** (`useOAuth`) - Core OAuth logic that works with any provider
2. **Provider-Specific Hooks** - Thin wrappers that configure the generic hook for specific providers
3. **OAuth Callback Pages** - React components that handle the OAuth redirect flow
### Current Supported Providers
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
## File Structure
```
src/
├── hooks/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
## Environment Variables
OAuth credentials are stored in environment variables and loaded from `process.env`:
```bash
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="your_github_client_id"
VITE_GITHUB_OAUTH_CLIENT_SECRET="your_github_client_secret"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="your_netlify_client_id"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="your_netlify_client_secret"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="your_vercel_client_id"
VITE_VERCEL_OAUTH_CLIENT_SECRET="your_vercel_client_secret"
```
### Security Note
**Client secrets are stored in environment variables** and bundled into the client-side JavaScript. This is necessary because the OAuth flow runs entirely in the browser. While this approach is less secure than a traditional server-side OAuth flow, it's acceptable for this use case because:
1. Shakespeare is a client-side application with no backend
2. The OAuth tokens are scoped to specific permissions
3. Users can revoke tokens at any time from the provider's settings
4. The redirect URIs are validated by the OAuth provider
For production deployments, consider using a serverless function or backend service to handle the token exchange step, keeping client secrets secure.
## How It Works
### 1. Generic OAuth Hook (`useOAuth`)
The `useOAuth` hook implements the OAuth 2.0 authorization code flow with optional PKCE (Proof Key for Code Exchange) support. It accepts a configuration object and returns methods to initiate and handle the OAuth flow.
**Configuration Interface:**
```typescript
interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel'; // Provider identifier
clientId: string; // OAuth client ID
clientSecret: string; // OAuth client secret
authorizeUrl: string; // Provider's authorization endpoint
tokenUrl: string; // Provider's token exchange endpoint
scope?: string; // Requested OAuth scopes (optional)
redirectUri: string; // Callback URL after authorization
usePKCE?: boolean; // Enable PKCE (default: false)
getUserInfo?: ( // Optional function to fetch user info
accessToken: string,
corsProxy: string
) => Promise<{
username: string;
[key: string]: unknown;
}>;
}
```
**Returned API:**
```typescript
{
isLoading: boolean; // True during token exchange
error: string | null; // Error message if OAuth fails
isOAuthConfigured: boolean; // True if client ID and secret are set
initiateOAuth: () => void; // Start the OAuth flow
handleCallback: ( // Handle the OAuth callback
code: string,
state: string
) => Promise<OAuthResult | null>;
}
```
### 2. OAuth Flow Steps
#### Step 1: Initiate OAuth
When the user clicks "Connect to [Provider]", the `initiateOAuth()` function:
1. Generates a random `state` parameter for CSRF protection
2. Optionally generates PKCE parameters (code verifier and challenge)
3. Stores the state and code verifier in localStorage
4. Redirects to the provider's authorization page
```typescript
const { initiateOAuth } = useGitHubOAuth();
// User clicks button
<Button onClick={initiateOAuth}>Connect to GitHub</Button>
```
#### Step 2: User Authorizes
The user is redirected to the provider's authorization page where they:
1. Log in to their account (if not already logged in)
2. Review the requested permissions
3. Approve or deny the authorization request
#### Step 3: OAuth Callback
After authorization, the provider redirects back to the callback URL with:
- `code` - Authorization code
- `state` - The state parameter we sent
- `error` (optional) - Error code if authorization failed
- `error_description` (optional) - Human-readable error description
The callback page (e.g., `GitHubOAuth.tsx`) extracts these parameters and calls `handleCallback()`.
#### Step 4: Token Exchange
The `handleCallback()` function:
1. Verifies the `state` parameter matches what we stored
2. Retrieves the PKCE code verifier (if PKCE is enabled)
3. Exchanges the authorization code for an access token
4. Optionally fetches user information using the access token
5. Returns an `OAuthResult` object with the token and user data
```typescript
interface OAuthResult {
accessToken: string; // OAuth access token
username?: string; // User's username/email
scopes?: string[]; // Granted OAuth scopes
userData?: Record<string, unknown>; // Additional user data
}
```
#### Step 5: Store Credentials
Provider-specific hooks override `handleCallback` to store the credentials appropriately:
- **GitHub**: Stores in Git settings (for push/pull operations)
- **Netlify/Vercel**: Stores in Deploy settings (for deployment operations)
### 3. PKCE Support
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow by preventing authorization code interception attacks. It's recommended for public clients like browser-based apps.
**How PKCE works:**
1. Generate a random `code_verifier` (cryptographically random string)
2. Create a `code_challenge` by hashing the verifier with SHA-256
3. Send the `code_challenge` during authorization
4. Send the `code_verifier` during token exchange
5. The server verifies that the verifier matches the challenge
**Enabling PKCE:**
```typescript
const config: OAuthConfig = {
// ... other config
usePKCE: true, // Enable PKCE
};
```
**Provider Support:**
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
### Scope Parameter
The `scope` parameter is optional in the OAuth configuration. Some providers (like Netlify) don't use scopes in the authorization request - instead, permissions are configured when you create the OAuth application in the provider's settings.
**Provider Scope Usage:**
- ✅ 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`)
## Adding a New OAuth Provider
To add a new OAuth provider, follow these steps:
### 1. Add Environment Variables
Add the client ID and secret to `.env.example`:
```bash
# NewProvider OAuth Configuration
VITE_NEWPROVIDER_OAUTH_CLIENT_ID="********************"
VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET="****************************************"
```
### 2. Create Provider-Specific Hook
Create a new file `src/hooks/useNewProviderOAuth.ts`:
```typescript
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { proxyUrl } from '@/lib/proxyUrl';
interface NewProviderUserInfo {
id: string;
email: string;
// ... other user fields
}
export function useNewProviderOAuth() {
// Get the context where you want to store credentials
// e.g., useDeploySettings() or useGitSettings()
const { setProviders, settings } = useDeploySettings();
const config: OAuthConfig = {
provider: 'newprovider',
clientId: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://provider.com/oauth/authorize',
tokenUrl: 'https://provider.com/oauth/token',
scope: 'read write', // Optional - omit if provider doesn't use scopes
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!userResponse.ok) {
throw new Error(`Failed to verify token: ${userResponse.statusText}`);
}
const userData: NewProviderUserInfo = await userResponse.json();
return {
username: userData.email,
...userData,
};
},
};
const oauth = useOAuth(config);
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Store the credentials in the appropriate context
// This will vary based on what the provider is used for
const newProvider = {
id: crypto.randomUUID(),
name: result.username ? `NewProvider (${result.username})` : 'NewProvider',
type: 'newprovider',
apiKey: result.accessToken,
proxy: true,
};
setProviders([...settings.providers, newProvider]);
return true;
}, [oauth, setProviders, settings.providers]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
};
}
```
### 3. Create OAuth Callback Page
Create a new file `src/pages/NewProviderOAuth.tsx`:
```typescript
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
export default function NewProviderOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useNewProviderOAuth();
const { toast } = useToast();
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('newprovider_oauth_state');
if (error) {
toast({
title: "NewProvider OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/deploy'); // or appropriate settings page
return;
}
if (code && state && storedState) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "NewProvider Connected",
description: "Successfully connected to NewProvider.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to NewProvider. Please try again.",
variant: "destructive",
});
}
navigate('/settings/deploy'); // or appropriate settings page
});
} else {
navigate('/settings/deploy');
}
}, [searchParams, handleCallback, toast, navigate]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
{/* Provider logo/icon */}
<div className="flex justify-center">
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24">
{/* Provider icon SVG */}
</svg>
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to NewProvider</h1>
<p className="text-muted-foreground">
Processing your NewProvider authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
```
### 4. Add Route
Add the OAuth callback route to `src/AppRouter.tsx`:
```typescript
import NewProviderOAuth from "./pages/NewProviderOAuth";
// ...
<Route path="/oauth/newprovider" element={<NewProviderOAuth />} />
```
### 5. Add to UI
Add the provider to the appropriate settings page (e.g., `DeploySettings.tsx`):
```typescript
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
// In component:
const newProviderOAuth = useNewProviderOAuth();
// In PRESET_PROVIDERS array:
{
id: 'newprovider',
type: 'newprovider',
name: 'NewProvider',
description: 'Deploy to NewProvider',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://provider.com/settings/tokens',
proxy: true,
}
// In the render logic, add the OAuth hook to the switch:
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
preset.type === 'vercel' ? vercelOAuth :
preset.type === 'newprovider' ? newProviderOAuth : null;
```
### 6. Register OAuth Application
Register your OAuth application with the provider:
1. Go to the provider's developer settings
2. Create a new OAuth application
3. Set the **redirect URI** to: `https://yourdomain.com/oauth/newprovider`
4. Note the **client ID** and **client secret**
5. Add them to your `.env` file
## Testing OAuth Flow
To test the OAuth flow locally:
1. **Set up a tunnel** (e.g., ngrok, cloudflared) to expose localhost:
```bash
npx cloudflared tunnel --url http://localhost:5173
```
2. **Register OAuth app** with the tunnel URL as the redirect URI:
```
https://your-tunnel-url.trycloudflare.com/oauth/provider
```
3. **Add credentials** to `.env`:
```bash
VITE_PROVIDER_OAUTH_CLIENT_ID="your_client_id"
VITE_PROVIDER_OAUTH_CLIENT_SECRET="your_client_secret"
```
4. **Start the dev server**:
```bash
npm run dev
```
5. **Test the flow** by clicking the "Connect to Provider" button
## Error Handling
The OAuth system handles several types of errors:
### User Denies Authorization
If the user denies authorization, the provider redirects with an `error` parameter:
```
/oauth/provider?error=access_denied&error_description=User+denied+access
```
The callback page displays an error toast and redirects to settings.
### Invalid State Parameter
If the `state` parameter doesn't match what we stored (CSRF attack), the flow is aborted and an error is shown.
### Token Exchange Failure
If the token exchange fails (invalid code, expired, etc.), an error is logged and shown to the user.
### Missing PKCE Verifier
If PKCE is enabled but the code verifier is missing from localStorage, the flow is aborted.
## Security Considerations
1. **State Parameter**: Always used for CSRF protection
2. **PKCE**: Used when supported by the provider for additional security
3. **HTTPS Only**: OAuth should only be used over HTTPS in production
4. **Token Storage**: Tokens are stored in browser storage (localStorage/IndexedDB)
5. **Token Revocation**: Users can revoke tokens from the provider's settings
6. **Scope Limitation**: Request only the minimum required scopes
## Troubleshooting
### "OAuth client ID not configured"
The environment variables are not set. Check your `.env` file and ensure the variables are prefixed with `VITE_`.
### "Invalid OAuth state parameter"
The state parameter doesn't match. This could be caused by:
- Multiple OAuth flows running simultaneously
- Browser localStorage being cleared mid-flow
- CSRF attack attempt
### "Failed to verify token"
The provider's API rejected the access token. This could be caused by:
- Incorrect API endpoint URL
- Token doesn't have required scopes
- Provider API is down
### Redirect URI Mismatch
The redirect URI in your OAuth app registration must exactly match the URI in your code:
```typescript
redirectUri: window.location.origin + '/oauth/provider'
```
For local development with a tunnel, this would be:
```
https://your-tunnel-url.trycloudflare.com/oauth/provider
```
## Best Practices
1. **Always use PKCE** when the provider supports it
2. **Request minimal scopes** - only what you need
3. **Handle errors gracefully** - show user-friendly error messages
4. **Clear localStorage** on errors to prevent stuck states
5. **Validate tokens** by fetching user info after exchange
6. **Store tokens securely** - use appropriate browser storage APIs
7. **Provide token revocation** - link to provider's token management page
8. **Test error cases** - user denial, network failures, etc.
## Future Improvements
Potential enhancements to the OAuth system:
1. **Token Refresh**: Implement refresh token flow for long-lived sessions
2. **Token Expiry**: Track token expiration and prompt for re-authentication
3. **Multiple Accounts**: Support multiple accounts per provider
4. **Backend Proxy**: Optional backend service for secure token exchange
5. **Device Flow**: Support OAuth device flow for CLI tools
6. **Biometric Auth**: Integrate with WebAuthn for passwordless OAuth
+7
View File
@@ -40,11 +40,18 @@ export default tseslint.config(
"ignoreRestSiblings": true,
},
],
"indent": [
"warn",
2,
{ SwitchCase: 1 },
],
"no-tabs": "warn",
"custom/no-placeholder-comments": "error",
"no-warning-comments": [
"error",
{ terms: ["fixme"] },
],
"no-control-regex": "off", // Allow ANSI escape sequences in regex
},
},
{
+12 -7
View File
@@ -2,14 +2,19 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shakespeare - AI-Powered Nostr Development</title>
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Shakespeare - Open Source AI Builder</title>
<meta name="description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
<link rel="icon" type="image/png" href="/favicon.png">
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
<meta name="theme-color" content="#2b0037">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
+70 -3
View File
@@ -14,6 +14,7 @@
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@icons-pack/react-simple-icons": "^13.8.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.5",
@@ -60,11 +61,14 @@
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
"isomorphic-git": "^1.32.1",
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
@@ -79,6 +83,7 @@
"streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
@@ -97,6 +102,7 @@
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
@@ -1193,6 +1199,15 @@
"url": "https://github.com/sponsors/nzakas"
}
},
"node_modules/@icons-pack/react-simple-icons": {
"version": "13.8.0",
"resolved": "https://registry.npmjs.org/@icons-pack/react-simple-icons/-/react-simple-icons-13.8.0.tgz",
"integrity": "sha512-iZrhL1fSklfCCVn68IYHaAoKfcby3RakUTn2tRPyHBkhr2tkYqeQbjJWf+NizIYBzKBn2IarDJXmTdXd6CuEfw==",
"license": "MIT",
"peerDependencies": {
"react": "^16.13 || ^17 || ^18 || ^19"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@@ -3802,6 +3817,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/prismjs": {
"version": "1.26.5",
"resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz",
"integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/prop-types": {
"version": "15.7.14",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz",
@@ -4668,9 +4690,9 @@
}
},
"node_modules/caniuse-lite": {
"version": "1.0.30001716",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001716.tgz",
"integrity": "sha512-49/c1+x3Kwz7ZIWt+4DvK3aMJy9oYXXG6/97JKsnjdCk/6n9vVyWL8NAwVt95Lwt9eigI10Hl782kDfZUUlRXw==",
"version": "1.0.30001746",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz",
"integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==",
"dev": true,
"funding": [
{
@@ -6891,6 +6913,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/jsonc-parser": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz",
"integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==",
"license": "MIT"
},
"node_modules/jszip": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
@@ -8174,6 +8202,21 @@
"node": ">=8.6"
}
},
"node_modules/mime": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-4.1.0.tgz",
"integrity": "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw==",
"funding": [
"https://github.com/sponsors/broofa"
],
"license": "MIT",
"bin": {
"mime": "bin/cli.js"
},
"engines": {
"node": ">=16"
}
},
"node_modules/mimic-response": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
@@ -8856,6 +8899,15 @@
"license": "MIT",
"peer": true
},
"node_modules/prismjs": {
"version": "1.30.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
"integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
@@ -10092,6 +10144,21 @@
"tailwindcss": ">=3.0.0 || insiders"
}
},
"node_modules/tailwindcss-safe-area": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/tailwindcss-safe-area/-/tailwindcss-safe-area-0.8.0.tgz",
"integrity": "sha512-OIKZfSvinI9kZ3hduoSxqP8EfW2rXoKvHnNyTDY2zwem06IIRtLcKdMe0nF98o+Xluk5Fy7mmesr1rSXg/wkhA==",
"license": "MIT",
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/mvllow"
},
"peerDependencies": {
"tailwindcss": "^2.0.0 || >=3.0.0"
}
},
"node_modules/tailwindcss/node_modules/postcss-selector-parser": {
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
+6
View File
@@ -17,6 +17,7 @@
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@icons-pack/react-simple-icons": "^13.8.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.5",
@@ -63,11 +64,14 @@
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
"isomorphic-git": "^1.32.1",
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
@@ -82,6 +86,7 @@
"streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
@@ -100,6 +105,7 @@
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
+261 -234
View File
@@ -1,35 +1,45 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
</head>
<body>
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
<p style="text-align: center;">Version 3, 19 November 2007</p>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
<p>Copyright © 2007 Free Software Foundation,
Inc. &lt;<a href="https://fsf.org/">https://fsf.org/</a>&gt;
<br>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
of this license document, but changing it is not allowed.</p>
Preamble
<h4 id="preamble">Preamble</h4>
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
<p>The GNU Affero General Public License is a free, copyleft license
for software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.</p>
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
<p>The licenses for most software and other practical works are
designed to take away your freedom to share and change the works. By
contrast, our General Public Licenses are intended to guarantee your
freedom to share and change all versions of a program--to make sure it
remains free software for all its users.</p>
When we speak of free software, we are referring to freedom, not
<p>When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
free programs, and that you know you can do these things.</p>
Developers that use our General Public Licenses protect your rights
<p>Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
and/or modify the software.</p>
A secondary benefit of defending all users' freedom is that
<p>A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
@@ -37,78 +47,79 @@ encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
source code to the public.</p>
The GNU Affero General Public License is designed specifically to
<p>The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
code of the modified version.</p>
An older license, called the Affero General Public License and
<p>An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
this license.</p>
The precise terms and conditions for copying, distribution and
modification follow.
<p>The precise terms and conditions for copying, distribution and
modification follow.</p>
TERMS AND CONDITIONS
<h4 id="terms">TERMS AND CONDITIONS</h4>
0. Definitions.
<h4 id="section0">0. Definitions.</h4>
"This License" refers to version 3 of the GNU Affero General Public License.
<p>"This License" refers to version 3 of the GNU Affero General Public
License.</p>
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
<p>"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.</p>
"The Program" refers to any copyrightable work licensed under this
<p>"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
"recipients" may be individuals or organizations.</p>
To "modify" a work means to copy from or adapt all or part of the work
<p>To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
earlier work or a work "based on" the earlier work.</p>
A "covered work" means either the unmodified Program or a work based
on the Program.
<p>A "covered work" means either the unmodified Program or a work based
on the Program.</p>
To "propagate" a work means to do anything with it that, without
<p>To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
public, and in some countries other activities as well.</p>
To "convey" a work means any kind of propagation that enables other
<p>To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
a computer network, with no transfer of a copy, is not conveying.</p>
An interactive user interface displays "Appropriate Legal Notices"
<p>An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
menu, a prominent item in the list meets this criterion.</p>
1. Source Code.
<h4 id="section1">1. Source Code.</h4>
The "source code" for a work means the preferred form of the work
<p>The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
form of a work.</p>
A "Standard Interface" means an interface that either is an official
<p>A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
is widely used among developers working in that language.</p>
The "System Libraries" of an executable work include anything, other
<p>The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
@@ -117,9 +128,9 @@ implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
produce the work, or an object code interpreter used to run it.</p>
The "Corresponding Source" for a work in object code form means all
<p>The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
@@ -130,26 +141,26 @@ includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
subprograms and other parts of the work.</p>
The Corresponding Source need not include anything that users
<p>The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
Source.</p>
The Corresponding Source for a work in source code form is that
same work.
<p>The Corresponding Source for a work in source code form is that
same work.</p>
2. Basic Permissions.
<h4 id="section2">2. Basic Permissions.</h4>
All rights granted under this License are granted for the term of
<p>All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
rights of fair use or other equivalent, as provided by copyright law.</p>
You may make, run and propagate covered works that you do not
<p>You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
@@ -158,69 +169,73 @@ the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
your copyrighted material outside their relationship with you.</p>
Conveying under any other circumstances is permitted solely under
<p>Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
makes it unnecessary.</p>
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
No covered work shall be deemed part of an effective technological
<p>No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
measures.</p>
When you convey a covered work, you waive any legal power to forbid
<p>When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
technological measures.</p>
4. Conveying Verbatim Copies.
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
You may convey verbatim copies of the Program's source code as you
<p>You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
recipients a copy of this License along with the Program.</p>
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
<p>You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.</p>
5. Conveying Modified Source Versions.
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
You may convey a work based on the Program, or the modifications to
<p>You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
terms of section 4, provided that you also meet all of these conditions:</p>
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
<ul>
b) The work must carry prominent notices stating that it is
<li>a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
"keep intact all notices".</li>
c) You must license the entire work, as a whole, under this
<li>c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
invalidate such permission if you have separately received it.</li>
d) If the work has interactive user interfaces, each must display
<li>d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
work need not make them do so.</li>
A compilation of a covered work with other separate and independent
</ul>
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
@@ -228,21 +243,23 @@ in or on a volume of a storage or distribution medium, is called an
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
parts of the aggregate.</p>
6. Conveying Non-Source Forms.
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
You may convey a covered work in object code form under the terms
<p>You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
in one of these ways:</p>
a) Convey the object code in, or embodied in, a physical product
<ul>
<li>a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
customarily used for software interchange.</li>
b) Convey the object code in, or embodied in, a physical product
<li>b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
@@ -252,15 +269,15 @@ in one of these ways:
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
Corresponding Source from a network server at no charge.</li>
c) Convey individual copies of the object code with a copy of the
<li>c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
with subsection 6b.</li>
d) Convey the object code by offering access from a designated
<li>d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
@@ -271,18 +288,20 @@ in one of these ways:
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
available for as long as needed to satisfy these requirements.</li>
e) Convey the object code using peer-to-peer transmission, provided
<li>e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
charge under subsection 6d.</li>
A separable portion of the object code, whose source code is excluded
</ul>
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
included in conveying the object code work.</p>
A "User Product" is either (1) a "consumer product", which means any
<p>A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
@@ -293,17 +312,17 @@ of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
the only significant mode of use of the product.</p>
"Installation Information" for a User Product means any methods,
<p>"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
modification has been made.</p>
If you convey an object code work under this section in, or with, or
<p>If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
@@ -312,133 +331,137 @@ Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
been installed in ROM).</p>
The requirement to provide Installation Information does not include a
<p>The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
protocols for communication across the network.</p>
Corresponding Source conveyed, and Installation Information provided,
<p>Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
unpacking, reading or copying.</p>
7. Additional Terms.
<h4 id="section7">7. Additional Terms.</h4>
"Additional permissions" are terms that supplement the terms of this
<p>"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
this License without regard to the additional permissions.</p>
When you convey a copy of a covered work, you may at your option
<p>When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
for which you have or can give appropriate copyright permission.</p>
Notwithstanding any other provision of this License, for material you
<p>Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
that material) supplement the terms of this License with terms:</p>
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
<ul>
b) Requiring preservation of specified reasonable legal notices or
<li>a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
Notices displayed by works containing it; or</li>
c) Prohibiting misrepresentation of the origin of that material, or
<li>c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
reasonable ways as different from the original version; or</li>
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
<li>d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li>
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
<li>e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li>
f) Requiring indemnification of licensors and authors of that
<li>f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
those licensors and authors.</li>
All other non-permissive additional terms are considered "further
</ul>
<p>All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
governed by this License along with a term that is a further restriction,
you may remove that term. If a license document contains a further
restriction but permits relicensing or conveying under this License, you
may add to a covered work material governed by the terms of that license
document, provided that the further restriction does not survive such
relicensing or conveying.</p>
If you add terms to a covered work in accord with this section, you
<p>If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
where to find the applicable terms.</p>
Additional terms, permissive or non-permissive, may be stated in the
<p>Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
the above requirements apply either way.</p>
8. Termination.
<h4 id="section8">8. Termination.</h4>
You may not propagate or modify a covered work except as expressly
<p>You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
paragraph of section 11).</p>
However, if you cease all violation of this License, then your
<p>However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
prior to 60 days after the cessation.</p>
Moreover, your license from a particular copyright holder is
<p>Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
your receipt of the notice.</p>
Termination of your rights under this section does not terminate the
<p>Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
material under section 10.</p>
9. Acceptance Not Required for Having Copies.
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
You are not required to accept this License in order to receive or
<p>You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
covered work, you indicate your acceptance of this License to do so.</p>
10. Automatic Licensing of Downstream Recipients.
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
Each time you convey a covered work, the recipient automatically
<p>Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
for enforcing compliance by third parties with this License.</p>
An "entity transaction" is a transaction transferring control of an
<p>An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
@@ -446,23 +469,23 @@ transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
the predecessor has it or can get it with reasonable efforts.</p>
You may not impose any further restrictions on the exercise of the
<p>You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
sale, or importing the Program or any portion of it.</p>
11. Patents.
<h4 id="section11">11. Patents.</h4>
A "contributor" is a copyright holder who authorizes use under this
<p>A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
work thus licensed is called the contributor's "contributor version".</p>
A contributor's "essential patent claims" are all patent claims
<p>A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
@@ -470,21 +493,21 @@ but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
this License.</p>
Each contributor grants you a non-exclusive, worldwide, royalty-free
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
propagate the contents of its contributor version.</p>
In the following three paragraphs, a "patent license" is any express
<p>In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
patent against the party.</p>
If you convey a covered work, knowingly relying on a patent license,
<p>If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
@@ -496,17 +519,17 @@ license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
country that you have reason to believe are valid.</p>
If, pursuant to or in connection with a single transaction or
<p>If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
work and works based on it.</p>
A patent license is "discriminatory" if it does not include within
<p>A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
@@ -519,15 +542,15 @@ patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
or that patent license was granted, prior to 28 March 2007.</p>
Nothing in this License shall be construed as excluding or limiting
<p>Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
otherwise be available to you under applicable patent law.</p>
12. No Surrender of Others' Freedom.
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
If conditions are imposed on you (whether by court order, agreement or
<p>If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
@@ -535,11 +558,11 @@ License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
License would be to refrain entirely from conveying the Program.</p>
13. Remote Network Interaction; Use with the GNU General Public License.
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
Notwithstanding any other provision of this License, if you modify the
<p>Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
@@ -548,56 +571,56 @@ from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
following paragraph.</p>
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
<p>Notwithstanding any other provision of this License, you have permission
to link or combine any covered work with a work licensed under version 3
of the GNU General Public License into a single combined work, and to
convey the resulting work. The terms of this License will continue to
apply to the part which is the covered work, but the work with which it is
combined will remain governed by version 3 of the GNU General Public
License.</p>
14. Revised Versions of this License.
<h4 id="section14">14. Revised Versions of this License.</h4>
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
<p>The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may differ
in detail to address new problems or concerns.</p>
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
<p>Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero
General Public License "or any later version" applies to it, you have
the option of following the terms and conditions either of that
numbered version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number
of the GNU Affero General Public License, you may choose any version
ever published by the Free Software Foundation.</p>
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
<p>If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that
proxy's public statement of acceptance of a version permanently
authorizes you to choose that version for the Program.</p>
Later license versions may give you additional or different
<p>Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
later version.</p>
15. Disclaimer of Warranty.
<h4 id="section15">15. Disclaimer of Warranty.</h4>
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
16. Limitation of Liability.
<h4 id="section16">16. Limitation of Liability.</h4>
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -605,37 +628,37 @@ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
SUCH DAMAGES.</p>
17. Interpretation of Sections 15 and 16.
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
If the disclaimer of warranty and limitation of liability provided
<p>If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
copy of the Program in return for a fee.</p>
END OF TERMS AND CONDITIONS
<p>END OF TERMS AND CONDITIONS</p>
How to Apply These Terms to Your New Programs
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
If you develop a new program, and you want it to be of the greatest
<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
free software which everyone can redistribute and change under these terms.</p>
To do so, attach the following notices to the program. It is safest
<p>To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
the "copyright" line and a pointer to where the full notice is found.</p>
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
<pre> &lt;one line to give the program's name and a brief idea of what it does.&gt;
Copyright (C) &lt;year&gt; &lt;name of author&gt;
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -643,19 +666,23 @@ the "copyright" line and a pointer to where the full notice is found.
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.
</pre>
Also add information on how to contact you by electronic and paper mail.
<p>Also add information on how to contact you by electronic and paper mail.</p>
If your software can interact with users remotely through a computer
<p>If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
specific requirements.</p>
You should also get your employer (if you work as a programmer) or school,
<p>You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
&lt;<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>&gt;.</p>
</body></html>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

+57 -8
View File
@@ -1,21 +1,70 @@
{
"name": "Shakespeare - AI-Powered Nostr Development",
"$schema": "https://json.schemastore.org/web-manifest-combined.json",
"name": "Shakespeare - Open Source AI Builder",
"short_name": "Shakespeare",
"description": "Build custom Nostr websites with AI assistance",
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"categories": ["productivity", "devtools"],
"id": "/",
"scope": "/",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"orientation": "any",
"background_color": "#2b0037",
"theme_color": "#2b0037",
"icons": [
{
"src": "/favicon.png",
"src": "/shakespeare-192x192.png",
"sizes": "192x192",
"type": "image/png"
"type": "image/png",
"purpose": "any"
},
{
"src": "/favicon.png",
"src": "/shakespeare-512x512.png",
"sizes": "512x512",
"type": "image/png"
"type": "image/png",
"purpose": "any"
},
{
"src": "/shakespeare-maskable-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/shakespeare-maskable-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"screenshots": [
{
"label": "Home",
"src": "/screenshot-mobile-home.png",
"sizes": "1179x2556",
"type": "image/png",
"form_factor": "narrow"
},
{
"label": "Project",
"src": "/screenshot-mobile-project.png",
"sizes": "1179x2556",
"type": "image/png",
"form_factor": "narrow"
},
{
"label": "Preview",
"src": "/screenshot-mobile-preview.png",
"sizes": "1179x2556",
"type": "image/png",
"form_factor": "narrow"
},
{
"label": "Desktop",
"src": "/screenshot-desktop.png",
"sizes": "1920x1080",
"type": "image/png",
"form_factor": "wide"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Allow: /
Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 321 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
<g>
<g>
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
<g>
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
</g>
</g>
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.8 KiB

+16
View File
@@ -0,0 +1,16 @@
// Shakespeare Service Worker
// Simple passthrough fetch handler
self.addEventListener('install', (event) => {
console.log('[ServiceWorker] Install');
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
console.log('[ServiceWorker] Activate');
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', (event) => {
// Passthrough: just fetch the request normally
});
+3
View File
@@ -0,0 +1,3 @@
# Shakespeare Services
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
+26
View File
@@ -0,0 +1,26 @@
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/") {
return Response.redirect("https://shakespeare.diy", 302);
}
url.hostname = "esm.sh";
// Cache response via Cloudflare
const response = await fetch(url, {
cf: { cacheEverything: true }
});
const headers = new Headers(response.headers);
headers.set("Cache-Control", "public, max-age=86400, immutable");
headers.set("Access-Control-Allow-Origin", "*");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
};
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
+5 -2
View File
@@ -1,8 +1,11 @@
import { render } from '@testing-library/react';
import { test } from 'vitest';
import { test, expect } from 'vitest';
import App from './App';
test('App', () => {
render(<App />);
const { container } = render(<App />);
// Basic smoke test to ensure App renders without crashing
expect(container).toBeInTheDocument();
})
+26 -15
View File
@@ -14,11 +14,13 @@ import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { ConsoleProvider } from '@/contexts/ConsoleContext';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { DynamicFavicon } from '@/components/DynamicFavicon';
import AppRouter from './AppRouter';
@@ -39,13 +41,19 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf",
theme: "system",
relayUrl: "wss://relay.ditto.pub",
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
esmUrl: "https://esm.shakespeare.diy",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
@@ -74,24 +82,27 @@ export function App() {
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FSProvider fs={fs}>
<FSCleanupHandler />
<ConsoleProvider>
<ConsoleErrorProvider>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<GitSettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleProvider>
</ConsoleErrorProvider>
</FSProvider>
</AppProvider>
</QueryClientProvider>
+13 -4
View File
@@ -1,6 +1,7 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
@@ -9,10 +10,14 @@ import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DataSettings from "./pages/DataSettings";
import DeploySettings from "./pages/DeploySettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
import EmailSettings from "./pages/EmailSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -23,18 +28,22 @@ export function AppRouter() {
<BrowserRouter>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="data" element={<DataSettings />} />
<Route path="email" element={<EmailSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
+15 -5
View File
@@ -1,11 +1,12 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
import { isEmptyMessage } from '@/lib/isEmptyMessage';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
@@ -69,8 +70,8 @@ export const AIMessageItem = memo(({
case 'text_editor_view': {
const title = args.path
? (args.start_line || args.end_line
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
: 'Viewed File';
return { icon: Eye, title };
}
@@ -150,6 +151,11 @@ export const AIMessageItem = memo(({
icon: CheckCircle,
title: 'TypeScript'
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console'
};
default:
return {
icon: Wrench,
@@ -294,8 +300,12 @@ export const AIMessageItem = memo(({
);
}
// If there's no reasoning content and the main content is empty, render nothing
if (!hasReasoningContent(message) && !getContent().trim()) {
if (message.role !== 'assistant') {
return null; // Only render assistant and user messages
}
// If the message is empty (no content or reasoning), render nothing
if (isEmptyMessage({ ...message, tool_calls: [] })) {
return null;
}
@@ -182,36 +182,4 @@ describe('AISettingsProvider', () => {
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
});
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
// Create a custom TestApp that mocks the query client
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
const queryClient = useQueryClient();
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
return <>{children}</>;
};
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<MockedTestApp>{children}</MockedTestApp>
</TestApp>
),
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
act(() => {
result.current.updateSettings({
recentlyUsedModels: ['test-model']
});
});
expect(mockInvalidateQueries).not.toHaveBeenCalled();
});
});
+4
View File
@@ -57,6 +57,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
// If providers are being updated, invalidate the provider-models query
if ('providers' in newSettings) {
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
}
};
@@ -80,6 +81,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
}
});
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const removeProvider = (id: string) => {
@@ -88,6 +90,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
providers: prev.providers.filter(provider => provider.id !== id),
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const setProviders = (providers: AIProvider[]) => {
@@ -96,6 +99,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
providers,
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const addRecentlyUsedModel = (modelId: string) => {
+303
View File
@@ -0,0 +1,303 @@
import { useState, useEffect } from 'react';
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { useAICredits } from '@/hooks/useAICredits';
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
interface Act1DialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome');
const { data: creditsData } = useAICredits(getShakespeareProvider());
const handleGetStarted = async () => {
try {
setStep('migration');
} catch (error) {
console.error('Failed to configure Shakespeare provider:', error);
}
};
const handleContinue = () => {
setStep('credits');
};
const handleCreditsNext = () => {
setStep('conclusion');
};
const handleFinish = () => {
// Mark that the user is a previous Act 1 user
localStorage.setItem('act1', 'true');
// Remove the selectedNSPAddr from localStorage
localStorage.removeItem('selectedNSPAddr');
onOpenChange(false);
};
const handleVisitAct1 = () => {
window.open('https://act1.shakespeare.diy', '_blank');
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'migration' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'credits' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('migration')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('credits')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
<div className="space-y-6 py-4">
{step === 'welcome' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">🎭✨</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Act 2!
</h2>
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
We're excited to see you again! Shakespeare has been completely rebuilt
with new features, improved performance, and a better development experience.
</p>
</div>
<Card className="max-w-lg mx-auto text-left">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<span className="text-2xl">🔄</span>
What's Changed
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Use any AI Provider</p>
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Git Integration</p>
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Your Files</p>
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
</div>
</div>
</CardContent>
</Card>
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
<div className="flex items-start gap-3">
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
<div className="text-left">
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
<p className="text-sm text-amber-700 dark:text-amber-300">
While we're working hard to make Act 2 stable, you may encounter bugs.
Your Act 1 projects remain safe and accessible.
</p>
</div>
</div>
</div>
<Button
onClick={handleGetStarted}
size="lg"
className="gap-2"
>
Next
</Button>
</div>
)}
{step === 'migration' && (
<div className="space-y-6">
<div className="text-center space-y-3">
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
<p className="text-muted-foreground max-w-lg mx-auto">
All your Act 1 projects and credits are safe and still accessible.
Here's how to work with them in Act 2.
</p>
</div>
<div className="text-center">
<Button
variant="outline"
onClick={handleVisitAct1}
className="gap-2"
>
<ExternalLink className="h-4 w-4" />
Visit Act 1
</Button>
</div>
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Download className="h-5 w-5 text-green-500" />
Export from Act 1
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 1, you can export your projects as ZIP files using the project menu.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Upload className="h-5 w-5 text-purple-500" />
Import to Act 2
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
</p>
</CardContent>
</Card>
</div>
<div className="flex justify-end pt-4">
<Button
onClick={handleContinue}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'credits' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">💳</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Your Credits</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your Act 1 credits are still available through the Shakespeare AI provider.
</p>
</div>
<Card className="max-w-md mx-auto">
<CardContent className="pt-6">
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
${(creditsData?.amount ?? 0).toFixed(2)}
</div>
<p className="text-sm text-muted-foreground">
Available credits
</p>
</div>
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<p className="text-sm text-green-800 dark:text-green-200">
✅ You're all set! We've configured the premium Shakespeare model for you.
</p>
</div>
</div>
</CardContent>
</Card>
<div className="flex justify-end pt-4">
<Button
onClick={handleCreditsNext}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
</p>
</div>
<div className="space-y-3">
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building in Act 2
</Button>
<div className="text-xs text-muted-foreground">
Remember: You can always access Act 1 at{' '}
<button
onClick={handleVisitAct1}
className="text-primary hover:underline"
>
act1.shakespeare.diy
</button>
</div>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+19 -1
View File
@@ -12,9 +12,11 @@ import {
MessageSquarePlus,
History,
Folder,
Rocket,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { DeployDialog } from '@/components/DeployDialog';
interface ActionsMenuProps {
projectId: string;
@@ -29,7 +31,7 @@ interface ActionsMenuProps {
export function ActionsMenu({
projectId,
projectName: _projectName,
projectName,
onNewChat,
onProjectDetails,
isLoading = false,
@@ -39,6 +41,7 @@ export function ActionsMenu({
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
@@ -86,6 +89,15 @@ export function ActionsMenu({
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
@@ -112,6 +124,12 @@ export function ActionsMenu({
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
</>
);
+133
View File
@@ -0,0 +1,133 @@
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 type { AIProvider } from '@/contexts/AISettingsContext';
describe('AddProviderDialog', () => {
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'sk-test-key-123',
};
it('renders new provider dialog', () => {
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</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();
});
it('shows add provider button for new provider', () => {
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
// No cancel button, only add provider button
expect(screen.queryByRole('button', { name: /cancel/i })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /add provider/i })).toBeInTheDocument();
});
it('calls onOpenChange when add provider is clicked', async () => {
const user = userEvent.setup();
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
const addButton = screen.getByRole('button', { name: /add provider/i });
await user.click(addButton);
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it('does not display provider details for new provider', () => {
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
// Provider details (API key, base URL, etc.) are not displayed for new providers
expect(screen.queryByText('••••••••')).not.toBeInTheDocument();
expect(screen.queryByText('sk-test-key-123')).not.toBeInTheDocument();
expect(screen.queryByText('https://api.test.com/v1')).not.toBeInTheDocument();
});
it('displays provider name from presets when available', () => {
const onOpenChange = vi.fn();
// Use a provider that exists in presets
const openrouterProvider: AIProvider = {
id: 'openrouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'sk-test-123',
};
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={openrouterProvider}
/>
</TestApp>
);
// Should show the preset name "OpenRouter" instead of the id
expect(screen.getByText(/Add OpenRouter to your configuration/i)).toBeInTheDocument();
});
it('uses provider id as fallback name when not in presets', () => {
const onOpenChange = vi.fn();
const customProvider: AIProvider = {
id: 'my-custom-provider',
baseURL: 'https://api.custom.com/v1',
};
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={customProvider}
/>
</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();
});
});
+179
View File
@@ -0,0 +1,179 @@
import { useEffect, useRef } from 'react';
import { Check, Sparkles, ArrowRight, AlertCircle } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { useAISettings } from '@/hooks/useAISettings';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import type { AIProvider } from '@/contexts/AISettingsContext';
interface AddProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: AIProvider;
}
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
const scrollableContentRef = useRef<HTMLDivElement>(null);
const { settings, setProvider } = useAISettings();
// Check if provider already exists and if it's identical
const existingProvider = settings.providers.find(p => p.id === provider.id);
const isIdentical = existingProvider &&
existingProvider.baseURL === provider.baseURL &&
existingProvider.apiKey === provider.apiKey &&
existingProvider.nostr === provider.nostr &&
existingProvider.proxy === provider.proxy;
// Get provider name from presets or fallback to id
const getProviderName = () => {
const preset = AI_PROVIDER_PRESETS.find(
p => p.id === provider.id && p.baseURL === provider.baseURL
);
return preset?.name || provider.id;
};
const providerName = getProviderName();
const handleAddProvider = () => {
setProvider(provider);
onOpenChange(false);
};
// Scroll to top when dialog opens
useEffect(() => {
if (open && scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2">
<span className="text-xl">Add Provider</span>
</DialogTitle>
</DialogHeader>
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
<div className="space-y-6 py-4">
{isIdentical ? (
// Provider already exists with identical configuration
<div className="text-center space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
<Check className="h-8 w-8 text-primary" />
</div>
<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.
</p>
</div>
<Button onClick={() => onOpenChange(false)} className="gap-2">
Close
</Button>
</div>
) : existingProvider ? (
// Provider exists but with different configuration
<div className="space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-yellow-500/10 flex items-center justify-center">
<AlertCircle className="h-8 w-8 text-yellow-500" />
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">Provider Already Exists</h2>
<p className="text-muted-foreground max-w-md mx-auto">
A provider with this ID already exists but with different settings. Would you like to overwrite it?
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl mx-auto">
<div className="space-y-2 p-4 rounded-lg border">
<h3 className="font-semibold text-sm">Current Settings</h3>
<div className="text-xs text-muted-foreground space-y-1">
<div>
<span className="font-medium">Base URL:</span>
<div className="font-mono break-all">{existingProvider.baseURL}</div>
</div>
{existingProvider.apiKey && (
<div>
<span className="font-medium">API Key:</span>
<div className="font-mono">••••••••</div>
</div>
)}
{existingProvider.nostr && (
<div>
<span className="font-medium">Nostr Auth:</span> Enabled
</div>
)}
{existingProvider.proxy && (
<div>
<span className="font-medium">Proxy:</span> Enabled
</div>
)}
</div>
</div>
<div className="space-y-2 p-4 rounded-lg border border-primary">
<h3 className="font-semibold text-sm">New Settings</h3>
<div className="text-xs text-muted-foreground space-y-1">
<div>
<span className="font-medium">Base URL:</span>
<div className="font-mono break-all">{provider.baseURL}</div>
</div>
{provider.apiKey && (
<div>
<span className="font-medium">API Key:</span>
<div className="font-mono">••••••••</div>
</div>
)}
{provider.nostr && (
<div>
<span className="font-medium">Nostr Auth:</span> Enabled
</div>
)}
{provider.proxy && (
<div>
<span className="font-medium">Proxy:</span> Enabled
</div>
)}
</div>
</div>
</div>
<div className="flex justify-center gap-3">
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleAddProvider} className="gap-2">
Overwrite Provider
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
) : (
// New provider
<div className="space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
<Sparkles className="h-8 w-8 text-primary" />
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">{providerName}</h2>
<p className="text-muted-foreground max-w-md mx-auto">
Add {providerName} to your configuration?
</p>
</div>
<div className="flex justify-center">
<Button onClick={handleAddProvider}>
Add Provider
</Button>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+15 -17
View File
@@ -18,7 +18,6 @@ interface AppLayoutProps {
export function AppLayout({
children,
selectedProject = null,
title = "Shakespeare",
showSidebar = true,
headerContent
}: AppLayoutProps) {
@@ -73,23 +72,22 @@ export function AppLayout({
return (
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
{/* Mobile Header */}
<header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{title}
</h1>
<header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe">
<div className="h-12 px-4 py-3 flex items-center justify-between border-b">
<div className="flex items-center space-x-2">
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
</div>
{headerContent}
</div>
{headerContent}
</header>
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
+16 -8
View File
@@ -15,12 +15,18 @@ interface AppProviderProps {
}
// Zod schema for AppConfig validation
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
deployServer: z.string().min(1),
language: z.string().optional(),
});
projectTemplate: z.string().url(),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseModerator: z.string(),
ngitServers: z.array(z.string()),
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
const {
@@ -31,23 +37,25 @@ export function AppProvider(props: AppProviderProps) {
} = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage<AppConfig>(
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
storageKey,
defaultConfig,
{},
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
return AppConfigSchema.partial().parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
setConfig(updater);
};
const config = { ...defaultConfig, ...rawConfig };
const appContextValue: AppContextType = {
config,
updateConfig,
+243
View File
@@ -0,0 +1,243 @@
import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { nip19 } from 'nostr-tools';
import { shuffleArray } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent } from "@/components/ui/card";
import { RelaySelector } from "@/components/RelaySelector";
import { useAppContext } from "@/hooks/useAppContext";
export function AppShowcase() {
const { user } = useCurrentUser();
const { config } = useAppContext();
const { data: submissions = [], isLoading } = useAppSubmissions();
const [showAllApps, setShowAllApps] = useState(false);
// Get moderator hex from config
const MODERATOR_HEX = useMemo(() => {
try {
const decoded = nip19.decode(config.showcaseModerator);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
}, [config.showcaseModerator]);
const isModerator = user?.pubkey === MODERATOR_HEX;
// Filter and shuffle submissions - memoized with stable dependency
const { templateApps, halloweenApps, featuredApps, approvedApps } = useMemo(() => {
// Filter visible submissions
const visibleSubmissions = submissions.filter(app => !app.isHidden);
// Separate template apps from other apps
const templates = shuffleArray(visibleSubmissions.filter(app => app.appTags.includes('Template')));
const nonTemplateSubmissions = visibleSubmissions.filter(app => !app.appTags.includes('Template'));
// Get Halloween Hackathon 2025 apps that are featured (for main showcase)
const halloween = shuffleArray(nonTemplateSubmissions.filter(app =>
app.appTags.includes('Halloween Hackathon 2025') && app.isFeatured
));
// Filter out Halloween Hackathon 2025 apps from other sections (unless featured, they go in Halloween section)
const nonHalloweenSubmissions = nonTemplateSubmissions.filter(app =>
!app.appTags.includes('Halloween Hackathon 2025')
);
// Shuffle featured and approved apps for random display order
const featured = shuffleArray(nonHalloweenSubmissions.filter(app => app.isFeatured));
const approved = shuffleArray(nonHalloweenSubmissions.filter(app => app.isApproved && !app.isFeatured));
return {
templateApps: templates,
halloweenApps: halloween,
featuredApps: featured,
approvedApps: approved,
};
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
// Don't show showcase if disabled in settings
if (!config.showcaseEnabled) {
return null;
}
// Don't show showcase if no apps exist
if (isLoading) {
return (
<div className="mt-16 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 6 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<Skeleton className="aspect-video rounded-t-lg" />
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-center gap-3 mb-3">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-24" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-6 flex-1" />
<Skeleton className="h-8 w-8" />
<Skeleton className="h-8 w-8" />
</div>
</CardContent>
</Card>
))}
</div>
</div>
);
}
if (!submissions.length) {
return (
<div className="mt-16 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No apps found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div className="mt-16 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{/* Apps Grid */}
<div className="space-y-12">
{/* Featured Apps */}
{featuredApps.length > 0 && (
<div>
<div className="flex items-center gap-3 mb-6">
<div className="w-8 h-8 bg-yellow-100 rounded-lg flex items-center justify-center">
<span className="text-sm">⭐</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">Featured Apps</h3>
<p className="text-sm text-muted-foreground">Handpicked applications showcasing the best of our community</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{featuredApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* Halloween Hackathon 2025 Apps */}
{halloweenApps.length > 0 && (
<div>
<div className="flex items-center gap-3 mb-6">
<div className="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center">
<span className="text-sm">🎃</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">Halloween Hackathon 2025</h3>
<p className="text-sm text-muted-foreground">Featured spooky creations from our Halloween hackathon</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{halloweenApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* Templates Section */}
{templateApps.length > 0 && (
<div>
<div className="flex items-center gap-3 mb-6">
<div className="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
<span className="text-sm">📋</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">Templates</h3>
<p className="text-sm text-muted-foreground">Ready-to-use templates to kickstart your project</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{templateApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* More Apps (Approved) - Collapsible */}
{approvedApps.length > 0 && (
<div>
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
<span className="text-sm">📱</span>
</div>
<div className="text-left">
<h3 className="text-xl font-bold text-foreground">
More Apps ({approvedApps.length})
</h3>
<p className="text-sm text-muted-foreground">
{showAllApps ? 'Click to collapse' : 'Click to view more community apps'}
</p>
</div>
</div>
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{approvedApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
</div>
</div>
);
}
+589
View File
@@ -0,0 +1,589 @@
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
ExternalLink,
Edit,
Star,
StarOff,
Eye,
EyeOff,
MoreVertical,
CheckCircle,
XCircle,
User,
Home,
Contact
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import type { AppSubmission } from '@/hooks/useAppSubmissions';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useNostr } from '@nostrify/react';
import { useAuthor } from '@/hooks/useAuthor';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
interface AppShowcaseCardProps {
app: AppSubmission;
onEdit?: (app: AppSubmission) => void;
showModerationControls?: boolean;
hideApprovalStatus?: boolean; // Hide pending/approval badges
}
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutate: publishEvent, isPending } = useNostrPublish();
const queryClient = useQueryClient();
const [imageError, setImageError] = useState(false);
const { toast } = useToast();
// Get author pubkey from authorNpub field
const authorPubkey = React.useMemo(() => {
if (!app.authorNpub) return app.pubkey; // Fallback to event pubkey
try {
// If it's already a hex key, use it directly
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
return app.authorNpub;
}
// Otherwise try to decode as npub
const decoded = nip19.decode(app.authorNpub);
return decoded.type === 'npub' ? decoded.data : app.pubkey;
} catch {
return app.pubkey; // Fallback to event pubkey if decode fails
}
}, [app.authorNpub, app.pubkey]);
const { data: authorData } = useAuthor(authorPubkey);
const isOwner = user?.pubkey === app.pubkey;
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
const isModerator = user?.pubkey === MODERATOR_HEX;
// Check if this is a Halloween submission by looking for Halloween tags
const isHalloweenSubmission = app.appTags.includes('Halloween Hackathon 2025');
// Get contact info from Halloween submissions (these have lightning/email tags)
const getContactInfo = () => {
if (!isHalloweenSubmission) return null;
// Look for lightning and email tags in the event tags
const lightningTag = app.tags?.find((tag: string[]) => tag[0] === 'lightning')?.[1];
const emailTag = app.tags?.find((tag: string[]) => tag[0] === 'email')?.[1];
return { lightning: lightningTag, email: emailTag };
};
const handleCopyContactInfo = () => {
const contactInfo = getContactInfo();
if (!contactInfo) return;
const info: string[] = [];
if (contactInfo.lightning) info.push(`Lightning: ${contactInfo.lightning}`);
if (contactInfo.email) info.push(`Email: ${contactInfo.email}`);
const textToCopy = info.join('\n');
navigator.clipboard.writeText(textToCopy);
toast({
title: 'Contact Info Copied!',
description: `Copied ${info.length} contact method(s) to clipboard`
});
};
const handleModerationAction = async (action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage') => {
if (!isModerator || !user) return;
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) {
toast({
title: 'Error',
description: 'Cannot perform moderation action: missing app identifier',
variant: 'destructive'
});
return;
}
const appCoordinate = `${app.kind}:${app.pubkey}:${dTag}`;
try {
if (action === 'homepage' || action === 'unhomepage') {
// Get current homepage apps list
const currentHomepageLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-homepage-apps'],
limit: 1
}]);
const currentHomepageList = currentHomepageLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current homepage app coordinates
const currentHomepageApps = new Set<string>();
if (currentHomepageList) {
currentHomepageList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentHomepageApps.add(tag[1]));
}
// Update the homepage set
if (action === 'homepage') {
currentHomepageApps.add(appCoordinate);
} else {
currentHomepageApps.delete(appCoordinate);
}
// Publish updated homepage apps list
publishEvent({
kind: 30267,
content: 'Soapbox homepage apps curated by moderators',
tags: [
['d', 'soapbox-homepage-apps'],
['title', 'Soapbox Homepage Apps'],
['description', 'Apps displayed on the Soapbox homepage'],
...Array.from(currentHomepageApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
// If adding to homepage, also ensure it's approved
if (action === 'homepage') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}]);
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
}
} else if (action === 'feature' || action === 'unfeature') {
// Get current featured apps list
const currentFeaturedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-featured-apps'],
limit: 1
}]);
const currentFeaturedList = currentFeaturedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current featured app coordinates
const currentFeaturedApps = new Set<string>();
if (currentFeaturedList) {
currentFeaturedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentFeaturedApps.add(tag[1]));
}
// Update the featured set
if (action === 'feature') {
currentFeaturedApps.add(appCoordinate);
} else {
currentFeaturedApps.delete(appCoordinate);
}
// Publish updated featured apps list
publishEvent({
kind: 30267,
content: 'Soapbox featured apps curated by moderators',
tags: [
['d', 'soapbox-featured-apps'],
['title', 'Soapbox Featured Apps'],
['description', 'Apps featured in the Soapbox showcase'],
...Array.from(currentFeaturedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
// If featuring an app, also ensure it's approved
if (action === 'feature') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}]);
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
}
} else if (action === 'approve' || action === 'unapprove') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}]);
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Update the approved set
if (action === 'approve') {
currentApprovedApps.add(appCoordinate);
} else {
currentApprovedApps.delete(appCoordinate);
}
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
} else if (action === 'hide' || action === 'unhide') {
// Create NIP-56 report event
publishEvent({
kind: 1984,
content: `App ${action}den by moderator: "${app.appName}"`,
tags: [
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
['p', app.pubkey],
['L', 'soapbox.moderation'],
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation']
],
created_at: Math.floor(Date.now() / 1000)
});
}
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
// If this is a Halloween app, also invalidate Halloween queries
if (isHalloweenSubmission) {
queryClient.invalidateQueries({ queryKey: ['halloween-submissions'] });
queryClient.invalidateQueries({ queryKey: ['halloween-submissions-with-contacts'] });
}
toast({
title: 'Success!',
description: `App "${app.appName}" ${action}d successfully`
});
} catch (error) {
console.error('Moderation action failed:', error);
toast({
title: 'Error',
description: `Failed to ${action} app "${app.appName}"`,
variant: 'destructive'
});
}
};
return (
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
<div className="relative">
{/* App Screenshot */}
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
>
{!imageError ? (
<img
src={app.screenshotUrl}
alt={`${app.appName} screenshot`}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
onError={() => setImageError(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
<div className="text-center">
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
<ExternalLink className="w-8 h-8" />
</div>
<p className="text-sm">Screenshot unavailable</p>
</div>
</div>
)}
</a>
{/* Actions Menu */}
{(isOwner || showModerationControls) && (
<div className="absolute top-3 right-3">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isOwner && (
<DropdownMenuItem onClick={() => onEdit?.(app)}>
<Edit className="w-4 h-4 mr-2" />
Edit App
</DropdownMenuItem>
)}
{showModerationControls && isModerator && (
<>
{isHalloweenSubmission && getContactInfo() && (getContactInfo()?.lightning || getContactInfo()?.email) && (
<DropdownMenuItem
onClick={handleCopyContactInfo}
>
<Contact className="w-4 h-4 mr-2" />
View Contact Info
</DropdownMenuItem>
)}
{!app.isApproved && (
<DropdownMenuItem
onClick={() => handleModerationAction('approve')}
disabled={isPending}
>
<CheckCircle className="w-4 h-4 mr-2" />
Approve
</DropdownMenuItem>
)}
{app.isApproved && !app.isFeatured && (
<DropdownMenuItem
onClick={() => handleModerationAction('unapprove')}
disabled={isPending}
>
<XCircle className="w-4 h-4 mr-2" />
Unapprove
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() => handleModerationAction(app.isFeatured ? 'unfeature' : 'feature')}
disabled={isPending}
>
{app.isFeatured ? (
<>
<StarOff className="w-4 h-4 mr-2" />
Un-feature
</>
) : (
<>
<Star className="w-4 h-4 mr-2" />
Feature
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHomepage ? 'unhomepage' : 'homepage')}
disabled={isPending}
>
{app.isHomepage ? (
<>
<Home className="w-4 h-4 mr-2" />
Remove from Homepage
</>
) : (
<>
<Home className="w-4 h-4 mr-2" />
Add to Homepage
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHidden ? 'unhide' : 'hide')}
disabled={isPending}
>
{app.isHidden ? (
<>
<Eye className="w-4 h-4 mr-2" />
Unhide
</>
) : (
<>
<EyeOff className="w-4 h-4 mr-2" />
Hide
</>
)}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
{/* App Icon */}
<div className="w-12 h-12 rounded-lg overflow-hidden bg-muted flex-shrink-0">
<img
src={app.appIconUrl}
alt={`${app.appName} icon`}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
}}
/>
</div>
<div>
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
</h3>
</div>
</div>
</div>
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
{/* Author Information */}
<div className="flex items-center gap-2 mb-4">
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
{authorData?.metadata?.picture ? (
<img
src={authorData.metadata.picture}
alt={`${authorData.metadata.name || 'Author'} avatar`}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
target.parentElement!.innerHTML = '<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<User className="w-3 h-3 text-muted-foreground" />
</div>
)}
</div>
<span className="text-sm text-muted-foreground">
by{' '}
<a
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:text-primary/80 transition-colors hover:underline"
>
{authorData?.metadata?.name || authorData?.metadata?.display_name || 'Anonymous'}
</a>
</span>
</div>
{/* Spacer to push action links to bottom */}
<div className="flex-1"></div>
{/* Action Links */}
<div className="flex items-center gap-2 mt-auto">
<Link
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
className="flex-1"
>
<img
src="/badge.svg"
alt="Edit with Shakespeare"
className="h-6 hover:opacity-80 transition-opacity"
/>
</Link>
<Button variant="outline" size="sm" asChild>
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
title="Visit app"
>
<ExternalLink className="w-4 h-4" />
</a>
</Button>
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,152 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { ReactNode } from 'react';
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
import { useConsoleError } from '@/hooks/useConsoleError';
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
// Wrapper component for testing
function TestWrapper({ children }: { children: ReactNode }) {
return (
<ConsoleErrorProvider>
{children}
</ConsoleErrorProvider>
);
}
describe('ConsoleErrorProvider', () => {
beforeEach(() => {
clearConsoleMessages();
});
it('should provide initial state with no errors', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should update hasErrors when console error is added', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
expect(result.current.hasErrors).toBe(false);
// Add an error message
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.hasErrors).toBe(true);
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
});
it('should not update hasErrors for non-error messages', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add non-error messages
act(() => {
addConsoleMessage('log', 'Test log message');
addConsoleMessage('warn', 'Test warning message');
addConsoleMessage('info', 'Test info message');
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should update consoleError with latest error message', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add first error
act(() => {
addConsoleMessage('error', 'First error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
// Add second error - should update to show latest error
act(() => {
addConsoleMessage('error', 'Second error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
expect(result.current.consoleError?.logs).toHaveLength(2);
});
it('should clear errors when clearErrors is called', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add error to set state
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.hasErrors).toBe(true);
expect(result.current.consoleError).not.toBeNull();
// Clear errors
act(() => {
result.current.clearErrors();
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should dismiss console error when dismissConsoleError is called', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add error to create console error
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.consoleError).not.toBeNull();
// Dismiss console error (this only clears the Quilly error, not the global state)
act(() => {
result.current.dismissConsoleError();
});
expect(result.current.consoleError).toBeNull();
// hasErrors should still be true since we only dismissed the Quilly display
expect(result.current.hasErrors).toBe(true);
});
it('should include all error messages in console error logs', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add multiple errors and non-errors
act(() => {
addConsoleMessage('log', 'Log message');
addConsoleMessage('error', 'First error');
addConsoleMessage('warn', 'Warning message');
addConsoleMessage('error', 'Second error');
addConsoleMessage('info', 'Info message');
addConsoleMessage('error', 'Third error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
expect(result.current.consoleError?.logs).toHaveLength(3);
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
'First error',
'Second error',
'Third error'
]);
});
});
+63
View File
@@ -0,0 +1,63 @@
import { useState, useEffect, useCallback, ReactNode } from 'react';
import {
addConsoleMessageListener,
removeConsoleMessageListener,
getHasConsoleErrors,
getConsoleMessages,
clearConsoleMessages,
ProjectPreviewConsoleError
} from '@/lib/consoleMessages';
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
interface ConsoleErrorProviderProps {
children: ReactNode;
}
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
const updateState = useCallback(() => {
const hasConsoleErrors = getHasConsoleErrors();
setHasErrors(hasConsoleErrors);
if (hasConsoleErrors) {
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
const latestError = errorMessages[errorMessages.length - 1];
setConsoleError(new ProjectPreviewConsoleError(
`Console error detected: ${latestError.message}`,
errorMessages
));
} else {
setConsoleError(null);
}
}, []);
useEffect(() => {
addConsoleMessageListener(updateState);
updateState(); // Initial sync
return () => removeConsoleMessageListener(updateState);
}, [updateState]);
const clearErrors = useCallback(() => {
clearConsoleMessages();
}, []);
const dismissConsoleError = useCallback(() => {
setConsoleError(null);
}, []);
const value = {
hasErrors,
consoleError,
clearErrors,
dismissConsoleError,
};
return (
<ConsoleErrorContext.Provider value={value}>
{children}
</ConsoleErrorContext.Provider>
);
}
+116 -125
View File
@@ -9,10 +9,11 @@ import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { AIProvider } from '@/contexts/AISettingsContext';
interface CreditsDialogProps {
@@ -183,6 +184,7 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) {
const { user } = useCurrentUser();
const { config } = useAppContext();
const { toast } = useToast();
const queryClient = useQueryClient();
@@ -195,7 +197,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
const { data: payments, isLoading: isLoadingPayments } = useQuery({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<Payment[]> => {
const ai = createAIClient(provider, user);
const ai = createAIClient(provider, user, config.corsProxy);
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
return data.data;
},
@@ -207,7 +209,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
const ai = createAIClient(provider, user);
const ai = createAIClient(provider, user, config.corsProxy);
return await ai.post('/credits/add', {
body: request,
}) as Payment;
@@ -248,7 +250,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
// Mutation for checking payment status
const checkPaymentMutation = useMutation({
mutationFn: async (paymentId: string): Promise<Payment> => {
const ai = createAIClient(provider, user);
const ai = createAIClient(provider, user, config.corsProxy);
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
},
onMutate: async (paymentId: string) => {
@@ -399,7 +401,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2 text-lg">
{lightningInvoice ? (
@@ -434,68 +436,61 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
<div className="flex-1 flex flex-col min-h-0">
{/* Add Credits Form - Fixed size section */}
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
</Button>
))}
</div>
</div>
</div>
</div>
<div className="space-y-3">
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stripe">
<div className="flex items-center gap-2">
<div className="space-y-3">
<Label className="text-sm font-medium">Payment Method</Label>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Credit Card
</div>
</SelectItem>
<SelectItem value="lightning">
<div className="flex items-center gap-2">
Credit Card
</TabsTrigger>
<TabsTrigger value="lightning" className="flex items-center gap-2">
<Zap className="h-4 w-4" />
Lightning
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
Lightning
</TabsTrigger>
</TabsList>
</Tabs>
</div>
<Button
onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
<Button
onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
</div>
<div className="flex-shrink-0 px-1 -mx-1 py-4">
@@ -509,17 +504,13 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? (
<div className="space-y-3">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
))}
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
) : !payments || payments.length === 0 ? (
<div className="flex-1 flex items-center justify-center">
@@ -532,65 +523,65 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
) : (
<div className="space-y-2 pb-2">
{payments.map((payment) => (
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)}
</p>
)}
</div>
</div>
</p>
)}
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button>
)}
</div>
)}
</div>
)}
</div>
</div>
</div>
))}
</div>
)}
+428 -138
View File
@@ -1,182 +1,472 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import { SiNetlify, SiVercel } from '@icons-pack/react-simple-icons';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMutation } from '@tanstack/react-query';
import { deployProject } from '@/lib/deploy';
import { useFS } from '@/hooks/useFS';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
CloudUpload,
Loader2,
} from 'lucide-react';
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
interface DeployDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onFirstInteraction?: () => void;
}
export function DeployDialog({
projectId,
projectName,
open,
onOpenChange,
onFirstInteraction
}: DeployDialogProps) {
const { config } = useAppContext();
interface ShakespeareFormData {
subdomain: string;
}
interface NsiteFormData {
nsec: string;
}
interface NetlifyFormData {
siteId: string;
siteName: string;
}
interface VercelFormData {
projectName: string;
teamId: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
const { user } = useCurrentUser();
const { fs } = useFS();
const { toast } = useToast();
const { config } = useAppContext();
const { nostr } = useNostr();
// State for the deploy URL input
const [deployUrl, setDeployUrl] = useState('');
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
// Initialize deploy URL when dialog opens
useEffect(() => {
if (open) {
setDeployUrl(`${projectId}.${config.deployServer}`);
}
}, [open, projectId, config.deployServer]);
const deployMutation = useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
// Parse the deploy URL to extract hostname and server
const hostname = deployUrl.trim();
const parts = hostname.split('.');
if (parts.length < 2) {
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
}
// Extract the deploy server (everything after the first dot)
const deployServer = parts.slice(1).join('.');
return await deployProject({
fs,
projectId, // Keep the original projectId for file path
deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
customHostname: hostname, // Pass the custom hostname
});
},
onSuccess: (result) => {
toast({
title: "Deployment successful!",
description: `Your project is now live at ${result.hostname}`,
});
// Open the deployed site in a new tab
window.open(result.url, '_blank');
// Close the dialog
onOpenChange(false);
},
onError: (error) => {
toast({
title: "Deployment failed",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
},
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
subdomain: projectId,
});
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
nsec: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
siteName: '',
});
const [vercelForm, setVercelForm] = useState<VercelFormData>({
projectName: projectName || projectId,
teamId: '',
});
const handleDeploy = () => {
if (onFirstInteraction) {
onFirstInteraction();
// Load project settings when dialog opens
useEffect(() => {
if (open) {
// First, try to use the currentProvider from project settings
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
setSelectedProviderId(projectSettings.currentProvider);
} else {
// Otherwise, find the first configured provider in project settings
const providerIds = Object.keys(projectSettings.providers);
if (providerIds.length > 0) {
setSelectedProviderId(providerIds[0]);
}
}
}
}, [open, projectSettings, settings.providers]);
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
const handleDeploy = async () => {
if (!selectedProvider) return;
setIsDeploying(true);
setError(null);
setDeployResult(null);
try {
const projectPath = `/projects/${projectId}`;
let adapter: DeployAdapter;
if (selectedProvider.type === 'shakespeare') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
adapter = new ShakespeareAdapter({
fs,
signer: user.signer,
host: shakespeareProvider.host,
subdomain: shakespeareForm.subdomain || undefined,
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
}
adapter = new NsiteAdapter({
fs,
nostr,
nsec: nsiteForm.nsec,
gateway: nsiteProvider.gateway,
relayUrls: nsiteProvider.relayUrls,
blossomServers: nsiteProvider.blossomServers,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider as NetlifyProvider;
if (!netlifyProvider.apiKey) {
throw new Error('Netlify API key is required');
}
// If siteId is empty, we're creating a new site, so only pass siteName
// If siteId is set, we're updating an existing site
adapter = new NetlifyAdapter({
fs,
apiKey: netlifyProvider.apiKey,
baseURL: netlifyProvider.baseURL,
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
siteId: netlifyForm.siteId || undefined,
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'vercel') {
const vercelProvider = selectedProvider as VercelProvider;
if (!vercelProvider.apiKey) {
throw new Error('Vercel API key is required');
}
adapter = new VercelAdapter({
fs,
apiKey: vercelProvider.apiKey,
baseURL: vercelProvider.baseURL,
teamId: vercelForm.teamId || undefined,
projectName: vercelForm.projectName || undefined,
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
const result = await adapter.deploy({
projectId,
projectPath,
});
// Save project-specific settings (updateSettings now automatically sets currentProvider)
if (selectedProvider.type === 'shakespeare') {
await updateProjectSettings(selectedProviderId, {
type: 'shakespeare',
data: {
subdomain: shakespeareForm.subdomain || undefined,
},
});
} else if (selectedProvider.type === 'nsite') {
await updateProjectSettings(selectedProviderId, {
type: 'nsite',
data: {
nsec: nsiteForm.nsec,
},
});
} else if (selectedProvider.type === 'netlify') {
await updateProjectSettings(selectedProviderId, {
type: 'netlify',
data: {
siteId: result.metadata?.siteId as string | undefined,
},
});
} else if (selectedProvider.type === 'vercel') {
await updateProjectSettings(selectedProviderId, {
type: 'vercel',
data: {
teamId: vercelForm.teamId || undefined,
projectId: vercelForm.projectName || undefined,
},
});
}
setDeployResult(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'Deployment failed');
} finally {
setIsDeploying(false);
}
deployMutation.mutate();
};
const handleUrlChange = (value: string) => {
// Remove protocol if user enters it
const cleanValue = value.replace(/^https?:\/\//, '');
setDeployUrl(cleanValue);
const handleClose = () => {
setSelectedProviderId('');
setDeployResult(null);
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
onOpenChange(false);
};
const isValidUrl = () => {
const trimmed = deployUrl.trim();
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
setNetlifyForm({ siteId, siteName });
}, []);
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
setVercelForm({ projectName, teamId });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
return (
<ShakespeareDeployForm
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
/>
);
}
if (selectedProvider.type === 'nsite') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
return (
<NsiteDeployForm
gateway={selectedProvider.gateway}
savedNsec={savedNsec}
onNsecChange={handleNsiteNsecChange}
/>
);
}
if (selectedProvider.type === 'netlify') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
return (
<NetlifyDeployForm
apiKey={selectedProvider.apiKey}
baseURL={selectedProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedSiteId={savedSiteId}
onSiteChange={handleNetlifySiteChange}
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
/>
);
}
if (selectedProvider.type === 'vercel') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedTeamId = savedConfig?.type === 'vercel' ? savedConfig.data.teamId : undefined;
const savedProjectName = savedConfig?.type === 'vercel' ? savedConfig.data.projectId : undefined;
return (
<VercelDeployForm
projectId={projectId}
projectName={projectName}
savedTeamId={savedTeamId}
savedProjectName={savedProjectName}
onConfigChange={handleVercelConfigChange}
/>
);
}
return null;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<CloudUpload className="h-5 w-5" />
Deploy "{projectName}"
<Rocket className="h-5 w-5" />
Deploy Project
</DialogTitle>
<DialogDescription>
Deploy your project to a hosting platform
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="deploy-url">Deploy URL</Label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
https://
</span>
<Input
id="deploy-url"
value={deployUrl}
onChange={(e) => handleUrlChange(e.target.value)}
placeholder={`${projectId}.${config.deployServer}`}
className="pl-16"
disabled={deployMutation.isPending}
/>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
<p className="text-xs text-muted-foreground">
Your project will be deployed to this URL. You can customize the subdomain.
</p>
</div>
{!user && (
<div className="p-3 bg-muted rounded-lg">
<p className="text-sm text-muted-foreground">
You must be logged into Nostr to deploy projects.
</p>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={deployMutation.isPending}
>
Cancel
</Button>
<Button
onClick={handleDeploy}
disabled={!user || !isValidUrl() || deployMutation.isPending}
className="gap-2"
>
{deployMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No deployment providers configured.{' '}
<Link
to="/settings/deploy"
className="underline hover:no-underline"
onClick={handleClose}
>
Configure deployment settings
</Link>
</AlertDescription>
</Alert>
) : (
<CloudUpload className="h-4 w-4" />
<>
<div className="space-y-2">
<Label htmlFor="provider">Select Provider</Label>
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
<SelectTrigger id="provider">
{selectedProvider ? (
<div className="flex items-center gap-2">
{selectedProvider.id === 'netlify' && <SiNetlify size={14} />}
{selectedProvider.id === 'vercel' && <SiVercel size={14} />}
<span>{selectedProvider.name}</span>
</div>
) : (
<SelectValue placeholder="Choose a deployment provider..." />
)}
</SelectTrigger>
<SelectContent>
{settings.providers.map((provider) => (
<SelectItem key={provider.id} value={provider.id}>
<div className="flex items-center gap-2">
{provider.id === 'netlify' && <SiNetlify size={14} />}
{provider.id === 'vercel' && <SiVercel size={14} />}
<span>{provider.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProvider && renderProviderFields()}
{selectedProvider?.type === 'shakespeare' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleClose}>
{t('cancel')}
</Button>
<Button
onClick={handleDeploy}
disabled={
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
}
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
</div>
</>
)}
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
</Button>
</DialogFooter>
</div>
)}
</DialogContent>
</Dialog>
);
}
}
+80
View File
@@ -0,0 +1,80 @@
import { useState, useEffect, useMemo, type ReactNode } from 'react';
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
import { useFS } from '@/hooks/useFS';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
const { fs } = useFS();
const [settings, setSettings] = useState<DeploySettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readDeploySettings(fs);
setSettings(settings);
} catch (error) {
console.error('Failed to initialize deploy settings:', error);
setSettings(DEFAULT_SETTINGS);
} finally {
setIsInitialized(true);
}
};
initializeSettings();
}, [fs]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
if (!isInitialized) return;
const saveSettings = async () => {
try {
await writeDeploySettings(fs, settings);
} catch (error) {
console.error('Failed to save deploy settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized]);
const updateSettings = (updates: Partial<DeploySettings>) => {
setSettings(prev => ({ ...prev, ...updates }));
};
const removeProvider = (index: number) => {
setSettings(prev => ({
...prev,
providers: prev.providers.filter((_, i) => i !== index),
}));
};
const setProviders = (providers: DeployProvider[]) => {
setSettings(prev => ({ ...prev, providers }));
};
const isConfigured = useMemo(() => {
return settings.providers.length > 0;
}, [settings.providers]);
const value = {
settings,
updateSettings,
removeProvider,
setProviders,
isConfigured,
isInitialized,
};
return (
<DeploySettingsContext.Provider value={value}>
{children}
</DeploySettingsContext.Provider>
);
}
+151
View File
@@ -0,0 +1,151 @@
import { useEffect, useRef } from 'react';
import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy';
/**
* Component that dynamically updates the favicon when any project is busy with AI
* Rotates the favicon counter-clockwise when busy
*/
export function DynamicFavicon() {
const isBusy = useAnyProjectBusy();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const animationRef = useRef<number | null>(null);
const rotationRef = useRef(0);
const originalFaviconRef = useRef<string | null>(null);
const originalImageRef = useRef<HTMLImageElement | null>(null);
// Initialize canvas and save original favicon
useEffect(() => {
// Create canvas element for drawing the favicon
if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
canvasRef.current.width = 32;
canvasRef.current.height = 32;
}
// Store the original favicon URL
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement && !originalFaviconRef.current) {
originalFaviconRef.current = faviconElement.getAttribute('href');
}
// Preload the favicon image
if (!originalImageRef.current) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = originalFaviconRef.current || '/shakespeare-192x192.png';
img.onload = () => {
originalImageRef.current = img;
};
}
return () => {
// Restore original favicon on unmount
if (originalFaviconRef.current) {
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', originalFaviconRef.current);
}
}
// Cancel any ongoing animation
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
}
};
}, []);
// Handle busy state changes
useEffect(() => {
if (!canvasRef.current) return;
// If busy, start rotation animation
if (isBusy) {
const startRotationAnimation = () => {
if (!canvasRef.current || !originalImageRef.current) {
// If image isn't loaded yet, try again in a moment
setTimeout(startRotationAnimation, 100);
return;
}
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const img = originalImageRef.current;
const animate = () => {
if (!ctx || !canvas) return;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Save context state
ctx.save();
// Translate to center for rotation
ctx.translate(canvas.width / 2, canvas.height / 2);
// Rotate counter-clockwise
ctx.rotate(-rotationRef.current);
// Draw the image centered
ctx.drawImage(
img,
-canvas.width / 2,
-canvas.height / 2,
canvas.width,
canvas.height
);
// Restore context state
ctx.restore();
// Update rotation for next frame (slower rotation)
rotationRef.current += 0.05;
// Update favicon
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', canvas.toDataURL('image/png'));
}
// Continue animation
animationRef.current = requestAnimationFrame(animate);
};
// Start animation loop
animate();
};
startRotationAnimation();
} else {
// If not busy, restore original favicon and stop animation
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
// Reset rotation
rotationRef.current = 0;
// Restore original favicon
if (originalFaviconRef.current) {
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', originalFaviconRef.current);
}
}
}
return () => {
// Cancel animation on effect cleanup
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
};
}, [isBusy]);
// This component doesn't render anything visible
return null;
}
+204
View File
@@ -0,0 +1,204 @@
import { useState, useEffect } from 'react';
import { Mail, CheckCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
export function EmailSubscription() {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { toast } = useToast();
const [email, setEmail] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
const tag = '8982396';
// Check localStorage on component mount
useEffect(() => {
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
if (hasSubscribed === 'true') {
setIsSubmitted(true);
}
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!email.trim()) {
toast({
title: "Email required",
description: "Please enter your email address",
variant: "destructive",
});
return;
}
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
toast({
title: "Invalid email",
description: "Please enter a valid email address",
variant: "destructive",
});
return;
}
setIsSubmitting(true);
try {
// Submit to Mailchimp
const form = document.createElement('form');
form.method = 'POST';
form.action = url.href;
form.target = '_blank'; // Open in new tab
form.style.display = 'none';
// Add email field
const emailInput = document.createElement('input');
emailInput.type = 'email';
emailInput.name = 'EMAIL';
emailInput.value = email.trim();
form.appendChild(emailInput);
// Add tag field with the new Shakespeare tag ID
const tagInput = document.createElement('input');
tagInput.type = 'hidden';
tagInput.name = 'tags';
tagInput.value = tag;
form.appendChild(tagInput);
// Add npub if available
if (user?.pubkey) {
const npubInput = document.createElement('input');
npubInput.type = 'text';
npubInput.name = 'NPUB';
npubInput.value = nip19.npubEncode(user.pubkey);
npubInput.style.display = 'none';
form.appendChild(npubInput);
}
// Add honeypot field
const honeypotInput = document.createElement('input');
honeypotInput.type = 'text';
honeypotInput.name = honeypot;
honeypotInput.tabIndex = -1;
honeypotInput.style.position = 'absolute';
honeypotInput.style.left = '-5000px';
form.appendChild(honeypotInput);
// Add form to document and submit
document.body.appendChild(form);
form.submit();
// Clean up after a short delay
setTimeout(() => {
document.body.removeChild(form);
}, 1000);
// Save subscription status to localStorage
localStorage.setItem('shakespeare-email-subscribed', 'true');
setIsSubmitted(true);
toast({
title: "Successfully subscribed!",
description: "You'll receive Shakespeare updates and resources occasionally.",
});
} catch (error) {
console.error('Email signup error:', error);
toast({
title: "Subscription failed",
description: "There was an error subscribing you to updates. Please try again.",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
if (isSubmitted) {
return (
<Card>
<CardContent className="pt-6">
<div className="text-center space-y-4">
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
<div className="space-y-2">
<h3 className="text-lg font-semibold">
Thanks for subscribing!
</h3>
<p className="text-muted-foreground text-sm">
You can opt out at any time using the unsubscribe link in our emails.
</p>
</div>
<Button
onClick={() => {
localStorage.removeItem('shakespeare-email-subscribed');
setIsSubmitted(false);
setEmail('');
}}
variant="outline"
className="w-full text-xs"
>
Subscribe with different email
</Button>
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Mail className="h-5 w-5 text-primary" />
{t('emailUpdates')}
</CardTitle>
<CardDescription>
{t('emailUpdatesDescription')}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">
Email Address
</Label>
<Input
id="email"
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isSubmitting}
required
/>
</div>
<div className="space-y-3">
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
>
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
</Button>
<p className="text-xs text-muted-foreground text-center">
You can opt out at any time using the unsubscribe link in our emails.
</p>
</div>
</form>
</CardContent>
</Card>
);
}
+418
View File
@@ -0,0 +1,418 @@
import React, { useState, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { AlertTriangle, Trash2, CheckCircle, Loader2, HardDrive } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { cn } from '@/lib/utils';
import { importFullSystem, validateExportFile, type ImportProgress, type ImportValidation } from '@/lib/fullSystemImport';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { FileUploadArea } from '@/components/ui/file-upload-area';
interface FullSystemImportDialogProps {
onImport?: () => void;
disabled?: boolean;
className?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
interface ImportState {
selectedFile: File | null;
validation: ImportValidation | null;
isImporting: boolean;
importProgress: ImportProgress | null;
error: string | null;
isDragOver: boolean;
showWarningDialog: boolean;
importComplete: boolean;
}
export function FullSystemImportDialog({
onImport,
disabled = false,
className,
open,
onOpenChange
}: FullSystemImportDialogProps) {
// Use controlled state if props are provided, otherwise use internal state
const [internalIsOpen, setInternalIsOpen] = useState(false);
const isOpen = open !== undefined ? open : internalIsOpen;
const setIsOpen = onOpenChange || setInternalIsOpen;
// Consolidated state management
const [state, setState] = useState<ImportState>({
selectedFile: null,
validation: null,
isImporting: false,
importProgress: null,
error: null,
isDragOver: false,
showWarningDialog: false,
importComplete: false
});
const { toast } = useToast();
const { fs } = useFS();
const updateState = (updates: Partial<ImportState>) => {
setState(prev => ({ ...prev, ...updates }));
};
const handleFileSelect = async (file: File) => {
if (!file.name.toLowerCase().endsWith('.zip')) {
updateState({ error: 'Please select a ZIP file', selectedFile: file, validation: null, importComplete: false });
return;
}
updateState({ selectedFile: file, error: null, validation: null, importComplete: false });
try {
const validationResult = await validateExportFile(file);
updateState({ validation: validationResult });
if (!validationResult.isValid) {
updateState({ error: `Invalid export: ${validationResult.errors.slice(0, 2).join(', ')}` });
}
} catch (err) {
updateState({ error: err instanceof Error ? err.message : 'Failed to validate file' });
}
};
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
updateState({ isDragOver: true });
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
updateState({ isDragOver: false });
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
updateState({ isDragOver: false });
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
const file = files[0];
if (!file.name.toLowerCase().endsWith('.zip')) {
updateState({ error: 'Please select a ZIP file', selectedFile: file, validation: null, importComplete: false });
return;
}
updateState({ selectedFile: file, error: null, validation: null, importComplete: false });
validateExportFile(file).then(validationResult => {
updateState({ validation: validationResult });
if (!validationResult.isValid) {
updateState({ error: `Invalid export: ${validationResult.errors.slice(0, 2).join(', ')}` });
}
}).catch(err => {
updateState({ error: err instanceof Error ? err.message : 'Failed to validate file' });
});
}
}, []);
const handleFileRemove = () => {
updateState({ selectedFile: null, validation: null, error: null, importComplete: false });
};
const handleImportStart = () => {
if (!state.selectedFile || !state.validation?.isValid) return;
updateState({ showWarningDialog: true });
};
const handleImportConfirm = async () => {
if (!state.selectedFile) return;
updateState({ showWarningDialog: false, isImporting: true, importProgress: null, error: null });
try {
await importFullSystem(state.selectedFile, fs, (progress) => {
updateState({ importProgress: progress });
});
updateState({ importComplete: true });
toast({
title: 'Import Successful',
description: 'Your workspace has been completely restored.',
});
if (onImport) onImport();
setTimeout(() => {
setIsOpen(false);
window.location.reload();
}, 2000);
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Import failed';
updateState({ error: errorMsg, importProgress: null, isImporting: false });
toast({
title: 'Import Failed',
description: errorMsg,
variant: 'destructive',
});
}
};
const handleClose = () => {
if (!state.isImporting) {
setIsOpen(false);
updateState({
selectedFile: null,
validation: null,
error: null,
importProgress: null,
importComplete: false
});
}
};
const getStageDescription = (stage: ImportProgress['stage']): string => {
const descriptions = {
extracting: 'Extracting ZIP file...',
validating: 'Validating export...',
creating_temp: 'Setting up workspace...',
importing: 'Importing files...',
replacing: 'Replacing system...',
cleanup: 'Cleaning up...',
complete: 'Import completed!'
};
return descriptions[stage] || 'Processing...';
};
const isControlled = open !== undefined && onOpenChange !== undefined;
return (
<>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
{!isControlled && (
<DialogTrigger asChild>
<Button
variant="outline"
disabled={disabled}
className={cn("gap-2 text-destructive border-destructive hover:bg-destructive hover:text-destructive-foreground", className)}
>
<HardDrive className="h-4 w-4" />
Import System
</Button>
</DialogTrigger>
)}
<DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<HardDrive className="h-5 w-5 text-destructive" />
Import System
</DialogTitle>
<DialogDescription>
Select a Shakespeare export file to replace your entire workspace.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{!state.isImporting && (
<Alert className="border-destructive/50 bg-destructive/5">
<AlertTriangle className="h-4 w-4 text-destructive" />
<AlertDescription className="text-destructive">
<strong>Warning:</strong> This action will <strong>completely replace</strong> your Shakespeare workspace with the imported data.
All current projects, AI settings, Git credentials, and preferences will be <strong>permanently deleted</strong>.
</AlertDescription>
</Alert>
)}
{!state.isImporting && !state.importComplete && (
<>
<FileUploadArea
selectedFile={state.selectedFile}
isDragOver={state.isDragOver}
isValid={state.validation?.isValid ?? false}
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
disabled={state.isImporting}
accept=".zip"
className="mb-4"
>
<div className="space-y-3">
<div className="flex justify-center">
{state.selectedFile ? (
state.validation?.isValid ? (
<CheckCircle className="h-8 w-8 text-green-600" />
) : (
<Trash2 className="h-8 w-8 text-destructive" />
)
) : (
<HardDrive className="h-8 w-8 text-muted-foreground" />
)}
</div>
<div>
{state.selectedFile ? (
<div className="space-y-2">
<p className="text-sm font-medium">{state.selectedFile.name}</p>
<p className="text-xs text-muted-foreground">
{(state.selectedFile.size / 1024 / 1024).toFixed(2)} MB
</p>
<button
onClick={(e) => {
e.stopPropagation();
handleFileRemove();
}}
className="text-xs text-destructive hover:underline"
>
Remove file
</button>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-medium">
Drop ZIP file here or click to browse
</p>
<p className="text-xs text-muted-foreground">
Only Shakespeare export ZIP files
</p>
</div>
)}
</div>
</div>
</FileUploadArea>
{state.validation && (
<div className="text-sm space-y-2 p-3 bg-muted rounded">
<div className="flex justify-between">
<span>Projects:</span>
<span className="font-medium">{state.validation.projectCount}</span>
</div>
<div className="flex justify-between">
<span>Files:</span>
<span className="font-medium">{state.validation.totalFiles}</span>
</div>
{state.validation.errors.length > 0 && (
<div className="text-xs text-destructive">
{state.validation.errors.slice(0, 2).join(', ')}
</div>
)}
</div>
)}
{state.error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{state.error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2 pt-4">
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleImportStart}
disabled={!state.selectedFile || !state.validation?.isValid}
variant="destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Replace Entire System
</Button>
</div>
</>
)}
{state.isImporting && state.importProgress && (
<div className="space-y-4">
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{getStageDescription(state.importProgress.stage)}
</div>
<Progress value={state.importProgress.progress} className="w-full" />
<div className="flex justify-between text-xs text-muted-foreground">
<span>{state.importProgress.message}</span>
<span>{Math.round(state.importProgress.progress)}%</span>
</div>
</div>
<Alert>
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Please do not close this window during import.
</AlertDescription>
</Alert>
</div>
)}
{state.importComplete && (
<Alert className="border-green-500/50 bg-green-500/5">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-600">
Import completed successfully! Reloading page...
</AlertDescription>
</Alert>
)}
</div>
</DialogContent>
</Dialog>
<AlertDialog open={state.showWarningDialog} onOpenChange={(open) => updateState({ showWarningDialog: open })}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Confirm Complete System Replacement
</AlertDialogTitle>
<AlertDialogDescription className="space-y-3">
<p>
You are about to <strong>completely replace</strong> your workspace with imported data.
</p>
<div className="bg-destructive/10 border border-destructive/20 rounded p-3">
<p className="text-sm font-medium text-destructive mb-2">This will permanently delete:</p>
<ul className="list-disc list-inside text-sm text-destructive space-y-1">
<li>All current projects and their files</li>
<li>AI provider settings and API keys</li>
<li>Git credentials and repository settings</li>
<li>User preferences and theme settings</li>
<li>All cached data and temporary files</li>
</ul>
</div>
{state.validation && (
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded p-3">
<p className="text-sm font-medium text-green-800 dark:text-green-200 mb-2">Import will restore:</p>
<ul className="list-disc list-inside text-sm text-green-700 dark:text-green-300 space-y-1">
<li>{state.validation.projectCount} projects</li>
<li>{state.validation.totalFiles} total files</li>
{state.validation.hasConfig && <li>Settings, themes, and preferences</li>}
</ul>
</div>
)}
<p className="text-destructive font-medium">
This action cannot be undone. Are you absolutely sure?
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleImportConfirm}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Yes, Replace Everything
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
File diff suppressed because it is too large. Load diff
+4 -42
View File
@@ -14,7 +14,7 @@ vi.mock('@/lib/configUtils', () => ({
// Test component that uses the hook
function TestComponent() {
const { settings, updateSettings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const handleAdd = () => {
const credential: GitCredential = {
@@ -32,21 +32,13 @@ function TestComponent() {
removeCredential('https://github.com');
};
const handleUpdateCorsProxy = () => {
updateSettings({ corsProxy: 'https://custom-cors.example.com' });
};
return (
<div>
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
<div data-testid="cors-proxy">{settings.corsProxy}</div>
<button onClick={handleAdd}>Add GitHub</button>
<button onClick={handleUpdate}>Update GitHub</button>
<button onClick={handleRemove}>Remove GitHub</button>
<button onClick={handleUpdateCorsProxy}>Update CORS Proxy</button>
{settings.credentials['https://github.com'] && (
<div data-testid="github-creds">
{settings.credentials['https://github.com'].username}:
@@ -76,7 +68,7 @@ describe('GitSettingsProvider', () => {
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
corsProxy: 'https://cors.isomorphic-git.org',
hostTokens: {},
});
});
@@ -178,8 +170,7 @@ describe('GitSettingsProvider', () => {
username: 'git',
password: 'test-token',
}
},
corsProxy: 'https://proxy.shakespeare.diy/?url={href}'
}
})
);
});
@@ -193,7 +184,7 @@ describe('GitSettingsProvider', () => {
password: 'gitlab-token',
},
},
corsProxy: 'https://custom-cors.example.com',
hostTokens: {},
};
const { readGitSettings } = await import('@/lib/configUtils');
@@ -208,37 +199,8 @@ describe('GitSettingsProvider', () => {
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
expect(screen.getByTestId('count')).toHaveTextContent('1');
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
});
});
it('provides default CORS proxy', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
});
it('can update CORS proxy', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
fireEvent.click(screen.getByText('Update CORS Proxy'));
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
});
});
+39 -6
View File
@@ -1,5 +1,5 @@
import { ReactNode, useState, useEffect } from 'react';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { useFS } from '@/hooks/useFS';
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
@@ -9,7 +9,7 @@ interface GitSettingsProviderProps {
const DEFAULT_SETTINGS: GitSettings = {
credentials: {},
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
hostTokens: {},
};
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
@@ -22,10 +22,6 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
const initializeSettings = async () => {
try {
const settings = await readGitSettings(fs);
// Migrate old CORS proxy format
if (settings.corsProxy === 'https://cors.isomorphic-git.org') {
settings.corsProxy = DEFAULT_SETTINGS.corsProxy;
}
setSettings(settings);
} catch (error) {
console.error('Failed to initialize Git settings:', error);
@@ -90,6 +86,39 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
}));
};
const addHostToken = (host: string, token: GitHostToken) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: token,
},
}));
};
const removeHostToken = (host: string) => {
setSettings(prev => {
const { [host]: removed, ...rest } = prev.hostTokens;
return {
...prev,
hostTokens: rest,
};
});
};
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: {
...prev.hostTokens[host],
...token,
},
},
}));
};
const isConfigured = Object.entries(settings.credentials).length > 0;
const contextValue: GitSettingsContextType = {
@@ -98,7 +127,11 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
addCredential,
removeCredential,
updateCredential,
addHostToken,
removeHostToken,
updateHostToken,
isConfigured,
isInitialized,
};
return (
+50
View File
@@ -0,0 +1,50 @@
import { Decimal } from 'decimal.js';
import { cn } from '@/lib/utils';
interface ModelPricingProps {
pricing: { prompt: Decimal; completion: Decimal };
className?: string;
}
/**
* Get a single normalized "price per token" for a model,
* combining input and output pricing with agentic-coding-aware weights.
*
* Default behavior:
* - Uses inputWeight = 0.20 (based on typical 3–5x output premium seen in practice).
*
* Optional behavior:
* - If you pass observed token usage, the function will compute the weight
* as the observed share of spend from inputs over total spend.
*/
function getNormalizedModelPrice(
pricing: { prompt: Decimal; completion: Decimal },
inputWeight = 0.2,
): Decimal {
if (!(inputWeight >= 0 && inputWeight <= 1)) {
throw new Error("Computed inputWeight is out of range [0,1]. Check inputs.");
}
if (pricing.prompt.equals(0) && pricing.completion.equals(0)) {
return new Decimal(0);
}
const outputWeight = 1 - inputWeight;
return pricing.prompt.times(inputWeight).plus(pricing.completion.times(outputWeight));
}
export function ModelPricing({ pricing, className }: ModelPricingProps) {
const normalizedPrice = getNormalizedModelPrice(pricing).times(1_000_000).toNumber();
if (normalizedPrice === 0) {
return <span className={cn("text-green-600 font-semibold", className)}>Free</span>;
} else if (normalizedPrice < 10) {
return <span className={cn("text-green-600 font-semibold", className)}>$</span>;
} else if (normalizedPrice >= 10 && normalizedPrice < 15) {
return <span className={cn("text-yellow-600 font-semibold", className)}>$$</span>;
} else if (normalizedPrice >= 15 && normalizedPrice < 50) {
return <span className={cn("text-red-600 font-semibold", className)}>$$$</span>;
} else if (normalizedPrice >= 50) {
return <span className={cn("text-red-800 font-semibold", className)}>$$$$</span>;
}
return null;
}
+401 -7
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Decimal } from 'decimal.js';
import { TestApp } from '@/test/TestApp';
import { ModelSelector } from './ModelSelector';
@@ -12,6 +14,10 @@ vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: vi.fn(),
}));
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(),
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
@@ -22,9 +28,11 @@ vi.mock('react-router-dom', async (importOriginal) => {
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseProviderModels = vi.mocked(useProviderModels);
const mockUseIsMobile = vi.mocked(useIsMobile);
describe('ModelSelector', () => {
const mockOnChange = vi.fn();
@@ -41,7 +49,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
mockUseProviderModels.mockReturnValue({
@@ -50,6 +58,8 @@ describe('ModelSelector', () => {
error: null,
refetch: vi.fn(),
});
mockUseIsMobile.mockReturnValue(false);
});
it('hides recently used section when less than 5 models and all recently used are available', async () => {
@@ -77,7 +87,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -92,11 +102,17 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
expect(screen.getByText('provider2')).toBeInTheDocument();
});
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 should still show with model3
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
@@ -124,7 +140,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -173,7 +189,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -188,11 +204,19 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
expect(screen.getByText('provider2')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 and provider3 should still show
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
@@ -216,7 +240,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -237,4 +261,374 @@ describe('ModelSelector', () => {
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
it('shows caution icon for free models', async () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
const paidModel = {
fullId: 'provider1/paid-model',
provider: 'provider1',
id: 'paid-model',
pricing: {
prompt: new Decimal('0.01'),
completion: new Decimal('0.02'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel, paidModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
// Test with free model selected
const { rerender } = render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
// Should show caution icon for free model
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
// Test with paid model selected
rerender(
<TestApp>
<ModelSelector value="provider1/paid-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for paid model
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon when no model is selected', () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon when no model is selected
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon for models without pricing information', () => {
const modelWithoutPricing = {
fullId: 'provider1/unknown-pricing',
provider: 'provider1',
id: 'unknown-pricing',
// No pricing property
};
mockUseProviderModels.mockReturnValue({
models: [modelWithoutPricing],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-pricing" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for models without pricing info
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('shows tooltip when hovering over caution icon', async () => {
const user = userEvent.setup();
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionIcon = screen.getByTestId('triangle-alert');
expect(cautionIcon).toBeInTheDocument();
// Hover over the caution icon
await user.hover(cautionIcon);
// Wait for tooltip to appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
});
it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => {
const user = userEvent.setup();
mockUseIsMobile.mockReturnValue(true);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile
// Click to open tooltip - just verify the click works without errors
await user.click(cautionButton);
// Tooltip should appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
// The button should still be clickable (no errors)
await user.click(cautionButton);
expect(cautionButton).toBeInTheDocument();
});
it('makes caution icon not focusable on desktop', () => {
mockUseIsMobile.mockReturnValue(false);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop
});
it('shows warning icon when selected model is not in provider models list', () => {
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
</TestApp>
);
// Should show warning icon for model not in list
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
});
it('does not show warning icon when selected model is in provider models list', () => {
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/model1" onChange={mockOnChange} />
</TestApp>
);
// Should not show warning icon when model is in list
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show warning icon while models are loading', () => {
mockUseProviderModels.mockReturnValue({
models: [],
isLoading: true,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show warning icon while loading
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show warning icon when no models are loaded', () => {
mockUseProviderModels.mockReturnValue({
models: [],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/some-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show warning icon when no models loaded
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('shows correct tooltip message for model not in list', async () => {
const user = userEvent.setup();
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
</TestApp>
);
const warningIcon = screen.getByTestId('triangle-alert');
expect(warningIcon).toBeInTheDocument();
// Hover over the warning icon
await user.hover(warningIcon);
// Wait for tooltip to appear
await waitFor(() => {
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
});
});
it('prioritizes "not in list" warning over "free model" warning in tooltip', async () => {
const user = userEvent.setup();
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-free-model" onChange={mockOnChange} />
</TestApp>
);
const warningIcon = screen.getByTestId('triangle-alert');
expect(warningIcon).toBeInTheDocument();
// Hover over the warning icon
await user.hover(warningIcon);
// Wait for tooltip to appear - should show "not in list" message, not "free model" message
await waitFor(() => {
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
});
// Should not show the free model message
expect(screen.queryByText('You are using a free model. For better results, switch to a paid model.')).not.toBeInTheDocument();
});
});
+289 -154
View File
@@ -1,14 +1,17 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useEffect, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ModelPricing } from '@/components/ModelPricing';
import { cn } from '@/lib/utils';
interface ModelSelectorProps {
@@ -21,7 +24,7 @@ interface ModelSelectorProps {
onOpenChange?: (open: boolean) => void;
}
export function ModelSelector({
export const ModelSelector = memo(function ModelSelector({
value,
onChange,
className,
@@ -32,6 +35,7 @@ export function ModelSelector({
}: ModelSelectorProps) {
const { t } = useTranslation();
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
// Use controlled state if provided, otherwise use local state
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
@@ -42,22 +46,31 @@ export function ModelSelector({
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const isMobile = useIsMobile();
const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Group models by provider
// Create a Set of recently used model IDs for efficient lookup
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
// Group models by provider, excluding models that are in the recently used section
const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof models> = {};
for (const model of models) {
// Skip models that are already shown in recently used
if (recentlyUsedSet.has(model.fullId)) {
continue;
}
if (!groups[model.provider]) {
groups[model.provider] = [];
}
groups[model.provider].push(model);
}
return groups;
}, [models]);
}, [models, recentlyUsedSet]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
@@ -82,9 +95,67 @@ export function ModelSelector({
return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]);
// Check if the current model is free
const isCurrentModelFree = useMemo(() => {
if (!value) return false;
const currentModel = models.find(model => model.fullId === value);
if (!currentModel?.pricing) return false;
return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0);
}, [value, models]);
// Check if the current model is not in the provider's model list
const isCurrentModelNotInList = useMemo(() => {
if (!value) return false;
if (isLoading) return false; // Don't show warning while loading
if (models.length === 0) return false; // Don't show warning if no models loaded
const currentModel = models.find(model => model.fullId === value);
return !currentModel;
}, [value, models, isLoading]);
// Determine if we should show the warning icon
const shouldShowWarning = isCurrentModelFree || isCurrentModelNotInList;
// Get the warning message
const warningMessage = useMemo(() => {
if (isCurrentModelNotInList) {
return "This model is not available in your provider's model list. It may not work or may have been deprecated.";
}
if (isCurrentModelFree) {
return "You are using a free model. For better results, switch to a paid model.";
}
return "";
}, [isCurrentModelNotInList, isCurrentModelFree]);
// Don't auto-initialize with recently used models
// Let the parent component handle initialization
// Close tooltip when clicking outside on mobile
useEffect(() => {
if (!isMobile || !isTooltipOpen) return;
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
const target = event.target as Element;
// Check if the click is outside the tooltip and trigger
if (!target.closest('[data-radix-tooltip-content]') &&
!target.closest('[data-radix-tooltip-trigger]') &&
!target.closest('[data-testid="triangle-alert"]')) {
setIsTooltipOpen(false);
}
};
// Add both click and touch event listeners
document.addEventListener('click', handleClickOutside, true);
document.addEventListener('touchstart', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
document.removeEventListener('touchstart', handleClickOutside, true);
};
}, [isMobile, isTooltipOpen]);
const handleSelect = (selectedValue: string) => {
if (selectedValue === '__custom__') {
setIsCustomInput(true);
@@ -125,167 +196,231 @@ export function ModelSelector({
if (isCustomInput) {
return (
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
<TooltipProvider>
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
</TooltipProvider>
);
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
<CommandList className="max-h-[300px]">
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<TooltipProvider>
<div className={cn("flex justify-end gap-0.5", className)}>
{shouldShowWarning && (
<Tooltip
open={isMobile ? isTooltipOpen : undefined}
onOpenChange={isMobile ? setIsTooltipOpen : undefined}
delayDuration={isMobile ? 0 : 700}
disableHoverableContent={isMobile}
>
<TooltipTrigger asChild>
<button
type="button"
className="inline-flex items-center p-0 rounded-none border-0 bg-transparent hover:bg-transparent focus:bg-transparent active:bg-transparent focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 focus:border-0 active:outline-none"
aria-label="Model warning"
tabIndex={isMobile ? 0 : -1}
onClick={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
onTouchStart={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
} : undefined}
onTouchEnd={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
style={{
WebkitTapHighlightColor: 'transparent',
outline: 'none',
border: 'none',
boxShadow: 'none'
}}
>
<TriangleAlert className="h-3 w-3 text-amber-500 flex-shrink-0" data-testid="triangle-alert" />
</button>
</TooltipTrigger>
<TooltipContent
side="top"
sideOffset={4}
className="max-w-xs text-center"
avoidCollisions={true}
collisionPadding={8}
>
<p>{warningMessage}</p>
</TooltipContent>
</Tooltip>
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
)}
disabled={disabled}
>
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-80" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList>
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</div>
</CommandGroup>
)}
</CommandEmpty>
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((modelId) => {
const modelData = models.find(m => m.fullId === modelId);
return (
<CommandItem
key={modelId}
value={modelId}
onSelect={() => handleSelect(modelId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === modelId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate flex-1">{modelId}</span>
{modelData?.pricing && (
<ModelPricing pricing={modelData.pricing} className="ml-2" />
)}
</CommandItem>
);
})}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</div>
</div>
</CommandGroup>
)}
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate flex-1">{model.fullId}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandGroup>
{isConfigured && (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
))}
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</TooltipProvider>
);
}
});
+4 -9
View File
@@ -15,16 +15,11 @@ const GIT_KINDS = [
1621, // NIP-34 Issue
];
const GIT_RELAYS = [
'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/',
'wss://gitnostr.com/',
];
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
const queryClient = useQueryClient();
// Create NPool instance only once
@@ -36,7 +31,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
@@ -51,7 +46,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) {
// If all filters are git-related, route to all git relays
for (const url of GIT_RELAYS) {
for (const url of gitRelays) {
routes.set(url, filters);
}
}
@@ -63,7 +58,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
// If it's a git-related event, also publish to the git relays
if (GIT_KINDS.includes(event.kind)) {
for (const url of GIT_RELAYS) {
for (const url of gitRelays) {
allRelays.add(url);
}
}
@@ -0,0 +1,103 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { OnboardingCreditsBadge } from './OnboardingCreditsBadge';
import type { UseQueryResult } from '@tanstack/react-query';
import type { CreditsResponse } from '@/hooks/useAICredits';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: vi.fn(),
}));
import { useAICredits } from '@/hooks/useAICredits';
const mockUseAICredits = vi.mocked(useAICredits);
describe('OnboardingCreditsBadge', () => {
const mockProvider = {
id: 'shakespeare',
baseURL: 'https://ai.shakespeare.diy/v1',
nostr: true,
};
it('renders credits badge when data is available', () => {
mockUseAICredits.mockReturnValue({
data: { object: 'credits', amount: 25.50 },
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(screen.getByText('$25.50')).toBeInTheDocument();
});
it('does not render when loading', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: true,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when there is an error', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: false,
error: new Error('Provider does not support credits'),
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when no credits data is available', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when credits amount is 0', () => {
mockUseAICredits.mockReturnValue({
data: { object: 'credits', amount: 0 },
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
});
+42
View File
@@ -0,0 +1,42 @@
import { Badge } from '@/components/ui/badge';
import { AIProvider } from '@/contexts/AISettingsContext';
import { useAICredits } from '@/hooks/useAICredits';
interface OnboardingCreditsBadgeProps {
provider: AIProvider;
className?: string;
}
/**
* Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider
*/
export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(provider);
// Don't render anything if there's an error (provider doesn't support credits endpoint)
if (error || isLoading) {
return null;
}
// Don't render if no credits data is available or if amount is 0
if (!credits || credits.amount === 0) {
return null;
}
// Format the amount as currency
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(credits.amount);
return (
<Badge
variant="secondary"
className={`text-xs ${className}`}
>
{formattedAmount}
</Badge>
);
}
+1 -1
View File
@@ -42,7 +42,7 @@ describe('OnboardingDialog', () => {
</TestApp>
);
expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
});
+341 -87
View File
@@ -1,59 +1,99 @@
import { Decimal } from 'decimal.js';
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Card, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Checkbox } from '@/components/ui/checkbox';
import { PasswordInput } from '@/components/ui/password-input';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useProviderModels } from '@/hooks/useProviderModels';
import { CreditsDialog } from '@/components/CreditsDialog';
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ModelPricing } from '@/components/ModelPricing';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { cn } from '@/lib/utils';
interface OnboardingDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion';
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
const [step, setStep] = useState<OnboardingStep>('welcome');
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
const [providerApiKey, setProviderApiKey] = useState<string>('');
const [selectedModel, setSelectedModel] = useState<string>('');
const [isSettingUp, setIsSettingUp] = useState(false);
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
// Ref for the scrollable content area
const scrollableContentRef = useRef<HTMLDivElement>(null);
const { setProvider, addRecentlyUsedModel } = useAISettings();
const { user } = useCurrentUser();
const login = useLoginActions();
const { models, isLoading: isLoadingModels } = useProviderModels();
// Filter models to only show Shakespeare provider models
const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
// Filter models to only show selected provider models
const providerModels = selectedProvider
? models.filter(model => model.provider === selectedProvider.id)
: [];
const handleGetStarted = () => {
setStep('open-source');
};
const handleContinueFromOpenSource = () => {
if (!agreedToTerms) return;
setStep('provider-selection');
};
const handleProviderSelect = (provider: PresetProvider) => {
setSelectedProvider(provider);
// Clear API key when switching providers
setProviderApiKey('');
// Reset provider terms agreement when switching providers
setAgreedToProviderTerms(false);
};
const handleContinueFromProviderSelection = async () => {
if (!selectedProvider) return;
// Check if user agreed to provider terms
if (!agreedToProviderTerms) return;
// Check if provider requires API key and if it's provided
const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr;
if (requiresApiKey && !providerApiKey.trim()) return;
const handleGetStarted = async () => {
setIsSettingUp(true);
try {
// If user is not logged in, generate and login with secret key
if (!user) {
// If user is not logged in and provider uses Nostr auth, generate and login with secret key
if (!user && selectedProvider.nostr) {
const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey);
login.nsec(nsec);
}
// Add Shakespeare provider to their config
setProvider(SHAKESPEARE_PROVIDER);
// Add selected provider to their config
const providerConfig = {
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
};
setProvider(providerConfig);
// Move to model selection
setStep('model-selection');
@@ -75,7 +115,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
addRecentlyUsedModel(selectedModel);
// Find the selected model to check if it's free
const model = shakespeareModels.find(m => m.fullId === selectedModel);
const model = providerModels.find(m => m.fullId === selectedModel);
const isFreeModel = !model?.pricing || (
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
);
@@ -98,31 +138,34 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
onOpenChange(false);
};
const formatPrice = (price: Decimal | undefined) => {
if (!price) return 'unknown';
if (price.equals(0)) return 'Free';
// Convert from per-token to per-1M tokens and format with $ prefix
const pricePerMillion = price.times(1_000_000);
return '$' + pricePerMillion.toFixed(2).toString().replace(/\.00$/, '') + '/M tokens';
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
setSelectedProvider(null);
setProviderApiKey('');
setSelectedModel('');
setIsSettingUp(false);
setShowCreditsDialog(false);
setAgreedToTerms(false);
setAgreedToProviderTerms(false);
}
}, [open]);
// Scroll to top when step changes
useEffect(() => {
if (scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}, [step]);
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
<DialogHeader>
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2">
{step === 'model-selection' && (
{step === 'open-source' && (
<Button
variant="ghost"
size="sm"
@@ -132,24 +175,54 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'provider-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('open-source')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'model-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('provider-selection')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('model-selection')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
<span className="text-xl">
{step === 'welcome' && 'Welcome to Shakespeare!'}
{step === 'model-selection' && 'Choose Your AI Model'}
{step === 'conclusion' && "You're All Set!"}
</span>
</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-hidden">
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
{step === 'welcome' && (
<div className="text-center space-y-6 py-4">
<div className="text-6xl mb-4">🎭</div>
<div className="mb-4">
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Shakespeare!
</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your AI-powered development assistant for building custom Nostr applications.
Your AI-powered development assistant for building custom applications.
Simply describe what you want to build, and AI will help you create it.
</p>
</div>
@@ -190,16 +263,215 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div>
)}
{step === 'model-selection' && (
<div className="space-y-4">
<div className="text-center space-y-2">
<p className="text-muted-foreground">
Choose an AI model to power your development experience.
Different models offer various capabilities and pricing.
{step === 'open-source' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">
Shakespeare is Open Source software that runs entirely in your web&nbsp;browser
</h2>
</div>
<div className="grid gap-1 max-w-md mx-auto">
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Your device connects directly to third-party AI providers of your choice</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Your files are stored on your device in your browser</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Be careful not to delete your browser data or you may lose project files</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">You are responsible for taking backups or syncing to git</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Quality of output depends on quality of input and models used, and is not guaranteed</p>
</div>
</div>
<div className="space-y-3 max-w-md mx-auto">
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
Shakespeare is not a cloud service. It's Open Source software that runs on your device.
You agree to the Terms of Service of AI providers you interact with.
Shakespeare is provided "as is" without warranty of any kind.
</p>
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-terms"
checked={agreedToTerms}
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
/>
<label
htmlFor="agree-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree
</label>
</div>
</div>
<div className="flex justify-center">
<Button
onClick={handleContinueFromOpenSource}
disabled={!agreedToTerms}
className="gap-2 rounded-full w-full max-w-md"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'provider-selection' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">Choose your AI provider</h2>
<p className="text-muted-foreground max-w-md mx-auto">
Select an AI provider to power your development assistant. You can add more providers later in settings.
</p>
</div>
<ScrollArea className="h-96">
<div className="grid grid-cols-1 md:grid-cols-2 p-1 gap-3 max-w-4xl mx-auto">
{AI_PROVIDER_PRESETS.map((provider) => {
const isSelected = selectedProvider?.id === provider.id;
const isShakespeare = provider.id === 'shakespeare';
return (
<Card
key={provider.id}
className={cn('cursor-pointer transition-all hover:shadow-md', {
'ring-2 ring-primary': isSelected,
})}
onClick={() => handleProviderSelect(provider)}
>
<div className="flex items-center justify-between p-3">
<div className="flex-1">
<CardTitle className={cn('text-lg font-semibold', {
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isShakespeare,
})}>
{provider.name}
</CardTitle>
</div>
<div className="flex items-center gap-2">
<OnboardingCreditsBadge provider={provider} />
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</Card>
);
})}
</div>
{/* 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">
{selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'}
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
<>{selectedProvider.name} requires a Cashu token</>
) : (
<>
{selectedProvider.name} requires an {selectedProvider.apiKeysURL ? (
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
API key
<ExternalLink className="inline-block h-4 w-4 ml-1" />
</a>
) : (
<>API key</>
)}
</>
)}
</p>
</div>
<PasswordInput
placeholder={selectedProvider.id === 'routstr' ? 'Enter a Cashu Token' : 'Enter your API key'}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim()) {
handleContinueFromProviderSelection();
}
}}
/>
</div>
)}
{/* Terms of Service Agreement */}
{selectedProvider && (
<div className="space-y-3 max-w-md mx-auto">
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToProviderTerms}
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
/>
<label
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 {selectedProvider.name}'s{' '}
{selectedProvider.tosURL ? (
<a
href={selectedProvider.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
Terms of Service
</a>
) : (
'Terms of Service'
)}
</label>
</div>
</div>
)}
<div className="flex justify-center">
<Button
onClick={handleContinueFromProviderSelection}
disabled={
!selectedProvider ||
isSettingUp ||
!agreedToProviderTerms ||
!!(selectedProvider?.apiKeysURL && !selectedProvider?.nostr && !providerApiKey.trim())
}
className="gap-2 rounded-full w-full max-w-md"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
Continue
<ArrowRight className="h-4 w-4" />
</>
)}
</Button>
</div>
</div>
)}
{step === 'model-selection' && (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto min-h-0 my-4">
<div className="space-y-3 p-1">
{isLoadingModels ? (
<>
@@ -219,7 +491,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Card>
))}
</>
) : shakespeareModels.length === 0 ? (
) : providerModels.length === 0 ? (
<Card className="p-6 text-center">
<div className="space-y-2">
<Bot className="h-8 w-8 mx-auto text-muted-foreground" />
@@ -229,65 +501,48 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div>
</Card>
) : (
shakespeareModels.map((model) => {
providerModels.map((model) => {
const isSelected = selectedModel === model.fullId;
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
const modelName = model.name || model.id;
return (
<Card
key={model.fullId}
className={`cursor-pointer transition-all hover:shadow-md ${
className={`relative cursor-pointer transition-all hover:shadow-md ${
isSelected ? 'ring-2 ring-primary' : ''
}`}
onClick={() => handleModelSelect(model.fullId)}
>
<CardHeader className="pb-3">
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex-1">
<CardTitle className="text-base font-semibold">
{model.description || model.name || model.id}
<CardTitle className="text-sm font-semibold flex gap-1">
<span>{modelName}</span>
{model.pricing && <ModelPricing pricing={model.pricing} />}
</CardTitle>
{model.description && (
<p className="text-sm text-muted-foreground mt-1">
{model.name || model.id}
<p className="text-lg text-muted-foreground mt-1">
{model.description.length > 500
? model.description.slice(0, 500) + '...'
: model.description}
</p>
)}
</div>
<div className="flex items-center gap-2">
{isFree && (
<Badge variant="secondary" className="text-xs">
Free
</Badge>
)}
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
{isSelected && (
<div className="absolute top-5 right-5 h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{model.pricing && (
<>
<span>Input: {formatPrice(model.pricing.prompt)}</span>
<span>Output: {formatPrice(model.pricing.completion)}</span>
</>
)}
{model.contextLength && (
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
)}
</div>
</CardContent>
</Card>
);
})
)}
</div>
</ScrollArea>
</div>
<div className="flex justify-end gap-2 pt-4 border-t">
<div className="flex justify-end gap-2 pt-4 flex-shrink-0">
<Button
onClick={handleContinue}
disabled={!selectedModel}
@@ -310,11 +565,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
Just enter your prompt to start building amazing Nostr applications.
</p>
</div>
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
<p className="text-sm text-muted-foreground italic">
"Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
</p>
</div>
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building
@@ -326,7 +576,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Dialog>
{/* Credits Dialog */}
{showCreditsDialog && selectedModel && (
{showCreditsDialog && selectedModel && selectedProvider && (
<CreditsDialog
open={showCreditsDialog}
onOpenChange={(open) => {
@@ -334,7 +584,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
handleCreditsDialogClose();
}
}}
provider={SHAKESPEARE_PROVIDER}
provider={{
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
/>
)}
</>
+1 -1
View File
@@ -208,7 +208,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" />
+1 -1
View File
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
</TestApp>
);
expect(screen.getByText('🎭')).toBeInTheDocument();
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
});
+35 -69
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
@@ -9,12 +9,10 @@ import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface ProjectItemProps {
project: Project;
@@ -95,9 +93,6 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const projectsManager = useProjectsManager();
const { toast } = useToast();
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const isMobile = useIsMobile();
const navigate = useNavigate();
@@ -123,24 +118,7 @@ export function ProjectSidebar({
}
};
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
try {
// Import project from zip file
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
// Show success toast
toast({
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
});
// Navigate to the imported project
navigate(`/project/${project.id}`);
} catch (error) {
console.error('Failed to import project:', error);
throw error; // Re-throw to let the dialog handle the error display
}
};
useEffect(() => {
queryClient.invalidateQueries({ queryKey: ['projects'] });
@@ -153,34 +131,36 @@ export function ProjectSidebar({
return (
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
{/* Header with Logo */}
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<span className="text-2xl">🎭</span>
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
</Button>
</div>
)}
<div className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex px-4 h-12 border-b border-sidebar-border">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<ShakespeareLogo className="w-6 h-6" />
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
</Button>
</div>
)}
</div>
</div>
</div>
@@ -211,13 +191,6 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setIsZipDialogOpen(true)}
className="flex items-center gap-2 w-full"
>
<FileArchive className="h-4 w-4" />
Import ZIP File
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -258,8 +231,8 @@ export function ProjectSidebar({
</div>
{/* Settings and Help at Bottom */}
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<div className="flex items-center gap-2">
<div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe">
<div className="p-2 flex items-center gap-2">
<Button
variant="ghost"
size="sm"
@@ -280,13 +253,6 @@ export function ProjectSidebar({
</Button>
</div>
</div>
{/* ZIP Import Dialog */}
<ZipImportDialog
onImport={handleImportZip}
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
</div>
);
}
+80
View File
@@ -0,0 +1,80 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { Quilly } from './Quilly';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
// Mock all required hooks and components
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
settings: {
providers: []
}
})
}));
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: null
})
}));
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
// Mock CreditsDialog to avoid NostrProvider dependency
vi.mock('./CreditsDialog', () => ({
CreditsDialog: () => null
}));
describe('Quilly', () => {
const defaultProps = {
error: new Error('Generic error'),
onDismiss: vi.fn(),
onNewChat: vi.fn(),
onOpenModelSelector: vi.fn(),
providerModel: 'test/model'
};
it('renders generic error message', () => {
render(<Quilly {...defaultProps} />);
expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument();
});
it('renders correctly for malformed tool call errors', () => {
const error = new MalformedToolCallError(
'The AI provider sent an incomplete response.',
'call_abc123',
'test/model'
);
render(
<Quilly
{...defaultProps}
error={error}
/>
);
expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument();
expect(screen.getByText(/Change model/)).toBeInTheDocument();
});
it('renders correctly for console errors', () => {
const error = new ProjectPreviewConsoleError(
'Console error',
[]
);
render(
<Quilly
{...defaultProps}
error={error}
/>
);
expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument();
expect(screen.getByText(/Help fix errors/)).toBeInTheDocument();
});
});
+121 -36
View File
@@ -1,4 +1,4 @@
import OpenAI from 'openai';
import { APIError } from 'openai';
import { useNavigate } from 'react-router-dom';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -7,113 +7,190 @@ import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog';
import { ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useState } from 'react';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
export interface QuillyProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
onTryAgain?: () => void;
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
providerModel: string;
}
interface ErrorBody {
message: string;
action?: {
actions?: Array<{
label: string;
onClick: () => void;
};
}>;
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
const { provider } = parseProviderModel(providerModel, settings.providers);
const credits = useAICredits(provider);
// Handle empty provider model gracefully
let provider;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error): ErrorBody => {
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
action: {
actions: [{
label: 'Help fix errors',
onClick: () => {
onRequestConsoleErrorHelp?.(error);
onDismiss();
},
},
}],
};
}
if (error instanceof MalformedToolCallError) {
return {
message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.',
actions: [{
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
}
if (error instanceof EmptyMessageError) {
return {
message: 'The AI generated an empty response. This may be due to a provider issue or model configuration problem. Try generating again, or switch to a different model.',
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [{
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
}
// Handle OpenAI API errors with specific error codes
if (error instanceof OpenAI.APIError) {
switch (error.code) {
case 'invalid_api_key':
case 'invalid_request_error':
if (error instanceof APIError) {
switch (true) {
case error.code ==='invalid_api_key':
case error.code === 'invalid_request_error':
return {
message: 'Authentication error: Please check your API key in AI settings.',
action: {
actions: [{
label: 'Check API key',
onClick: () => navigate('/settings/ai'),
}
}],
};
case 'insufficient_quota': {
case error.code === 'insufficient_quota': {
if (credits.data) {
return {
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
action: {
actions: [{
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}
}],
};
} else {
return {
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
action: {
actions: [{
label: 'Check AI settings',
onClick: () => navigate('/settings/ai'),
}
}],
};
}
}
case 'rate_limit_exceeded':
case error.code === 'rate_limit_exceeded':
return {
message: 'Rate limit exceeded. Please wait a moment before trying again.',
actions: [],
};
case 'model_not_found':
case error.code === 'model_not_found':
return {
message: 'The selected AI model is not available. Please choose a different model.',
action: {
actions: [{
label: 'Choose model',
onClick: onOpenModelSelector,
},
}],
};
case 'context_length_exceeded':
case error.code === 'context_length_exceeded':
return {
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
action: {
actions: [{
label: 'New chat',
onClick: onNewChat,
},
}, {
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
case 'server_error':
case 'service_unavailable':
case error.status === 403:
return {
message: `It seems your API key has been used up. Check your API provider's settings, or try a different API key or different provider/model combo:`,
actions: [{
label: 'Check API settings',
onClick: () => navigate('/settings/ai'),
}, {
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
case error.status === 400:
return {
message: 'The AI provider did not understand the message / data it got. If it persists, try stating a new conversation or using a different model.',
actions: [{
label: 'New chat',
onClick: onNewChat,
}, {
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
case error.status === 422:
return {
message: 'Request rejected by AI provider. Try a different model.',
actions: [{
label: 'Choose model',
onClick: onOpenModelSelector,
}],
};
case error.code === 'server_error':
case error.code === 'service_unavailable':
return {
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
actions: [],
};
default:
return {
message: `AI service error: ${error.message}`,
actions: [],
};
}
}
@@ -123,10 +200,11 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
actions: [],
};
};
const { message, action } = renderBody(error);
const { message, actions = [] } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
@@ -139,11 +217,18 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
</h4>
<p className="text-sm text-muted-foreground">
{message}
{' '}
{action && (
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
{actions.length > 0 && (
<>
{' '}
{actions.map((action, i) => (
<span key={action.label}>
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
{i < actions.length - 1 && <> or </>}
</span>
))}
</>
)}
</p>
</div>
+4 -2
View File
@@ -5,6 +5,7 @@ import { useFS } from '@/hooks/useFS';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
interface SessionManagerProviderProps {
children: ReactNode;
@@ -18,12 +19,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user, metadata } = useCurrentUser();
const { config } = useAppContext();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
}, [fs, settings, models, user, metadata]);
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy);
}, [fs, settings, models, user, metadata, config.corsProxy]);
// Cleanup on unmount
useEffect(() => {
+6 -67
View File
@@ -1,76 +1,15 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
import { Menu } from 'lucide-react';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type Project } from '@/lib/ProjectsManager';
import { useCallback } from 'react';
import { cn } from '@/lib/utils';
interface SettingsItem {
id: string;
title: string;
description: string;
icon: React.ComponentType<{ className?: string }>;
href: string;
}
// Define settings items as a function to get fresh translations
const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
{
id: 'ai',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
},
{
id: 'git',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'data',
title: t('dataSettings'),
description: t('dataSettingsDescription'),
icon: Database,
href: '/settings/data',
},
{
id: 'email',
title: t('emailUpdates'),
description: t('emailUpdatesDescription'),
icon: Mail,
href: '/settings/email',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
import { getSettingsItems } from '@/lib/settingsItems';
export function SettingsLayout() {
const { t } = useTranslation();
@@ -127,10 +66,10 @@ export function SettingsLayout() {
if (isMobile) {
return (
<div className="min-h-dvh bg-background">
<div className="min-h-dvh pb-safe bg-background">
{/* Mobile Header */}
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
<header className="pt-safe bg-background">
<div className="flex items-center space-x-2 h-12 border-b px-4 py-3">
<Button
variant="ghost"
size="sm"
+249
View File
@@ -0,0 +1,249 @@
import { useState, useCallback, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
providerModel: string;
onProviderModelChange: (model: string) => void;
onSend: (input: string, files: File[]) => void;
onStop: () => void;
onFocus: () => void;
onFirstInteraction: () => void;
isModelSelectorOpen: boolean;
onModelSelectorOpenChange: (open: boolean) => void;
contextUsagePercentage: number;
currentModelContextLength?: number;
lastInputTokens?: number;
totalCost: number;
isDragOver: boolean;
onDragEnter: (e: React.DragEvent) => void;
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
}
export const ChatInput = memo(function ChatInput({
isLoading,
isConfigured,
providerModel,
onProviderModelChange,
onSend,
onStop,
onFocus,
onFirstInteraction,
isModelSelectorOpen,
onModelSelectorOpenChange,
contextUsagePercentage,
currentModelContextLength,
lastInputTokens,
totalCost,
isDragOver,
onDragEnter,
onDragOver,
onDragLeave,
onDrop,
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
}, []);
const handleFileRemove = useCallback((fileToRemove: File) => {
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
}, []);
const handleSend = useCallback(() => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
if (!isConfigured || !providerModel.trim()) return;
const currentInput = input;
const currentFiles = [...attachedFiles];
setInput('');
setAttachedFiles([]);
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
const handlePaste = useCallback(async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Add to attached files
setAttachedFiles(prev => [...prev, namedFile]);
}
break; // Only handle the first image found
}
}
}, []);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
return (
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
multiple={true}
/>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModelContextLength && lastInputTokens && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModelContextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */}
{totalCost >= 0.01 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
${totalCost.toFixed(2)}
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={onProviderModelChange}
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={onModelSelectorOpenChange}
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={onStop}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
onMouseDown={onFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
)}
</div>
</div>
</div>
</div>
);
});
+136 -270
View File
@@ -2,20 +2,16 @@ import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo,
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { Loader2, ChevronDown } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useKeepAlive } from '@/hooks/useKeepAlive';
import { useAppContext } from '@/hooks/useAppContext';
import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { ModelSelector } from '@/components/ModelSelector';
import { AIMessageItem } from '@/components/AIMessageItem';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
@@ -35,13 +31,15 @@ import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { useConsole, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
// Clean interfaces now handled by proper hooks
@@ -52,6 +50,8 @@ interface ChatPaneProps {
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
}
export interface ChatPaneRef {
@@ -65,32 +65,25 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onLoadingChange,
isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading,
consoleError,
onDismissConsoleError,
}, ref) => {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
const { user } = useCurrentUser();
const { models } = useProviderModels();
const { config } = useAppContext();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
// Get console functionality early so it can be used in useEffect
const { messagesRef: consoleMessagesRef, addErrorListener, removeErrorListener } = useConsole();
// Console error handling
useEffect(() => {
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
// Only show console errors if there's no existing AI error
if (!aiError) {
setAIError(error);
}
};
addErrorListener(handleConsoleError);
return () => removeErrorListener(handleConsoleError);
}, [aiError, addErrorListener, removeErrorListener]);
// Determine which error to show - console error takes priority over AI errors
const displayError = consoleError || aiError;
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
@@ -102,27 +95,46 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
});
// State to control model selector dropdown
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
const [shouldAutostart, setShouldAutostart] = useState(false);
const autostartedRef = useRef(false);
// Memoize model selector onChange handler to prevent unnecessary re-renders
const handleModelChange = useCallback((newModel: string) => {
setProviderModel(newModel);
}, []);
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
}
}, [providerModel, settings.recentlyUsedModels]);
useEffect(() => {
const urlModel = searchParams.get('model');
const autostart = searchParams.get('autostart');
if (urlModel && !providerModel) {
setProviderModel(urlModel);
}
if (autostart === 'true') {
setShouldAutostart(true);
}
// Clear the autostart and model parameters
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
}, [providerModel, searchParams, setSearchParams])
// Reset error state when navigating between projects and switching models
useEffect(() => {
setAIError(null);
}, [projectId, providerModel]);
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
const { user } = useCurrentUser();
const { models } = useProviderModels();
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const esmUrlRef = useRef(config.esmUrl);
const customTools = useMemo(() => {
const baseTools = {
git_commit: new GitCommitTool(fs, cwd, git),
@@ -131,7 +143,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd),
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
typecheck: new TypecheckTool(fs, cwd),
nostr_read_nip: new NostrReadNipTool(),
nostr_fetch_event: new NostrFetchEventTool(),
@@ -141,7 +153,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
shell: new ShellTool(fs, cwd, git),
read_console_messages: new ReadConsoleMessagesTool(() => consoleMessagesRef.current),
read_console_messages: new ReadConsoleMessagesTool(),
};
// Add deploy tool only if user is logged in
@@ -153,7 +165,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, git, cwd, user, projectId, consoleMessagesRef]);
}, [fs, git, cwd, user, projectId]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
@@ -171,7 +183,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
artist: `Working on ${projectId}...`,
artwork: [
{
src: '/favicon.png',
src: '/shakespeare-512x512.png',
sizes: '512x512',
type: 'image/png'
}
@@ -194,6 +206,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isLoading: internalIsLoading,
totalCost,
lastInputTokens,
addMessage,
sendMessage,
startGeneration,
stopGeneration,
@@ -207,9 +220,42 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
});
// Handle console error help requests
const handleConsoleErrorHelp = useCallback(() => {
sendMessage('Read the console messages and fix any errors present.', providerModel);
}, [sendMessage, providerModel]);
const handleConsoleErrorHelp = useCallback(async () => {
const tool = new ReadConsoleMessagesTool();
const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`;
await addMessage({
role: 'assistant',
content: 'Let me take a look at the console messages to help diagnose the issue.',
tool_calls: [
{
id: toolCallId,
type: 'function',
function: {
name: 'read_console_messages',
arguments: '{}',
}
}
]
});
await addMessage({
role: 'tool',
content: await tool.execute({ filter: 'error' }),
tool_call_id: toolCallId,
});
await startGeneration(providerModel);
}, [addMessage, providerModel, startGeneration]);
// Handle error dismissal
const handleErrorDismiss = useCallback(() => {
if (consoleError && onDismissConsoleError) {
onDismissConsoleError();
} else {
setAIError(null);
}
}, [consoleError, onDismissConsoleError]);
// Use external loading state if provided, otherwise use internal state
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
@@ -257,41 +303,24 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setIsModelSelectorOpen(true);
}, []);
// Scroll to bottom when AI error occurs
// Scroll to bottom when any error occurs (AI error or console error)
useEffect(() => {
scrollToBottom();
}, [aiError, scrollToBottom]);
if (displayError) {
scrollToBottom();
}
}, [displayError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
if (autostartedRef.current) return;
const autostart = searchParams.get('autostart');
const urlModel = searchParams.get('model');
if (autostart === 'true' && isConfigured) {
// Use model from URL if available, otherwise use current selection
const modelToUse = urlModel?.trim() || providerModel.trim();
if (modelToUse) {
// Update provider model if it came from URL
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
setProviderModel(urlModel.trim());
}
// Clear the autostart and model parameters so they don't trigger again
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
// Start AI generation
addRecentlyUsedModel(modelToUse);
startGeneration(modelToUse);
autostartedRef.current = true;
}
if (shouldAutostart && providerModel && isConfigured) {
// Start AI generation
addRecentlyUsedModel(providerModel);
startGeneration(providerModel);
autostartedRef.current = true;
}
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
}, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]);
// Simple scroll event listener
useEffect(() => {
@@ -343,30 +372,22 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [projectId, scrolledProjects, scrollToBottom]);
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
};
const handleFileRemove = (fileToRemove: File) => {
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
};
// Drag and drop handlers
const handleDragEnter = (e: React.DragEvent) => {
const handleDragEnter = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
};
}, []);
const handleDragOver = (e: React.DragEvent) => {
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isDragOver) {
setIsDragOver(true);
}
};
}, [isDragOver]);
const handleDragLeave = (e: React.DragEvent) => {
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
@@ -378,23 +399,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
if (!container.contains(relatedTarget)) {
setIsDragOver(false);
}
};
}, []);
const handleDrop = (e: React.DragEvent) => {
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
if (isLoading || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
};
const send = useCallback(async (input: string, attachedFiles: File[]) => {
const handleSend = useCallback(async (input: string, attachedFiles: File[]) => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
// If AI is not configured, show onboarding dialog
@@ -444,9 +457,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
});
}
setInput('');
setAttachedFiles([]);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
@@ -455,64 +465,24 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
await send(input, attachedFiles);
}, [input, attachedFiles, send]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const handlePaste = async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Add to attached files
setAttachedFiles(prev => [...prev, namedFile]);
}
break; // Only handle the first image found
}
}
};
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = () => {
const handleTextareaFocus = useCallback(() => {
if (!isConfigured) {
setShowOnboarding(true);
}
if (onFirstInteraction) {
onFirstInteraction();
}
};
}, [isConfigured, onFirstInteraction]);
// Handle first user interaction to enable audio context
const handleFirstInteraction = () => {
const handleFirstInteraction = useCallback(() => {
// This will be handled automatically by the useKeepAlive hook
// when isLoading becomes true after user interaction
if (onFirstInteraction) {
onFirstInteraction();
}
};
}, [onFirstInteraction]);
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
@@ -530,7 +500,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
{messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]">
<div className="text-center space-y-4 max-w-md mx-auto">
<div className="text-6xl mb-6">🎭</div>
<div className="mb-6">
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div>
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('welcomeToShakespeare')}
@@ -613,13 +585,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
{/* AI Error Alert */}
{aiError && (
{/* Error Alert (Console or AI) - Don't show while assistant is loading */}
{displayError && !isLoading && (
<Quilly
error={aiError}
onDismiss={() => setAIError(null)}
error={displayError}
onDismiss={handleErrorDismiss}
onNewChat={onNewChat}
onOpenModelSelector={openModelSelector}
onTryAgain={() => startGeneration(providerModel)}
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
providerModel={providerModel}
/>
@@ -641,134 +614,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleTextareaFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
multiple={true}
/>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModel.contextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */}
{totalCost >= 0.01 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
${totalCost.toFixed(2)}
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
)}
</div>
</div>
</div>
</div>
<ChatInput
isLoading={isLoading}
isConfigured={isConfigured}
providerModel={providerModel}
onProviderModelChange={handleModelChange}
onSend={handleSend}
onStop={stopGeneration}
onFocus={handleTextareaFocus}
onFirstInteraction={handleFirstInteraction}
isModelSelectorOpen={isModelSelectorOpen}
onModelSelectorOpenChange={setIsModelSelectorOpen}
contextUsagePercentage={contextUsagePercentage}
currentModelContextLength={currentModel?.contextLength}
lastInputTokens={lastInputTokens}
totalCost={totalCost}
isDragOver={isDragOver}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
/>
{/* Onboarding Dialog */}
<OnboardingDialog
+1 -1
View File
@@ -30,7 +30,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
const [gitignoreFilter, setGitignoreFilter] = useState<{
isIgnored: (path: string) => boolean;
shouldShow: (path: string) => boolean;
} | null>(null);
} | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [isSearching, setIsSearching] = useState(false);
const { fs } = useFS();
+215 -144
View File
@@ -3,12 +3,13 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useConsole, type ConsoleMessage } from '@/contexts/ConsoleContext';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -27,10 +28,9 @@ import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
// Get iframe domain from environment variable
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
import { useAppContext } from '@/hooks/useAppContext';
interface PreviewPaneProps {
projectId: string;
@@ -71,12 +71,15 @@ interface JSONRPCResponse {
id: number;
}
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer');
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [currentPath, setCurrentPath] = useState('/');
@@ -87,7 +90,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
const { addMessage: addConsoleMessage, messages: consoleMessages } = useConsole();
// Use console error state from provider
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
@@ -179,26 +184,26 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`;
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
}
}, 10);
}
}, [projectId]);
}, [projectId, previewDomain]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
}, [projectId, previewDomain]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
}, [projectId, previewDomain]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
@@ -221,7 +226,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Log to parent console for debugging with appropriate level
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, [addConsoleMessage]);
}, []);
const handleUpdateNavigationState = useCallback((message: {
jsonrpc: '2.0';
@@ -261,10 +266,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
params: params || {},
id: Date.now()
};
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
}, [projectId, previewDomain]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
@@ -311,7 +316,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
@@ -418,13 +423,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
id
});
}
}, [projectId, projectsManager, sendResponse, sendError]);
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
// Setup messaging protocol for iframe communication
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
@@ -443,7 +448,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
useEffect(() => {
if (selectedFile) {
@@ -452,16 +457,24 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}, [selectedFile, loadFileContent]);
// Reset selected file and navigation history when projectId changes
const prevProjectIdRef = useRef<string>();
useEffect(() => {
setSelectedFile(null);
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
// Reset navigation history and state
setCurrentPath('/');
setNavigationHistory(['/']);
setHistoryIndex(0);
}, [projectId]);
// Only clear console messages when projectId actually changes (not on initial mount)
if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) {
clearErrors();
}
prevProjectIdRef.current = projectId;
}, [projectId, clearErrors]);
useEffect(() => {
checkForBuiltProject();
@@ -495,6 +508,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
try {
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
setFileContent(content);
// Automatically trigger a rebuild after saving a file
if (isPreviewable) {
console.log('File saved, triggering rebuild...');
handleBuildProject();
}
} catch (error) {
console.error('Failed to save file:', error);
}
@@ -504,6 +523,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const messages = isOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
@@ -514,9 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
};
// consoleMessages is now available from the hook
const messageCount = consoleMessages.length;
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
const messageCount = messages.length;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
@@ -524,10 +543,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
className="h-8 w-8 p-0 relative"
>
<Bug className="h-4 w-4" />
{hasErrors && (
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
@@ -547,7 +566,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
consoleMessages.map((msg, index) => (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
@@ -559,9 +578,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}>
{msg.message}
</div>
@@ -632,7 +651,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
disabled={isAnyLoading}
className="gap-2"
>
<CloudUpload className="h-4 w-4" />
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
</DropdownMenuContent>
@@ -645,103 +664,133 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Tabs value={activeTab} className="h-full">
{isPreviewable && (
<TabsContent value="preview" className="h-full mt-0">
<div className="h-full w-full flex flex-col relative">
{/* Always show browser address bar */}
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
<div className="flex items-center">
{(!isMobile && onToggleView && isPreviewable) && (
<div className="h-full w-full flex flex-col relative">
{/* Always show browser address bar */}
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
<div className="flex items-center">
{(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
<Menu />
</div>
)}
/>
</div>
{/* Content area */}
<div className="flex-1">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
onClick={handleBuildProject}
disabled={isBuildLoading}
variant="outline"
className="gap-2"
>
<Code className="h-4 w-4" />
{isBuildLoading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button>
)}
<ConsoleDropdown />
<Menu />
</div>
</div>
)}
/>
</div>
</div>
{/* Content area */}
<div className="flex-1">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button
onClick={handleBuildProject}
disabled={isBuildLoading}
variant="outline"
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button>
{/* Build loading overlay */}
{isBuildLoading && (
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm font-medium">Building project...</span>
</div>
</div>
)}
</div>
{/* Build loading overlay */}
{isBuildLoading && (
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm font-medium">Building project...</span>
</div>
</div>
)}
</div>
</TabsContent>
</TabsContent>
)}
<TabsContent value="code" className="h-full mt-0">
{isMobile ? (
<div className="h-full flex flex-col">
<div className="h-full flex flex-col min-h-0">
{mobileCodeView === 'explorer' ? (
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
<div className="flex-1 relative min-h-0">
<ScrollArea className="h-full">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</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>
</ScrollArea>
<div className="flex-1 min-h-0">
<TerminalComponent projectId={projectId} />
</div>
</>
) : (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
@@ -804,50 +853,73 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{t('backToPreview')}
</Button>
<div className="flex-1" />
<GitStatusIndicator projectId={projectId} />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
</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" />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
)}
<div className="flex-1 flex min-h-0">
<div className="w-1/3 border-r flex flex-col">
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
{desktopCodeView === 'terminal' ? (
<div className="flex-1">
<TerminalComponent projectId={projectId} />
</div>
) : (
<>
<div className="w-1/3 border-r flex flex-col">
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
</div>
</ScrollArea>
</div>
<div className="flex-1">
{selectedFile ? (
<FileEditor
filePath={selectedFile}
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
{t('selectFileFromExplorer')}
</p>
</div>
<div className="flex-1">
{selectedFile ? (
<FileEditor
filePath={selectedFile}
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
{t('selectFileFromExplorer')}
</p>
</div>
</div>
)}
</div>
)}
</div>
</>
)}
</div>
</div>
)}
@@ -861,7 +933,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
onFirstInteraction={onFirstInteraction}
/>
)}
</div>
+13
View File
@@ -0,0 +1,13 @@
export interface ShakespeareLogoProps {
className?: string;
}
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
return (
<img
src="/shakespeare.svg"
alt="Shakespeare"
className={className}
/>
);
}
+240
View File
@@ -0,0 +1,240 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { Copy } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ShellTool } from '@/lib/tools/ShellTool';
import { useFS } from '@/hooks/useFS';
import { useGit } from '@/hooks/useGit';
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
interface TerminalProps {
projectId: string;
className?: string;
}
interface TerminalLine {
id: string;
type: 'input' | 'output' | 'error';
content: string;
timestamp: Date;
}
export function Terminal({ projectId, className }: TerminalProps) {
const [lines, setLines] = useState<TerminalLine[]>([]);
const [currentInput, setCurrentInput] = useState('');
const [isExecuting, setIsExecuting] = useState(false);
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState(-1);
const inputRef = useRef<HTMLInputElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const shellToolRef = useRef<ShellTool | null>(null);
const { fs } = useFS();
const { git } = useGit();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
// Add welcome message
setLines([{
id: Date.now().toString(),
type: 'output',
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
timestamp: new Date()
}]);
}, [projectId, fs, git]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [lines, isExecuting]);
// Focus input when component mounts
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
// Refocus input after command execution
useEffect(() => {
if (!isExecuting && inputRef.current) {
inputRef.current.focus();
}
}, [isExecuting]);
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
const newLine: TerminalLine = {
id: Date.now().toString() + Math.random(),
type,
content,
timestamp: new Date()
};
setLines(prev => [...prev, newLine]);
}, []);
const executeCommand = useCallback(async (command: string) => {
if (!shellToolRef.current || !command.trim()) return;
// Add command to history
if (command.trim() && !commandHistory.includes(command.trim())) {
setCommandHistory(prev => [...prev, command.trim()]);
}
setHistoryIndex(-1);
// Add input line
addLine('input', command);
setIsExecuting(true);
try {
// 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 if (command.trim() === 'clear') {
setLines([]);
} else {
const result = await shellToolRef.current.execute({ command });
// Add output
if (result && result.trim()) {
addLine('output', result);
}
}
} catch (error) {
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
if (currentInput.trim() && !isExecuting) {
executeCommand(currentInput);
setCurrentInput('');
}
}, [currentInput, isExecuting, executeCommand]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (commandHistory.length > 0) {
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (historyIndex >= 0) {
const newIndex = historyIndex + 1;
if (newIndex >= commandHistory.length) {
setHistoryIndex(-1);
setCurrentInput('');
} else {
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
}
} else if (e.key === 'Tab') {
e.preventDefault();
// Basic tab completion could be added here
}
}, [commandHistory, historyIndex]);
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);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
}, []);
// Focus input when clicking anywhere in the terminal
const handleTerminalClick = useCallback(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
<div className={cn("h-full flex flex-col bg-black text-slate-300 font-mono text-sm", className)}>
{/* Terminal Content */}
<div className="flex-1 flex flex-col min-h-0" onClick={handleTerminalClick}>
<ScrollArea className="flex-1" ref={scrollRef}>
<div className="p-2 space-y-1">
{lines.map((line) => (
<div
key={line.id}
className={cn(
"group relative",
line.type === 'input' && "text-white",
line.type === 'error' && "text-red-400",
line.type === 'output' && "text-slate-300"
)}
>
<pre className="whitespace-pre-wrap break-words font-mono leading-relaxed">
{line.type === 'input' ? (
<span className="text-purple-400 font-mono whitespace-nowrap">
${' '}
</span>
) : null}
{containsAnsiCodes(line.content)
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
: line.content}
</pre>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
copyToClipboard(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"
>
<Copy className="h-2 w-2" />
</Button>
</div>
))}
{/* Current Command Input - inline with content */}
{!isExecuting && (
<div className="flex items-center gap-2">
<span className="text-purple-400 font-mono whitespace-nowrap">
$
</span>
<form onSubmit={handleSubmit} className="flex-1 relative">
<input
ref={inputRef}
type="text"
value={currentInput}
onChange={(e) => setCurrentInput(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isExecuting}
className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed"
placeholder=""
autoComplete="off"
spellCheck="false"
autoCapitalize="off"
autoCorrect="off"
/>
</form>
</div>
)}
</div>
</ScrollArea>
</div>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { Terminal } from './Terminal';
/**
* A test component to verify ANSI color code rendering in the terminal
*/
export function TerminalTest() {
return (
<div className="h-[500px] w-full">
<Terminal projectId="test" />
</div>
);
}
+154
View File
@@ -0,0 +1,154 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
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 } }) => {
if (!open) return null;
return (
<div data-testid="add-provider-dialog">
<div>Provider ID: {provider.id}</div>
<div>Base URL: {provider.baseURL}</div>
{provider.apiKey && <div>API Key: {provider.apiKey}</div>}
{provider.nostr && <div>Nostr: true</div>}
{provider.proxy && <div>Proxy: true</div>}
</div>
);
},
}));
describe('URLFragmentHandler', () => {
const originalHash = window.location.hash;
beforeEach(() => {
// Clear hash before each test
window.location.hash = '';
});
afterEach(() => {
// Restore original hash
window.location.hash = originalHash;
});
it('does not render dialog when no hash is present', () => {
window.location.hash = '';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
expect(screen.queryByTestId('add-provider-dialog')).not.toBeInTheDocument();
});
it('does not render dialog when hash does not contain provider params', () => {
window.location.hash = '#some-random-hash';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
expect(screen.queryByTestId('add-provider-dialog')).not.toBeInTheDocument();
});
it('parses provider from URL fragment and displays dialog', async () => {
window.location.hash = '#id=openrouter&baseURL=https://openrouter.ai/api/v1';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
await waitFor(() => {
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
});
expect(screen.getByText('Provider ID: openrouter')).toBeInTheDocument();
expect(screen.getByText('Base URL: https://openrouter.ai/api/v1')).toBeInTheDocument();
});
it('parses API key from URL fragment', async () => {
window.location.hash = '#id=openrouter&baseURL=https://openrouter.ai/api/v1&apiKey=sk-test-123';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
await waitFor(() => {
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
});
expect(screen.getByText('API Key: sk-test-123')).toBeInTheDocument();
});
it('parses nostr flag from URL fragment', async () => {
window.location.hash = '#id=shakespeare&baseURL=https://ai.shakespeare.diy/v1&nostr=true';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
await waitFor(() => {
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
});
expect(screen.getByText('Nostr: true')).toBeInTheDocument();
});
it('parses proxy flag from URL fragment', async () => {
window.location.hash = '#id=custom&baseURL=https://api.custom.com/v1&proxy=true';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
await waitFor(() => {
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
});
expect(screen.getByText('Proxy: true')).toBeInTheDocument();
});
it('parses all parameters from complete URL', async () => {
window.location.hash = '#id=openrouter&baseURL=https://openrouter.ai/api&apiKey=sk-b7719bfc06f04bb29086f380969c76eb&nostr=false&proxy=true';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
await waitFor(() => {
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
});
expect(screen.getByText('Provider ID: openrouter')).toBeInTheDocument();
expect(screen.getByText('Base URL: https://openrouter.ai/api')).toBeInTheDocument();
expect(screen.getByText('API Key: sk-b7719bfc06f04bb29086f380969c76eb')).toBeInTheDocument();
expect(screen.getByText('Proxy: true')).toBeInTheDocument();
});
it('requires both id and baseURL to show dialog', () => {
window.location.hash = '#id=openrouter';
render(
<TestApp>
<URLFragmentHandler />
</TestApp>
);
expect(screen.queryByTestId('add-provider-dialog')).not.toBeInTheDocument();
});
});
+80
View File
@@ -0,0 +1,80 @@
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
/**
* Component that handles URL fragments for adding AI providers
* Example URL: https://shakespeare.diy/#id=openrouter&baseURL=https://openrouter.ai/api&apiKey=sk-123
*/
export function URLFragmentHandler() {
const location = useLocation();
const navigate = useNavigate();
const [providerFromURL, setProviderFromURL] = useState<AIProvider | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
useEffect(() => {
// Only process if there's a hash
if (!location.hash) return;
// Remove the leading '#' and parse as URLSearchParams
const fragment = location.hash.slice(1);
const params = new URLSearchParams(fragment);
// Check if we have the required parameters for a provider
const id = params.get('id');
const baseURL = params.get('baseURL');
if (!id || !baseURL) {
// Not a provider URL, ignore
return;
}
// Build the provider object
const provider: AIProvider = {
id,
baseURL,
};
// Add optional parameters
const apiKey = params.get('apiKey');
if (apiKey) {
provider.apiKey = apiKey;
}
const nostr = params.get('nostr');
if (nostr === 'true') {
provider.nostr = true;
}
const proxy = params.get('proxy');
if (proxy === 'true') {
provider.proxy = true;
}
// Set the provider and open dialog
setProviderFromURL(provider);
setDialogOpen(true);
// Remove the fragment from the URL immediately
// Preserve the current path and search params
navigate(location.pathname + location.search, { replace: true });
}, [location, navigate]);
const handleDialogClose = () => {
setDialogOpen(false);
setProviderFromURL(null);
};
if (!providerFromURL) {
return null;
}
return (
<AddProviderDialog
open={dialogOpen}
onOpenChange={handleDialogClose}
provider={providerFromURL}
/>
);
}
+144 -144
View File
@@ -41,29 +41,29 @@ const AddWalletContent = forwardRef<HTMLDivElement, {
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
@@ -77,132 +77,132 @@ const WalletContent = forwardRef<HTMLDivElement, {
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
);
})}
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
</>
)}
</div>
));
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) {
+3 -7
View File
@@ -199,17 +199,13 @@ This reverts the codebase back to the state at commit ${targetCommit.oid.substri
Reverted ${commitsToRevert.length} commit(s):
${commitsToRevert.map(c => {
const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine;
return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`;
}).join('\n')}`;
const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine;
return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`;
}).join('\n')}`;
await git.commit({
dir: projectPath,
message: revertMessage,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
toast({
+4 -4
View File
@@ -186,9 +186,9 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* Prominent Sign Up Section */}
@@ -370,7 +370,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</div>
</DialogContent>
</Dialog>
);
};
);
};
export default LoginDialog;
+35 -35
View File
@@ -505,11 +505,11 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
@@ -519,39 +519,39 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
</div>
<div className='text-xs text-muted-foreground'>
Save as secret-key.txt file
</div>
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
)}
</div>
</Button>
</CardContent>
</Card>
{/* Copy Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'copied'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
@@ -561,20 +561,20 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'copied'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'copied' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Copy className='w-4 h-4 text-primary' />
)}
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Copy className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
<div className='font-medium text-sm'>
Copy to Clipboard
</div>
<div className='text-xs text-muted-foreground'>
</div>
<div className='text-xs text-muted-foreground'>
Save to password manager
</div>
<div className='text-[.7rem] text-muted-foreground'>
@@ -582,10 +582,10 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
</div>
</div>
{keySecured === 'copied' && (
<div className='text-xs font-medium text-green-600'>
<div className='text-xs font-medium text-green-600'>
✓ Copied
</div>
)}
</div>
)}
</div>
</Button>
</CardContent>
+88 -24
View File
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Cloud } from 'lucide-react';
import React, { useState, useEffect, useRef } from 'react';
import { Cloud, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -32,6 +32,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
}) => {
// Removed step state - we only have one step now
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
@@ -39,7 +40,9 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
nsec?: string;
bunker?: string;
extension?: string;
file?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions();
@@ -47,10 +50,15 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
useEffect(() => {
if (isOpen) {
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setActiveTab('nsec');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [isOpen]);
@@ -86,20 +94,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
setIsLoading(true);
setErrors({});
setTimeout(() => {
try {
login.nsec(nsec);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
@@ -131,6 +126,52 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
@@ -202,14 +243,37 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
)}
</div>
<Button
size="lg"
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
className="w-full"
>
{isLoading ? 'Verifying...' : 'Add Key'}
</Button>
<div className="flex space-x-2">
<Button
size="lg"
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Add Key'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</div>
)}
+193
View File
@@ -0,0 +1,193 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface NetlifySite {
id: string;
site_id: string;
name: string;
url: string;
admin_url: string;
}
interface NetlifyDeployFormProps {
apiKey: string;
baseURL?: string;
projectId: string;
projectName?: string;
savedSiteId?: string;
onSiteChange: (siteId: string, siteName: string) => void;
corsProxy?: string;
}
export function NetlifyDeployForm({
apiKey,
baseURL = 'https://api.netlify.com/api/v1',
projectId,
projectName,
savedSiteId,
onSiteChange,
corsProxy,
}: NetlifyDeployFormProps) {
const [sites, setSites] = useState<NetlifySite[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedSiteId, setSelectedSiteId] = useState<string>('');
const [newSiteName, setNewSiteName] = useState(projectName || projectId);
const fetchSites = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const url = `${baseURL}/sites`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: {
'Authorization': `Bearer ${apiKey}`,
},
});
if (!response.ok) {
throw new Error(`Failed to fetch sites: ${response.status} ${response.statusText}`);
}
const data: NetlifySite[] = await response.json();
setSites(data);
// If there's a saved site ID and it exists in the list, select it
// Otherwise leave it empty (showing placeholder)
if (savedSiteId && data.some(s => s.id === savedSiteId)) {
setSelectedSiteId(savedSiteId);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch sites');
} finally {
setIsLoading(false);
}
}, [apiKey, baseURL, savedSiteId, corsProxy]);
useEffect(() => {
fetchSites();
}, [fetchSites]);
// Update newSiteName when switching to "new" if it's empty
useEffect(() => {
if (selectedSiteId === 'new' && !newSiteName) {
setNewSiteName(projectName || projectId);
}
}, [selectedSiteId, newSiteName, projectName, projectId]);
useEffect(() => {
if (selectedSiteId === '') {
// No selection yet - don't call onSiteChange
return;
} else if (selectedSiteId === 'new') {
onSiteChange('', newSiteName);
} else {
const site = sites.find(s => s.id === selectedSiteId);
if (site) {
onSiteChange(site.id, site.name);
}
}
}, [selectedSiteId, newSiteName, sites, onSiteChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Site</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedSite = sites.find(s => s.id === selectedSiteId);
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="netlify-site">Select Site</Label>
<Select value={selectedSiteId} onValueChange={setSelectedSiteId}>
<SelectTrigger id="netlify-site">
<SelectValue placeholder="Select a site or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new site
</div>
</SelectItem>
{sites.map((site) => (
<SelectItem key={site.id} value={site.id}>
{site.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedSiteId === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-site-name">New Site Name</Label>
<Input
id="new-site-name"
value={newSiteName}
onChange={(e) => setNewSiteName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
Domain: <span className="font-mono">{newSiteName || projectId}.netlify.app</span>
</p>
<p className="text-xs text-muted-foreground">
A new site will be created when you deploy
</p>
</div>
) : selectedSite ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedSite.name}</p>
<p className="text-xs text-muted-foreground font-mono">{selectedSite.url}</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(selectedSite.admin_url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will update this existing site
</p>
</div>
) : null}
</div>
);
}
+109
View File
@@ -0,0 +1,109 @@
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { nip19 } from 'nostr-tools';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { PasswordInput } from '@/components/ui/password-input';
import { RefreshCw } from 'lucide-react';
interface NsiteDeployFormProps {
gateway: string;
savedNsec?: string;
onNsecChange: (nsec: string) => void;
}
export function NsiteDeployForm({
gateway,
savedNsec,
onNsecChange,
}: NsiteDeployFormProps) {
const [nsec, setNsec] = useState(savedNsec || '');
const [npub, setNpub] = useState('');
const initialized = useRef(false);
// Initialize nsec on mount
useEffect(() => {
if (!initialized.current) {
initialized.current = true;
if (savedNsec) {
// If we have a saved nsec, notify parent immediately
onNsecChange(savedNsec);
} else if (!nsec) {
// Generate a new nsec if none exists
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
}
}
}, [savedNsec, nsec, onNsecChange]);
// Update npub when nsec changes
useEffect(() => {
if (nsec) {
try {
const decoded = nip19.decode(nsec);
if (decoded.type === 'nsec') {
const pk = getPublicKey(decoded.data);
const npubEncoded = nip19.npubEncode(pk);
setNpub(npubEncoded);
}
} catch {
setNpub('');
}
}
}, [nsec]);
const handleNsecChange = (value: string) => {
setNsec(value);
onNsecChange(value);
};
const handleGenerateNew = () => {
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
};
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Site URL</Label>
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
{fullDomain}
</p>
<p className="text-xs text-muted-foreground">
Each site has a unique Nostr keypair
</p>
</div>
<div className="space-y-2">
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
<div className="flex gap-2">
<PasswordInput
id="nsite-nsec"
value={nsec}
onChange={(e) => handleNsecChange(e.target.value)}
placeholder="nsec1..."
className="flex-1"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleGenerateNew}
title="Generate new key"
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Keep this private key secure. It's used to sign site metadata.
</p>
</div>
</div>
);
}
@@ -0,0 +1,40 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface ShakespeareDeployFormProps {
host?: string;
projectId: string;
onSubdomainChange: (subdomain: string) => void;
}
export function ShakespeareDeployForm({
host = 'shakespeare.wtf',
projectId,
onSubdomainChange,
}: ShakespeareDeployFormProps) {
const [subdomain, setSubdomain] = useState(projectId);
useEffect(() => {
onSubdomainChange(subdomain);
}, [subdomain, onSubdomainChange]);
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="shakespeare-subdomain">Subdomain</Label>
<Input
id="shakespeare-subdomain"
value={subdomain}
onChange={(e) => setSubdomain(e.target.value)}
placeholder={projectId}
/>
<p className="text-xs text-muted-foreground">
Will deploy to: <span className="font-mono">{fullDomain}</span>
</p>
</div>
</div>
);
}
@@ -0,0 +1,55 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface VercelDeployFormProps {
projectId: string;
projectName?: string;
savedTeamId?: string;
savedProjectName?: string;
onConfigChange: (projectName: string, teamId: string) => void;
}
export function VercelDeployForm({
projectId,
projectName: initialProjectName,
savedTeamId,
savedProjectName,
onConfigChange,
}: VercelDeployFormProps) {
const [projectName, setProjectName] = useState(savedProjectName || initialProjectName || projectId);
const [teamId, setTeamId] = useState(savedTeamId || '');
useEffect(() => {
onConfigChange(projectName, teamId);
}, [projectName, teamId, onConfigChange]);
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="vercel-project-name">Project Name</Label>
<Input
id="vercel-project-name"
value={projectName}
onChange={(e) => setProjectName(e.target.value)}
placeholder={initialProjectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{projectName || projectId}.vercel.app</span>
</p>
</div>
<div className="space-y-2">
<Label htmlFor="vercel-team-id">Team ID (optional)</Label>
<Input
id="vercel-team-id"
value={teamId}
onChange={(e) => setTeamId(e.target.value)}
placeholder="Leave empty for personal account"
/>
<p className="text-xs text-muted-foreground">
Deploy to a team account instead of your personal account
</p>
</div>
</div>
);
}
+4
View File
@@ -0,0 +1,4 @@
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
export { NetlifyDeployForm } from './NetlifyDeployForm';
export { VercelDeployForm } from './VercelDeployForm';
export { NsiteDeployForm } from './NsiteDeployForm';
@@ -0,0 +1,569 @@
import { useState, useEffect, useCallback } 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 {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
GitBranch,
Loader2,
AlertCircle,
CheckCircle,
Plus,
X,
Megaphone,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@/hooks/useNostr';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
interface AnnounceRepositoryDialogProps {
projectId: string;
remoteUrl?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function AnnounceRepositoryDialog({
projectId,
remoteUrl,
open,
onOpenChange,
}: AnnounceRepositoryDialogProps) {
const [isOpen, setIsOpen] = useState(open ?? false);
const [repoId, setRepoId] = useState('');
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [webUrls, setWebUrls] = useState<string[]>([]);
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
const [relays, setRelays] = useState<string[]>(['wss://relay.nostr.band']);
const [earliestCommit, setEarliestCommit] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [createdNaddr, setCreatedNaddr] = useState<string | null>(null);
const [newWebUrl, setNewWebUrl] = useState('');
const [newCloneUrl, setNewCloneUrl] = useState('');
const [newRelay, setNewRelay] = useState('');
const { git } = useGit();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { toast } = useToast();
const projectPath = `/projects/${projectId}`;
useEffect(() => {
if (open !== undefined) {
setIsOpen(open);
}
}, [open]);
const parseRemoteUrl = useCallback((url: string) => {
// Extract repo ID from Nostr URL
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/[^/]+\/(.+)$/);
if (match) {
const id = match[1];
setRepoId(id);
setName(id.split('/').pop() || id);
}
}
// Add the remote URL as a clone URL
if (url && !cloneUrls.includes(url)) {
setCloneUrls([url]);
}
}, [cloneUrls]);
const getEarliestCommit = useCallback(async () => {
try {
const commits = await git.log({
dir: projectPath,
ref: 'HEAD',
});
if (commits.length > 0) {
// Get the earliest commit (last in the log)
const earliest = commits[commits.length - 1];
setEarliestCommit(earliest.oid);
}
} catch (err) {
console.warn('Failed to get earliest commit:', err);
}
}, [git, projectPath]);
useEffect(() => {
if (isOpen && remoteUrl) {
// Parse remote URL to pre-fill data
parseRemoteUrl(remoteUrl);
// Get earliest commit
getEarliestCommit();
}
}, [isOpen, remoteUrl, parseRemoteUrl, getEarliestCommit]);
const addWebUrl = () => {
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
setWebUrls([...webUrls, newWebUrl.trim()]);
setNewWebUrl('');
}
};
const removeWebUrl = (index: number) => {
setWebUrls(webUrls.filter((_, i) => i !== index));
};
const addCloneUrl = () => {
if (newCloneUrl.trim() && !cloneUrls.includes(newCloneUrl.trim())) {
setCloneUrls([...cloneUrls, newCloneUrl.trim()]);
setNewCloneUrl('');
}
};
const removeCloneUrl = (index: number) => {
setCloneUrls(cloneUrls.filter((_, i) => i !== index));
};
const addRelay = () => {
if (newRelay.trim() && !relays.includes(newRelay.trim())) {
setRelays([...relays, newRelay.trim()]);
setNewRelay('');
}
};
const removeRelay = (index: number) => {
setRelays(relays.filter((_, i) => i !== index));
};
const announceRepository = async () => {
if (!user || !user.signer) {
toast({
title: 'Authentication required',
description: 'Please log in with Nostr to announce repositories',
variant: 'destructive',
});
return;
}
if (!repoId.trim()) {
toast({
title: 'Repository ID required',
description: 'Please enter a repository identifier',
variant: 'destructive',
});
return;
}
if (cloneUrls.length === 0) {
toast({
title: 'Clone URL required',
description: 'Please add at least one clone URL',
variant: 'destructive',
});
return;
}
setIsCreating(true);
setError(null);
try {
// Build tags array per NIP-34
const tags: string[][] = [
['d', repoId.trim()], // Required: repository identifier
];
if (name.trim()) {
tags.push(['name', name.trim()]);
}
if (description.trim()) {
tags.push(['description', description.trim()]);
}
// Add web URLs
webUrls.forEach(url => {
if (url.trim()) tags.push(['web', url.trim()]);
});
// Add clone URLs (required)
cloneUrls.forEach(url => {
if (url.trim()) tags.push(['clone', url.trim()]);
});
// Add relays for patch submissions
relays.forEach(relay => {
if (relay.trim()) tags.push(['relays', relay.trim()]);
});
// Add earliest unique commit (euc) for repository identification
if (earliestCommit.trim()) {
tags.push(['r', earliestCommit.trim(), 'euc']);
}
// Create repository announcement event (kind 30617)
const repoEvent = {
kind: 30617,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
};
console.log('=== ANNOUNCING REPOSITORY ===');
console.log('Repository ID:', repoId.trim());
console.log('Owner pubkey:', user.pubkey);
console.log('Creating repository announcement event:', repoEvent);
// Sign the event
const signedEvent = await user.signer.signEvent(repoEvent);
console.log('Signed repository announcement:', signedEvent);
console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`);
// Publish to Nostr relays
await nostr.event(signedEvent);
console.log('Published repository announcement to Nostr relays');
console.log('To verify: Query for kind 30617 with authors=[' + user.pubkey + '] and #d=[' + repoId.trim() + ']');
// Create naddr for the repository
const naddr = nip19.naddrEncode({
identifier: repoId.trim(),
pubkey: user.pubkey,
kind: 30617,
relays: relays.length > 0 ? relays : undefined,
});
setCreatedNaddr(naddr);
toast({
title: 'Repository announced!',
description: 'Your repository has been announced on Nostr',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
toast({
title: 'Failed to announce repository',
description: errorMessage,
variant: 'destructive',
});
} finally {
setIsCreating(false);
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
onOpenChange?.(newOpen);
// Reset form when closing
if (!newOpen) {
setRepoId('');
setName('');
setDescription('');
setWebUrls([]);
setCloneUrls([]);
setRelays(['wss://relay.nostr.band']);
setEarliestCommit('');
setCreatedNaddr(null);
setError(null);
setNewWebUrl('');
setNewCloneUrl('');
setNewRelay('');
}
};
const copyNaddr = () => {
if (createdNaddr) {
navigator.clipboard.writeText(createdNaddr);
toast({
title: 'Copied to clipboard',
description: 'Repository address copied',
});
}
};
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" className="gap-2">
<Megaphone className="h-4 w-4" />
Announce Repository
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Megaphone className="h-5 w-5" />
Announce Repository on Nostr
</DialogTitle>
<DialogDescription>
Publish a repository announcement (NIP-34) to make it discoverable on Nostr git
clients
</DialogDescription>
</DialogHeader>
{createdNaddr ? (
// Success state
<div className="py-8 text-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
<div>
<h3 className="text-lg font-semibold mb-2">Repository Announced!</h3>
<p className="text-muted-foreground">
Your repository is now discoverable on Nostr git clients
</p>
</div>
<div className="bg-muted/30 rounded-lg p-4 space-y-2">
<Label>Repository Address (naddr)</Label>
<div className="flex gap-2">
<Input
value={createdNaddr}
readOnly
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={copyNaddr}
>
<Plus className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Share this address with others to let them find your repository
</p>
</div>
</div>
) : (
// Form
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 pr-4">
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Repository ID */}
<div className="space-y-2">
<Label htmlFor="repo-id">Repository ID *</Label>
<Input
id="repo-id"
placeholder="e.g., my-project or username/repo-name"
value={repoId}
onChange={(e) => setRepoId(e.target.value)}
disabled={isCreating}
/>
<p className="text-xs text-muted-foreground">
Unique identifier for this repository (like GitHub's owner/repo)
</p>
</div>
{/* Name */}
<div className="space-y-2">
<Label htmlFor="repo-name">Name</Label>
<Input
id="repo-name"
placeholder="Human-readable project name"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isCreating}
/>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="repo-description">Description</Label>
<Textarea
id="repo-description"
placeholder="Brief description of your project"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
disabled={isCreating}
/>
</div>
{/* Web URLs */}
<div className="space-y-2">
<Label>Web URLs (Optional)</Label>
<div className="space-y-2">
{webUrls.map((url, index) => (
<div key={index} className="flex gap-2">
<Input value={url} readOnly className="flex-1" />
<Button
variant="outline"
size="icon"
onClick={() => removeWebUrl(index)}
disabled={isCreating}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="https://example.com/browse"
value={newWebUrl}
onChange={(e) => setNewWebUrl(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addWebUrl())}
disabled={isCreating}
/>
<Button
variant="outline"
size="icon"
onClick={addWebUrl}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
URLs where the repository can be browsed online
</p>
</div>
{/* Clone URLs */}
<div className="space-y-2">
<Label>Clone URLs *</Label>
<div className="space-y-2">
{cloneUrls.map((url, index) => (
<div key={index} className="flex gap-2">
<Input value={url} readOnly className="flex-1 font-mono text-sm" />
<Button
variant="outline"
size="icon"
onClick={() => removeCloneUrl(index)}
disabled={isCreating}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="nostr://npub.../repo-id"
value={newCloneUrl}
onChange={(e) => setNewCloneUrl(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addCloneUrl())}
disabled={isCreating}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={addCloneUrl}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
URLs for cloning the repository (at least one required)
</p>
</div>
{/* Relays */}
<div className="space-y-2">
<Label>Relays for Patches</Label>
<div className="space-y-2">
{relays.map((relay, index) => (
<div key={index} className="flex gap-2">
<Input value={relay} readOnly className="flex-1 font-mono text-sm" />
<Button
variant="outline"
size="icon"
onClick={() => removeRelay(index)}
disabled={isCreating || relays.length === 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="wss://relay.example.com"
value={newRelay}
onChange={(e) => setNewRelay(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addRelay())}
disabled={isCreating}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={addRelay}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Relays where patches will be published and monitored
</p>
</div>
{/* Earliest Commit */}
<div className="space-y-2">
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
<Input
id="earliest-commit"
placeholder="Commit hash"
value={earliestCommit}
onChange={(e) => setEarliestCommit(e.target.value)}
disabled={isCreating}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
The root commit of your repository (auto-detected when available)
</p>
</div>
</div>
</ScrollArea>
)}
{!createdNaddr && (
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isCreating}
>
Cancel
</Button>
<Button onClick={announceRepository} disabled={isCreating}>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Announcing...
</>
) : (
<>
<GitBranch className="h-4 w-4 mr-2" />
Announce Repository
</>
)}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
+510
View File
@@ -0,0 +1,510 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import {
GitBranch,
Plus,
Trash2,
Check,
Loader2,
ArrowUpRight,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
interface BranchInfo {
name: string;
isCurrent: boolean;
isRemote: boolean;
remoteName?: string;
commitId?: string;
ahead?: number;
behind?: number;
}
interface BranchManagerProps {
projectId: string;
currentBranch: string | null;
onBranchChange?: () => void;
}
export function BranchManager({ projectId, currentBranch, onBranchChange }: BranchManagerProps) {
const [branches, setBranches] = useState<BranchInfo[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [newBranchName, setNewBranchName] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [deletingBranch, setDeletingBranch] = useState<string | null>(null);
const [switchingToBranch, setSwitchingToBranch] = useState<string | null>(null);
const { git } = useGit();
const { toast } = useToast();
const projectPath = `/projects/${projectId}`;
const loadBranches = useCallback(async () => {
setIsLoading(true);
try {
// Get local branches
const localBranches = await git.listBranches({
dir: projectPath,
});
// Get remote branches
let remoteBranches: string[] = [];
try {
remoteBranches = await git.listBranches({
dir: projectPath,
remote: 'origin',
});
} catch {
// No remote or error fetching remote branches
}
// Get current branch
const current = await git.currentBranch({ dir: projectPath }).catch(() => null);
// Build branch info
const branchInfos: BranchInfo[] = [];
// Add local branches
for (const branch of localBranches) {
const isCurrent = branch === current;
let commitId: string | undefined;
try {
commitId = await git.resolveRef({
dir: projectPath,
ref: `refs/heads/${branch}`,
});
} catch {
// Skip branches we can't resolve
}
branchInfos.push({
name: branch,
isCurrent,
isRemote: false,
commitId,
});
}
// Add remote branches
for (const branch of remoteBranches) {
// Skip if we already have this as a local branch
if (localBranches.includes(branch)) continue;
let commitId: string | undefined;
try {
commitId = await git.resolveRef({
dir: projectPath,
ref: `refs/remotes/origin/${branch}`,
});
} catch {
// Skip branches we can't resolve
}
branchInfos.push({
name: branch,
isCurrent: false,
isRemote: true,
remoteName: 'origin',
commitId,
});
}
setBranches(branchInfos);
} catch (error) {
console.error('Failed to load branches:', error);
toast({
title: 'Failed to load branches',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
}, [git, projectPath, toast]);
useEffect(() => {
loadBranches();
}, [projectId, currentBranch, loadBranches]);
const handleCreateBranch = async () => {
if (!newBranchName.trim()) {
toast({
title: 'Invalid branch name',
description: 'Please enter a branch name',
variant: 'destructive',
});
return;
}
// Validate branch name
const invalidChars = /[~^: \\?*[\]]/;
if (invalidChars.test(newBranchName)) {
toast({
title: 'Invalid branch name',
description: 'Branch name contains invalid characters',
variant: 'destructive',
});
return;
}
setIsCreating(true);
try {
// Get current HEAD to base the new branch on
const currentRef = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
// Create the new branch
await git.branch({
dir: projectPath,
ref: newBranchName.trim(),
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
});
setNewBranchName('');
setIsCreateDialogOpen(false);
await loadBranches();
onBranchChange?.();
} catch (error) {
toast({
title: 'Failed to create branch',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsCreating(false);
}
};
const handleSwitchBranch = async (branchName: string) => {
setSwitchingToBranch(branchName);
try {
await git.checkout({
dir: projectPath,
ref: branchName,
});
toast({
title: 'Branch switched',
description: `Switched to branch "${branchName}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
toast({
title: 'Failed to switch branch',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setSwitchingToBranch(null);
}
};
const handleDeleteBranch = async (branchName: string) => {
setDeletingBranch(branchName);
try {
await git.deleteBranch({
dir: projectPath,
ref: branchName,
});
toast({
title: 'Branch deleted',
description: `Deleted branch "${branchName}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
toast({
title: 'Failed to delete branch',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setDeletingBranch(null);
}
};
const localBranches = branches.filter(b => !b.isRemote);
const remoteBranches = branches.filter(b => b.isRemote);
return (
<div className="space-y-4">
{/* Header with create button */}
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium">Branches</h3>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="h-8 gap-2">
<Plus className="h-4 w-4" />
New Branch
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Branch</DialogTitle>
<DialogDescription>
Create a new branch from the current HEAD
</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' && !isCreating) {
handleCreateBranch();
}
}}
autoFocus
/>
</div>
{currentBranch && (
<div className="text-sm text-muted-foreground">
Creating from: <span className="font-medium">{currentBranch}</span>
</div>
)}
</div>
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => setIsCreateDialogOpen(false)}
disabled={isCreating}
>
Cancel
</Button>
<Button onClick={handleCreateBranch} disabled={isCreating}>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Creating...
</>
) : (
<>
<Plus className="h-4 w-4 mr-2" />
Create Branch
</>
)}
</Button>
</div>
</DialogContent>
</Dialog>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-4">
{/* Local Branches */}
{localBranches.length > 0 && (
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Local Branches
</div>
<div className="space-y-1">
{localBranches.map((branch) => (
<BranchItem
key={branch.name}
branch={branch}
onSwitch={handleSwitchBranch}
onDelete={handleDeleteBranch}
isSwitching={switchingToBranch === branch.name}
isDeleting={deletingBranch === branch.name}
/>
))}
</div>
</div>
)}
{/* Remote Branches */}
{remoteBranches.length > 0 && (
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Remote Branches
</div>
<div className="space-y-1">
{remoteBranches.map((branch) => (
<BranchItem
key={`remote-${branch.name}`}
branch={branch}
onSwitch={handleSwitchBranch}
onDelete={handleDeleteBranch}
isSwitching={switchingToBranch === branch.name}
isDeleting={deletingBranch === branch.name}
/>
))}
</div>
</div>
)}
{/* Empty state */}
{localBranches.length === 0 && remoteBranches.length === 0 && (
<div className="text-center py-8 text-muted-foreground">
<GitBranch className="h-12 w-12 mx-auto mb-2 opacity-50" />
<p className="text-sm">No branches found</p>
</div>
)}
</div>
)}
</div>
);
}
interface BranchItemProps {
branch: BranchInfo;
onSwitch: (name: string) => void;
onDelete: (name: string) => void;
isSwitching: boolean;
isDeleting: boolean;
}
function BranchItem({ branch, onSwitch, onDelete, isSwitching, isDeleting }: BranchItemProps) {
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
return (
<>
<div
className={cn(
'flex items-center gap-3 p-3 rounded-lg border transition-colors group',
branch.isCurrent
? 'bg-primary/5 border-primary/20'
: 'hover:bg-muted/50 border-transparent'
)}
>
{/* Branch icon and name */}
<div className="flex items-center gap-2 flex-1 min-w-0">
{branch.isCurrent ? (
<Check className="h-4 w-4 text-primary shrink-0" />
) : (
<GitBranch className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span
className={cn(
'font-mono text-sm truncate',
branch.isCurrent && 'font-semibold text-primary'
)}
>
{branch.name}
</span>
{branch.isRemote && (
<ArrowUpRight className="h-3 w-3 text-muted-foreground shrink-0" />
)}
</div>
{branch.commitId && (
<div className="text-xs text-muted-foreground font-mono">
{branch.commitId.substring(0, 7)}
</div>
)}
</div>
</div>
{/* Current badge */}
{branch.isCurrent && (
<Badge variant="secondary" className="shrink-0">
Current
</Badge>
)}
{/* Actions */}
{!branch.isCurrent && !branch.isRemote && (
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<Button
variant="ghost"
size="sm"
className="h-8 px-2"
onClick={() => onSwitch(branch.name)}
disabled={isSwitching || isDeleting}
>
{isSwitching ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<GitBranch className="h-4 w-4 mr-1" />
Switch
</>
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setShowDeleteDialog(true)}
disabled={isSwitching || isDeleting}
>
{isDeleting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4" />
)}
</Button>
</div>
)}
</div>
{/* Delete confirmation dialog */}
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Branch</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete the branch <strong>{branch.name}</strong>?
This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
onDelete(branch.name);
setShowDeleteDialog(false);
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete Branch
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
+350
View File
@@ -0,0 +1,350 @@
import { useState, useEffect, useCallback } from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { GitCompare, Loader2, GitCommit, FileIcon } from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useToast } from '@/hooks/useToast';
import { DiffViewer } from './DiffViewer';
interface CompareViewProps {
projectId: string;
}
interface CommitInfo {
oid: string;
message: string;
author: string;
timestamp: number;
}
export function CompareView({ projectId }: CompareViewProps) {
const [branches, setBranches] = useState<string[]>([]);
const [commits, setCommits] = useState<CommitInfo[]>([]);
const [baseRef, setBaseRef] = useState<string>('');
const [compareRef, setCompareRef] = useState<string>('');
const [isLoading, setIsLoading] = useState(true);
const [isComparing, setIsComparing] = useState(false);
const [comparisonStats, setComparisonStats] = useState<{
ahead: number;
behind: number;
filesChanged: number;
} | null>(null);
const { git } = useGit();
const { toast } = useToast();
const projectPath = `/projects/${projectId}`;
const loadReferences = useCallback(async () => {
setIsLoading(true);
try {
// Get all branches
const localBranches = await git.listBranches({ dir: projectPath });
setBranches(localBranches);
// Set defaults
const currentBranch = await git.currentBranch({ dir: projectPath }).catch(() => null);
if (currentBranch) {
setCompareRef(currentBranch);
}
// Set base to main/master if available
if (localBranches.includes('main')) {
setBaseRef('main');
} else if (localBranches.includes('master')) {
setBaseRef('master');
} else if (localBranches.length > 0) {
setBaseRef(localBranches[0]);
}
} catch (error) {
console.error('Failed to load references:', error);
toast({
title: 'Failed to load branches',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
}, [git, projectPath, toast]);
const performComparison = useCallback(async () => {
if (!baseRef || !compareRef) return;
setIsComparing(true);
try {
// Get commits in compareRef that are not in baseRef
const baseCommits = await git.log({ dir: projectPath, ref: baseRef, depth: 100 });
const compareCommits = await git.log({ dir: projectPath, ref: compareRef, depth: 100 });
const baseCommitIds = new Set(baseCommits.map(c => c.oid));
const compareCommitIds = new Set(compareCommits.map(c => c.oid));
// Commits ahead (in compare but not in base)
const aheadCommits = compareCommits.filter(c => !baseCommitIds.has(c.oid));
// Commits behind (in base but not in compare)
const behindCommits = baseCommits.filter(c => !compareCommitIds.has(c.oid));
// Get list of changed files
const baseFiles = await git.listFiles({ dir: projectPath, ref: baseRef });
const compareFiles = await git.listFiles({ dir: projectPath, ref: compareRef });
const changedFiles = new Set<string>();
// Check files in compare ref
for (const file of compareFiles) {
try {
const baseBlob = await git.readBlob({ dir: projectPath, oid: baseRef, filepath: file });
const compareBlob = await git.readBlob({ dir: projectPath, oid: compareRef, filepath: file });
if (Buffer.from(baseBlob.blob).toString() !== Buffer.from(compareBlob.blob).toString()) {
changedFiles.add(file);
}
} catch {
// File exists in one but not the other
changedFiles.add(file);
}
}
// Check for deleted files
for (const file of baseFiles) {
if (!compareFiles.includes(file)) {
changedFiles.add(file);
}
}
setComparisonStats({
ahead: aheadCommits.length,
behind: behindCommits.length,
filesChanged: changedFiles.size,
});
// Set commit info for display
const commitInfos: CommitInfo[] = aheadCommits.map(c => ({
oid: c.oid,
message: c.commit.message,
author: c.commit.author.name,
timestamp: c.commit.author.timestamp,
}));
setCommits(commitInfos);
} catch (error) {
console.error('Failed to compare:', error);
toast({
title: 'Comparison failed',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsComparing(false);
}
}, [baseRef, compareRef, git, projectPath, toast]);
useEffect(() => {
loadReferences();
}, [projectId, loadReferences]);
useEffect(() => {
if (baseRef && compareRef && baseRef !== compareRef) {
performComparison();
}
}, [baseRef, compareRef, performComparison]);
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return 'today';
} else if (diffDays === 1) {
return 'yesterday';
} else if (diffDays < 7) {
return `${diffDays} days ago`;
} else {
return date.toLocaleDateString();
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="space-y-6">
{/* Comparison selectors */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<GitCompare className="h-5 w-5" />
Compare Branches
</CardTitle>
<CardDescription>
Select two branches to compare changes
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4">
<div className="flex-1">
<label className="text-sm font-medium mb-2 block">Base Branch</label>
<Select value={baseRef} onValueChange={setBaseRef}>
<SelectTrigger>
<SelectValue placeholder="Select base branch" />
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="pt-6">
<GitCompare className="h-5 w-5 text-muted-foreground" />
</div>
<div className="flex-1">
<label className="text-sm font-medium mb-2 block">Compare Branch</label>
<Select value={compareRef} onValueChange={setCompareRef}>
<SelectTrigger>
<SelectValue placeholder="Select compare branch" />
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Comparison stats */}
{comparisonStats && !isComparing && (
<div className="mt-6 grid grid-cols-3 gap-4">
<div className="bg-muted/30 rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-green-600">
{comparisonStats.ahead}
</div>
<div className="text-sm text-muted-foreground mt-1">
Commits Ahead
</div>
</div>
<div className="bg-muted/30 rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-orange-600">
{comparisonStats.behind}
</div>
<div className="text-sm text-muted-foreground mt-1">
Commits Behind
</div>
</div>
<div className="bg-muted/30 rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-blue-600">
{comparisonStats.filesChanged}
</div>
<div className="text-sm text-muted-foreground mt-1">
Files Changed
</div>
</div>
</div>
)}
{isComparing && (
<div className="mt-6 flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
<span className="text-muted-foreground">Comparing branches...</span>
</div>
)}
</CardContent>
</Card>
{/* Comparison results */}
{baseRef && compareRef && baseRef !== compareRef && !isComparing && (
<Tabs defaultValue="commits" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="commits" className="gap-2">
<GitCommit className="h-4 w-4" />
Commits ({commits.length})
</TabsTrigger>
<TabsTrigger value="files" className="gap-2">
<FileIcon className="h-4 w-4" />
Files ({comparisonStats?.filesChanged || 0})
</TabsTrigger>
</TabsList>
{/* Commits tab */}
<TabsContent value="commits" className="mt-6">
{commits.length > 0 ? (
<Card>
<CardHeader>
<CardTitle className="text-base">
Commits in {compareRef} not in {baseRef}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{commits.map((commit) => (
<div
key={commit.oid}
className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors"
>
<GitCommit className="h-5 w-5 text-muted-foreground shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<p className="font-medium text-sm">
{commit.message.split('\n')[0]}
</p>
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
<span>{commit.author}</span>
<span>•</span>
<span>{formatDate(commit.timestamp)}</span>
<span>•</span>
<span className="font-mono">{commit.oid.substring(0, 7)}</span>
</div>
</div>
</div>
))}
</CardContent>
</Card>
) : (
<Card>
<CardContent className="py-12 text-center">
<GitCommit className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
<p className="text-muted-foreground">
No commits difference between branches
</p>
</CardContent>
</Card>
)}
</TabsContent>
{/* Files tab */}
<TabsContent value="files" className="mt-6">
<Card>
<CardContent className="p-0">
<DiffViewer
projectId={projectId}
compareFrom={baseRef}
compareTo={compareRef}
/>
</CardContent>
</Card>
</TabsContent>
</Tabs>
)}
</div>
);
}
+556
View File
@@ -0,0 +1,556 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
FileIcon,
Plus,
Minus,
Edit,
Loader2,
SplitSquareHorizontal,
ListTree,
Copy,
Check,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
interface DiffHunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: DiffLine[];
}
interface DiffLine {
type: 'add' | 'delete' | 'context';
content: string;
oldLineNumber?: number;
newLineNumber?: number;
}
interface FileDiff {
filepath: string;
status: 'modified' | 'added' | 'deleted';
hunks: DiffHunk[];
oldContent?: string;
newContent?: string;
}
interface DiffViewerProps {
projectId: string;
compareFrom?: string; // commit, branch, or 'HEAD'
compareTo?: string; // commit, branch, or working directory
filepath?: string; // If provided, show only this file
}
export function DiffViewer({ projectId, compareFrom = 'HEAD', compareTo, filepath }: DiffViewerProps) {
const [diffs, setDiffs] = useState<FileDiff[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'unified' | 'split'>('split');
const [copiedHunk, setCopiedHunk] = useState<number | null>(null);
const { git } = useGit();
const { fs } = useFS();
const { toast } = useToast();
const projectPath = `/projects/${projectId}`;
const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise<string[]> => {
// Get list of files from both refs and find differences
const filesFrom = await git.listFiles({ dir: projectPath, ref: from });
const filesTo = await git.listFiles({ dir: projectPath, ref: to });
const changedFiles = new Set<string>();
// Check files that exist in 'to'
for (const file of filesTo) {
try {
const blobFrom = await git.readBlob({ dir: projectPath, oid: from, filepath: file });
const blobTo = await git.readBlob({ dir: projectPath, oid: to, filepath: file });
// Compare content
if (Buffer.from(blobFrom.blob).toString() !== Buffer.from(blobTo.blob).toString()) {
changedFiles.add(file);
}
} catch {
// File exists in one but not the other
changedFiles.add(file);
}
}
// Check files that were deleted
for (const file of filesFrom) {
if (!filesTo.includes(file)) {
changedFiles.add(file);
}
}
return Array.from(changedFiles);
}, [git, projectPath]);
const generateFileDiff = useCallback(async (
file: string,
from: string,
to?: string
): Promise<FileDiff | null> => {
try {
let oldContent = '';
let newContent = '';
let status: 'modified' | 'added' | 'deleted' = 'modified';
// Get old content
try {
const blob = await git.readBlob({ dir: projectPath, oid: from, filepath: file });
oldContent = Buffer.from(blob.blob).toString('utf-8');
} catch {
// File didn't exist in old version
status = 'added';
}
// Get new content
try {
if (to) {
const blob = await git.readBlob({ dir: projectPath, oid: to, filepath: file });
newContent = Buffer.from(blob.blob).toString('utf-8');
} else {
// Working directory
const content = await fs.readFile(`${projectPath}/${file}`, { encoding: 'utf8' });
newContent = content;
}
} catch {
// File doesn't exist in new version
if (status !== 'added') {
status = 'deleted';
}
}
// Generate hunks
const hunks = generateDiffHunks(oldContent, newContent);
return {
filepath: file,
status,
hunks,
oldContent,
newContent,
};
} catch (error) {
console.error(`Error generating diff for ${file}:`, error);
return null;
}
}, [git, projectPath, fs]);
const generateDiffHunks = (oldContent: string, newContent: string): DiffHunk[] => {
const oldLines = oldContent.split('\n');
const newLines = newContent.split('\n');
// Simple line-by-line diff
const hunks: DiffHunk[] = [];
let currentHunk: DiffHunk | null = null;
let oldIndex = 0;
let newIndex = 0;
while (oldIndex < oldLines.length || newIndex < newLines.length) {
const oldLine = oldLines[oldIndex];
const newLine = newLines[newIndex];
if (oldLine === newLine) {
// Context line
if (currentHunk) {
currentHunk.lines.push({
type: 'context',
content: oldLine || '',
oldLineNumber: oldIndex + 1,
newLineNumber: newIndex + 1,
});
}
oldIndex++;
newIndex++;
} else {
// Start a new hunk if needed
if (!currentHunk) {
currentHunk = {
oldStart: oldIndex + 1,
oldLines: 0,
newStart: newIndex + 1,
newLines: 0,
lines: [],
};
// Add context before the change
const contextStart = Math.max(0, oldIndex - 3);
for (let i = contextStart; i < oldIndex; i++) {
currentHunk.lines.push({
type: 'context',
content: oldLines[i] || '',
oldLineNumber: i + 1,
newLineNumber: i + 1,
});
}
}
// Determine if this is an addition, deletion, or modification
if (oldIndex >= oldLines.length) {
// Addition
currentHunk.lines.push({
type: 'add',
content: newLine || '',
newLineNumber: newIndex + 1,
});
currentHunk.newLines++;
newIndex++;
} else if (newIndex >= newLines.length) {
// Deletion
currentHunk.lines.push({
type: 'delete',
content: oldLine || '',
oldLineNumber: oldIndex + 1,
});
currentHunk.oldLines++;
oldIndex++;
} else {
// Changed line - show as delete + add
currentHunk.lines.push({
type: 'delete',
content: oldLine || '',
oldLineNumber: oldIndex + 1,
});
currentHunk.lines.push({
type: 'add',
content: newLine || '',
newLineNumber: newIndex + 1,
});
currentHunk.oldLines++;
currentHunk.newLines++;
oldIndex++;
newIndex++;
}
// Check if we should close this hunk
const contextAfter = 3;
let contextCount = 0;
let tempOldIndex = oldIndex;
let tempNewIndex = newIndex;
while (
contextCount < contextAfter &&
tempOldIndex < oldLines.length &&
tempNewIndex < newLines.length
) {
if (oldLines[tempOldIndex] === newLines[tempNewIndex]) {
currentHunk.lines.push({
type: 'context',
content: oldLines[tempOldIndex] || '',
oldLineNumber: tempOldIndex + 1,
newLineNumber: tempNewIndex + 1,
});
contextCount++;
tempOldIndex++;
tempNewIndex++;
} else {
break;
}
}
if (contextCount >= contextAfter || tempOldIndex >= oldLines.length) {
hunks.push(currentHunk);
currentHunk = null;
oldIndex = tempOldIndex;
newIndex = tempNewIndex;
}
}
}
// Close any remaining hunk
if (currentHunk) {
hunks.push(currentHunk);
}
return hunks;
};
const loadDiffs = useCallback(async () => {
setIsLoading(true);
try {
let files: string[] = [];
if (filepath) {
files = [filepath];
} else if (compareTo) {
// Compare two commits/branches
files = await getChangedFilesBetweenRefs(compareFrom, compareTo);
} else {
// Compare against working directory
const statusMatrix = await git.statusMatrix({ dir: projectPath });
files = statusMatrix
.filter(([, head, workdir]) => head !== workdir)
.map(([file]) => file);
}
const fileDiffs: FileDiff[] = [];
for (const file of files) {
try {
const diff = await generateFileDiff(file, compareFrom, compareTo);
if (diff) {
fileDiffs.push(diff);
}
} catch (error) {
console.warn(`Failed to generate diff for ${file}:`, error);
}
}
setDiffs(fileDiffs);
if (fileDiffs.length > 0 && !selectedFile) {
setSelectedFile(fileDiffs[0].filepath);
}
} catch (error) {
console.error('Failed to load diffs:', error);
toast({
title: 'Failed to load diffs',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
}, [compareFrom, compareTo, filepath, git, projectPath, selectedFile, toast, getChangedFilesBetweenRefs, generateFileDiff]);
useEffect(() => {
loadDiffs();
}, [projectId, compareFrom, compareTo, filepath, loadDiffs]);
const copyHunkToClipboard = async (hunk: DiffHunk, index: number) => {
const hunkText = hunk.lines.map(line => line.content).join('\n');
await navigator.clipboard.writeText(hunkText);
setCopiedHunk(index);
setTimeout(() => setCopiedHunk(null), 2000);
};
const selectedDiff = diffs.find(d => d.filepath === selectedFile);
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
if (diffs.length === 0) {
return (
<div className="flex flex-col items-center justify-center py-12 text-center">
<FileIcon className="h-12 w-12 text-muted-foreground mb-4" />
<p className="text-muted-foreground">No changes to display</p>
</div>
);
}
return (
<div className="flex h-full">
{/* File list sidebar */}
<div className="w-64 border-r">
<div className="p-4 border-b">
<h3 className="font-semibold text-sm">Changed Files</h3>
<p className="text-xs text-muted-foreground mt-1">
{diffs.length} file{diffs.length !== 1 ? 's' : ''} changed
</p>
</div>
<ScrollArea className="h-[calc(100%-73px)]">
<div className="p-2 space-y-1">
{diffs.map((diff) => (
<button
key={diff.filepath}
onClick={() => setSelectedFile(diff.filepath)}
className={cn(
'w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors',
selectedFile === diff.filepath
? 'bg-primary/10 text-primary'
: 'hover:bg-muted/50'
)}
>
{diff.status === 'added' && <Plus className="h-4 w-4 text-green-600 shrink-0" />}
{diff.status === 'deleted' && <Minus className="h-4 w-4 text-red-600 shrink-0" />}
{diff.status === 'modified' && <Edit className="h-4 w-4 text-blue-600 shrink-0" />}
<span className="font-mono text-sm truncate">{diff.filepath}</span>
</button>
))}
</div>
</ScrollArea>
</div>
{/* Diff content */}
<div className="flex-1 flex flex-col">
{selectedDiff && (
<>
{/* Header */}
<div className="p-4 border-b flex items-center justify-between">
<div className="flex items-center gap-3">
<h3 className="font-mono text-sm font-medium">{selectedDiff.filepath}</h3>
<Badge
variant="outline"
className={cn(
selectedDiff.status === 'added' && 'border-green-600 text-green-600',
selectedDiff.status === 'deleted' && 'border-red-600 text-red-600',
selectedDiff.status === 'modified' && 'border-blue-600 text-blue-600'
)}
>
{selectedDiff.status}
</Badge>
</div>
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'unified' | 'split')}>
<TabsList>
<TabsTrigger value="split" className="gap-2">
<SplitSquareHorizontal className="h-4 w-4" />
Split
</TabsTrigger>
<TabsTrigger value="unified" className="gap-2">
<ListTree className="h-4 w-4" />
Unified
</TabsTrigger>
</TabsList>
</Tabs>
</div>
{/* Diff content */}
<ScrollArea className="flex-1">
<div className="p-4">
{selectedDiff.hunks.map((hunk, hunkIndex) => (
<div key={hunkIndex} className="mb-6 border rounded-lg overflow-hidden">
{/* Hunk header */}
<div className="bg-muted/50 px-4 py-2 flex items-center justify-between border-b">
<span className="font-mono text-xs text-muted-foreground">
@@ -{hunk.oldStart},{hunk.oldLines} +{hunk.newStart},{hunk.newLines} @@
</span>
<Button
variant="ghost"
size="sm"
className="h-6 px-2"
onClick={() => copyHunkToClipboard(hunk, hunkIndex)}
>
{copiedHunk === hunkIndex ? (
<>
<Check className="h-3 w-3 mr-1" />
Copied
</>
) : (
<>
<Copy className="h-3 w-3 mr-1" />
Copy
</>
)}
</Button>
</div>
{/* Hunk lines */}
{viewMode === 'split' ? (
<SplitDiffView hunk={hunk} filepath={selectedDiff.filepath} />
) : (
<UnifiedDiffView hunk={hunk} filepath={selectedDiff.filepath} />
)}
</div>
))}
</div>
</ScrollArea>
</>
)}
</div>
</div>
);
}
function SplitDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
return (
<div className="grid grid-cols-2 divide-x font-mono text-sm">
{/* Old (left) side */}
<div>
{hunk.lines.map((line, i) => (
line.type !== 'add' && (
<div
key={i}
className={cn(
'flex',
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
)}
>
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
{line.oldLineNumber}
</span>
<pre className="px-2 py-1 flex-1 overflow-x-auto">
<code
className={cn(line.type === 'delete' && 'text-red-700 dark:text-red-400')}
dangerouslySetInnerHTML={{ __html: line.content }}
/>
</pre>
</div>
)
))}
</div>
{/* New (right) side */}
<div>
{hunk.lines.map((line, i) => (
line.type !== 'delete' && (
<div
key={i}
className={cn(
'flex',
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20'
)}
>
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
{line.newLineNumber}
</span>
<pre className="px-2 py-1 flex-1 overflow-x-auto">
<code
className={cn(line.type === 'add' && 'text-green-700 dark:text-green-400')}
dangerouslySetInnerHTML={{ __html: line.content }}
/>
</pre>
</div>
)
))}
</div>
</div>
);
}
function UnifiedDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
return (
<div className="font-mono text-sm">
{hunk.lines.map((line, i) => (
<div
key={i}
className={cn(
'flex',
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20',
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
)}
>
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
{line.oldLineNumber || line.newLineNumber}
</span>
<span className="px-2 py-1 select-none w-6 shrink-0">
{line.type === 'add' ? '+' : line.type === 'delete' ? '-' : ' '}
</span>
<pre className="px-2 py-1 flex-1 overflow-x-auto">
<code
className={cn(
line.type === 'add' && 'text-green-700 dark:text-green-400',
line.type === 'delete' && 'text-red-700 dark:text-red-400'
)}
dangerouslySetInnerHTML={{ __html: line.content }}
/>
</pre>
</div>
))}
</div>
);
}
+166
View File
@@ -0,0 +1,166 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
GitBranch,
GitCompare,
Settings,
GitPullRequest,
} from 'lucide-react';
import { BranchManager } from './BranchManager';
import { CompareView } from './CompareView';
import { DiffViewer } from './DiffViewer';
import { PullRequestForm } from './PullRequestForm';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGit } from '@/hooks/useGit';
interface GitManagementDialogProps {
projectId: string;
children?: React.ReactNode;
open?: boolean;
onOpenChange?: (open: boolean) => void;
defaultTab?: string;
}
export function GitManagementDialog({
projectId,
children,
open,
onOpenChange,
defaultTab = 'branches',
}: GitManagementDialogProps) {
const [activeTab, setActiveTab] = useState(defaultTab);
const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
const { git } = useGit();
const projectPath = `/projects/${projectId}`;
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
useEffect(() => {
const loadRemoteUrl = async () => {
try {
const url = await git.getRemoteURL(projectPath, 'origin');
setRemoteUrl(url);
} catch {
setRemoteUrl(null);
}
};
if (open) {
loadRemoteUrl();
}
}, [open, git, projectPath]);
const handleBranchChange = () => {
// Refetch git status when branches change
refetchGitStatus();
};
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
<DialogContent className="max-w-6xl h-[90vh] p-0 flex flex-col gap-0">
{/* Fixed Header */}
<DialogHeader className="px-6 pt-6 pb-4 border-b shrink-0">
<DialogTitle className="flex items-center gap-2">
<GitBranch className="h-5 w-5" />
Git Management
</DialogTitle>
</DialogHeader>
{/* Tabs Container - takes remaining space */}
<div className="flex-1 flex flex-col min-h-0">
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col">
{/* Fixed Tab List */}
<div className="border-b px-6 shrink-0">
<TabsList className="h-auto p-0 bg-transparent">
<TabsTrigger
value="branches"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitBranch className="h-4 w-4" />
Branches
</TabsTrigger>
<TabsTrigger
value="changes"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<Settings className="h-4 w-4" />
Changes
</TabsTrigger>
<TabsTrigger
value="compare"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitCompare className="h-4 w-4" />
Compare
</TabsTrigger>
{remoteUrl && (
<TabsTrigger
value="pr"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitPullRequest className="h-4 w-4" />
Pull Request
</TabsTrigger>
)}
</TabsList>
</div>
{/* Scrollable Tab Content */}
<TabsContent value="branches" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<BranchManager
projectId={projectId}
currentBranch={gitStatus?.currentBranch || null}
onBranchChange={handleBranchChange}
/>
</div>
</ScrollArea>
</TabsContent>
<TabsContent value="changes" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col min-h-0">
<div className="flex-1 min-h-0">
<DiffViewer
projectId={projectId}
compareFrom="HEAD"
/>
</div>
</TabsContent>
<TabsContent value="compare" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<CompareView projectId={projectId} />
</div>
</ScrollArea>
</TabsContent>
{remoteUrl && (
<TabsContent value="pr" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<PullRequestForm
projectId={projectId}
currentBranch={gitStatus?.currentBranch || null}
remoteUrl={remoteUrl}
/>
</div>
</ScrollArea>
</TabsContent>
)}
</Tabs>
</div>
</DialogContent>
</Dialog>
</>
);
}
+574
View File
@@ -0,0 +1,574 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import {
GitMerge,
Loader2,
AlertCircle,
CheckCircle,
GitCommit,
AlertTriangle,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useToast } from '@/hooks/useToast';
import { useSearchParams } from 'react-router-dom';
interface MergeDialogProps {
projectId: string;
currentBranch: string | null;
sourceBranch?: string;
targetBranch?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
onMergeComplete?: () => void;
}
interface MergePreview {
sourceBranch: string;
targetBranch: string;
commitsToMerge: Array<{
oid: string;
message: string;
author: string;
timestamp: number;
}>;
filesChanged: string[];
canFastForward: boolean;
hasConflicts: boolean;
conflictingFiles: string[];
}
export function MergeDialog({
projectId,
currentBranch,
sourceBranch: initialSourceBranch,
targetBranch: _initialTargetBranch,
open,
onOpenChange,
onMergeComplete,
}: MergeDialogProps) {
const [isOpen, setIsOpen] = useState(open ?? false);
const [branches, setBranches] = useState<string[]>([]);
const [sourceBranch, setSourceBranch] = useState<string>(initialSourceBranch || '');
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
const [isMerging, setIsMerging] = useState(false);
const [mergePreview, setMergePreview] = useState<MergePreview | null>(null);
const [error, setError] = useState<string | null>(null);
const [mergeComplete, setMergeComplete] = useState(false);
const { git } = useGit();
const { toast } = useToast();
const [searchParams, setSearchParams] = useSearchParams();
const projectPath = `/projects/${projectId}`;
useEffect(() => {
if (open !== undefined) {
setIsOpen(open);
}
}, [open]);
const loadBranches = useCallback(async () => {
setIsLoadingBranches(true);
try {
const localBranches = await git.listBranches({ dir: projectPath });
// Filter out current branch from source options
const availableBranches = localBranches.filter(b => b !== currentBranch);
setBranches(availableBranches);
// Set default source branch
if (availableBranches.length > 0) {
setSourceBranch(availableBranches[0]);
}
} catch (err) {
console.error('Failed to load branches:', err);
toast({
title: 'Failed to load branches',
description: err instanceof Error ? err.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoadingBranches(false);
}
}, [git, projectPath, currentBranch, toast]);
const loadMergePreview = useCallback(async () => {
if (!sourceBranch || !currentBranch) return;
setIsLoadingPreview(true);
setError(null);
try {
// Get commits that will be merged
const sourceCommits = await git.log({ dir: projectPath, ref: sourceBranch, depth: 50 });
const targetCommits = await git.log({ dir: projectPath, ref: currentBranch, depth: 50 });
const targetCommitIds = new Set(targetCommits.map(c => c.oid));
const commitsToMerge = sourceCommits.filter(c => !targetCommitIds.has(c.oid));
// Get changed files
const sourceFiles = await git.listFiles({ dir: projectPath, ref: sourceBranch });
const targetFiles = await git.listFiles({ dir: projectPath, ref: currentBranch });
const changedFiles = new Set<string>();
for (const file of [...sourceFiles, ...targetFiles]) {
try {
const sourceBlob = await git.readBlob({
dir: projectPath,
oid: sourceBranch,
filepath: file,
}).catch(() => null);
const targetBlob = await git.readBlob({
dir: projectPath,
oid: currentBranch,
filepath: file,
}).catch(() => null);
if (!sourceBlob || !targetBlob ||
Buffer.from(sourceBlob.blob).toString() !== Buffer.from(targetBlob.blob).toString()) {
changedFiles.add(file);
}
} catch {
changedFiles.add(file);
}
}
// Check if can fast-forward
const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch });
const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch });
const canFastForward = await git.isDescendent({
dir: projectPath,
oid: sourceOid,
ancestor: targetOid,
}).catch(() => false);
// Try to detect conflicts (simplified - real detection happens during merge)
const conflictingFiles: string[] = [];
// For now, we'll set this during actual merge
setMergePreview({
sourceBranch,
targetBranch: currentBranch,
commitsToMerge: commitsToMerge.map(c => ({
oid: c.oid,
message: c.commit.message,
author: c.commit.author.name,
timestamp: c.commit.author.timestamp,
})),
filesChanged: Array.from(changedFiles),
canFastForward,
hasConflicts: false,
conflictingFiles,
});
} catch (err) {
console.error('Failed to load merge preview:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setIsLoadingPreview(false);
}
}, [sourceBranch, currentBranch, git, projectPath]);
useEffect(() => {
if (isOpen) {
loadBranches();
}
}, [isOpen, loadBranches]);
useEffect(() => {
if (sourceBranch && currentBranch && sourceBranch !== currentBranch) {
loadMergePreview();
} else {
setMergePreview(null);
}
}, [sourceBranch, currentBranch, loadMergePreview]);
const performMerge = async () => {
if (!sourceBranch || !currentBranch) return;
setIsMerging(true);
setError(null);
try {
// Check if can fast-forward
const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch });
const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch });
const canFastForward = await git.isDescendent({
dir: projectPath,
oid: sourceOid,
ancestor: targetOid,
}).catch(() => false);
if (canFastForward) {
// Fast-forward merge: update the current branch to point to source branch commit
await git.writeRef({
dir: projectPath,
ref: `refs/heads/${currentBranch}`,
value: sourceOid,
force: true,
});
// Update working directory to match the new HEAD
await git.checkout({
dir: projectPath,
ref: currentBranch,
force: true,
});
toast({
title: 'Fast-forward merge successful',
description: `Successfully fast-forwarded ${currentBranch} to ${sourceBranch}`,
});
} else {
// Three-way merge
const result = await git.merge({
dir: projectPath,
ours: currentBranch,
theirs: sourceBranch,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
});
if (result.alreadyMerged) {
toast({
title: 'Already merged',
description: 'The branches are already merged',
});
setMergeComplete(true);
onMergeComplete?.();
return;
}
// The merge result contains the new tree OID
// We need to create a commit with this tree
const mergeCommitOid = await git.commit({
dir: projectPath,
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
parent: [targetOid, sourceOid], // Two parents for merge commit
tree: result.tree,
});
console.log('Created merge commit:', mergeCommitOid);
// Update working directory to match the merge
await git.checkout({
dir: projectPath,
ref: currentBranch,
force: true,
});
toast({
title: 'Merge successful',
description: `Successfully merged ${sourceBranch} into ${currentBranch}`,
});
}
setMergeComplete(true);
// Trigger rebuild
setTimeout(() => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set('build', '');
setSearchParams(newSearchParams);
}, 500);
onMergeComplete?.();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
if (errorMessage.includes('conflict') || errorMessage.includes('CONFLICT')) {
setError('Merge conflicts detected. Please resolve conflicts manually using the terminal.');
} else {
setError(errorMessage);
}
toast({
title: 'Merge failed',
description: errorMessage,
variant: 'destructive',
duration: Infinity,
});
} finally {
setIsMerging(false);
}
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return 'today';
} else if (diffDays === 1) {
return 'yesterday';
} else if (diffDays < 7) {
return `${diffDays} days ago`;
} else {
return date.toLocaleDateString();
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
onOpenChange?.(newOpen);
if (!newOpen) {
setSourceBranch('');
setMergePreview(null);
setError(null);
setMergeComplete(false);
}
};
if (!currentBranch) {
return null;
}
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" className="gap-2">
<GitMerge className="h-4 w-4" />
Merge Branch
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<GitMerge className="h-5 w-5" />
Merge Branch
</DialogTitle>
<DialogDescription>
Merge changes from another branch into {currentBranch}
</DialogDescription>
</DialogHeader>
{mergeComplete ? (
// Success state
<div className="py-8 text-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
<div>
<h3 className="text-lg font-semibold mb-2">Merge Complete!</h3>
<p className="text-muted-foreground">
Successfully merged {sourceBranch} into {currentBranch}
</p>
</div>
<Button onClick={() => handleOpenChange(false)}>
Close
</Button>
</div>
) : (
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 pr-4">
{/* Source branch selection */}
<div className="space-y-2">
<label className="text-sm font-medium">Source Branch</label>
<Select
value={sourceBranch}
onValueChange={setSourceBranch}
disabled={isLoadingBranches || isMerging}
>
<SelectTrigger>
<SelectValue placeholder="Select branch to merge from" />
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
The branch to merge into {currentBranch}
</p>
</div>
{/* Merge direction visualization */}
{sourceBranch && (
<div className="bg-muted/30 rounded-lg p-4">
<div className="flex items-center gap-2 justify-center text-sm">
<Badge variant="outline" className="font-mono">
{sourceBranch}
</Badge>
<GitMerge className="h-4 w-4 text-muted-foreground" />
<Badge variant="default" className="font-mono">
{currentBranch}
</Badge>
</div>
</div>
)}
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Loading preview */}
{isLoadingPreview && (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
<span className="text-muted-foreground">Loading merge preview...</span>
</div>
)}
{/* Merge preview */}
{mergePreview && !isLoadingPreview && (
<div className="space-y-4">
{/* Stats */}
<div className="grid grid-cols-2 gap-4">
<Card>
<CardContent className="pt-6 text-center">
<div className="text-2xl font-bold text-green-600">
{mergePreview.commitsToMerge.length}
</div>
<div className="text-sm text-muted-foreground mt-1">
Commits to Merge
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6 text-center">
<div className="text-2xl font-bold text-blue-600">
{mergePreview.filesChanged.length}
</div>
<div className="text-sm text-muted-foreground mt-1">
Files Changed
</div>
</CardContent>
</Card>
</div>
{/* Fast-forward badge */}
{mergePreview.canFastForward && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
This merge can be fast-forwarded (no merge commit needed)
</AlertDescription>
</Alert>
)}
{/* Commits to merge */}
{mergePreview.commitsToMerge.length > 0 && (
<div>
<h4 className="text-sm font-medium mb-3">Commits to be merged:</h4>
<div className="space-y-2 max-h-60 overflow-y-auto">
{mergePreview.commitsToMerge.slice(0, 10).map((commit) => (
<div
key={commit.oid}
className="flex items-start gap-3 p-3 rounded-lg border bg-card"
>
<GitCommit className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">
{commit.message.split('\n')[0]}
</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
<span>{commit.author}</span>
<span>•</span>
<span>{formatDate(commit.timestamp)}</span>
</div>
</div>
</div>
))}
{mergePreview.commitsToMerge.length > 10 && (
<p className="text-xs text-muted-foreground text-center py-2">
+ {mergePreview.commitsToMerge.length - 10} more commits
</p>
)}
</div>
</div>
)}
{/* No changes */}
{mergePreview.commitsToMerge.length === 0 && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
No new commits to merge. The branches are already in sync.
</AlertDescription>
</Alert>
)}
{/* Warning about conflicts */}
{mergePreview.hasConflicts && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Conflicts detected in {mergePreview.conflictingFiles.length} file(s).
You may need to resolve conflicts manually.
</AlertDescription>
</Alert>
)}
</div>
)}
</div>
</ScrollArea>
)}
{!mergeComplete && (
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isMerging}
>
Cancel
</Button>
<Button
onClick={performMerge}
disabled={
isMerging ||
isLoadingPreview ||
!mergePreview ||
mergePreview.commitsToMerge.length === 0
}
>
{isMerging ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Merging...
</>
) : (
<>
<GitMerge className="h-4 w-4 mr-2" />
Merge Branch
</>
)}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff. Show more