mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4be7f67cac | ||
|
|
e1da355392 | ||
|
|
e47413559b |
No files matched your search
@@ -1,6 +1,3 @@
|
||||
# Sentry
|
||||
VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************"
|
||||
|
||||
# GitHub OAuth Configuration
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
|
||||
@@ -7,7 +7,6 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
deploy.sh
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
@@ -16,9 +15,6 @@ dist-ssr
|
||||
*.apk
|
||||
*.aab
|
||||
|
||||
# Electron build output
|
||||
electron-dist
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
.DS_Store
|
||||
|
||||
@@ -33,7 +33,7 @@ This architecture allows Shakespeare to provide a full development environment e
|
||||
|
||||
Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`:
|
||||
|
||||
- **ShellTool**: Execute shell commands (virtual in browser, real OS shell in Electron)
|
||||
- **ShellTool**: Execute shell commands in the virtual filesystem environment
|
||||
- **TextEditorViewTool**: Read file contents and view directory structures
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
@@ -55,7 +55,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
**In Browser Mode:**
|
||||
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
|
||||
|
||||
**Available Commands:**
|
||||
@@ -64,16 +63,6 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
|
||||
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
|
||||
|
||||
**In Electron Mode:**
|
||||
When running in Electron, the ShellTool automatically uses the **real OS terminal** instead of the virtual terminal. This means:
|
||||
- **All OS commands available**: Not limited to built-in commands
|
||||
- **Native shell features**: Pipes, redirection, environment variables work natively
|
||||
- **Package managers**: `npm`, `yarn`, `pnpm` work directly
|
||||
- **Build tools**: `vite`, `webpack`, `tsc`, etc. available
|
||||
- **System utilities**: Full access to OS commands
|
||||
|
||||
The ShellTool detects the environment automatically and uses the appropriate execution method.
|
||||
|
||||
#### Security
|
||||
|
||||
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
|
||||
@@ -91,7 +80,6 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
|
||||
- **GitCommitTool**: AI tool for automated commits with staging and validation
|
||||
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
|
||||
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
@@ -120,30 +108,6 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
|
||||
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
|
||||
|
||||
### Gift Card Redemption
|
||||
|
||||
Shakespeare supports automatic gift card redemption via URL parameters. Users can click shareable gift card links to instantly redeem AI credits.
|
||||
|
||||
**URL Format:**
|
||||
```
|
||||
/giftcard#baseURL=<providerBaseURL>&code=<giftcardCode>
|
||||
```
|
||||
|
||||
**Flow:**
|
||||
1. User clicks gift card link (e.g., from email or social media)
|
||||
2. Shakespeare displays a dialog showing the credit amount
|
||||
3. URL is rewritten to `/` for privacy (removes gift card code from history)
|
||||
4. If user is not logged in or provider is not configured, a multi-step wizard guides them through setup
|
||||
5. User can switch between Nostr accounts before redeeming
|
||||
6. Credits are added to the user's account via NIP-98 authenticated API call
|
||||
|
||||
**Components:**
|
||||
- `GiftCardRedeemDialog`: Main dialog handling the entire redemption flow
|
||||
- Integrates with existing login/signup dialogs and provider configuration
|
||||
- Automatically matches provider baseURL against configured providers and presets
|
||||
|
||||
See `GIFTCARD_REDEMPTION.md` for detailed documentation.
|
||||
|
||||
## AI Message Format
|
||||
|
||||
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
|
||||
@@ -220,7 +184,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||
- `useTheme`: Theme management
|
||||
@@ -1100,19 +1063,12 @@ The project includes an `AppProvider` that manages global application state incl
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
// ... other config options
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
The app uses NIP-65 relay lists for managing multiple relays with read/write permissions. Configuration is persisted in local storage.
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
@@ -1166,12 +1122,11 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state that guides users to take action or provides helpful context.
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
@@ -1179,64 +1134,24 @@ import { Link } from 'react-router-dom';
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Configure your relays to discover more content.
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<Button asChild variant="outline">
|
||||
<Link to="/settings/nostr">Manage Relays</Link>
|
||||
</Button>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## CRITICAL Design Standards
|
||||
## Design Customization
|
||||
|
||||
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
|
||||
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
|
||||
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
|
||||
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
|
||||
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
### Design Principles
|
||||
|
||||
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
|
||||
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
|
||||
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
|
||||
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
|
||||
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
|
||||
|
||||
### Avoid Generic Design
|
||||
|
||||
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
|
||||
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
|
||||
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
|
||||
|
||||
### Interaction Patterns
|
||||
|
||||
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
|
||||
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
|
||||
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
|
||||
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
|
||||
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
|
||||
|
||||
### Technical Requirements
|
||||
|
||||
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
|
||||
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
|
||||
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
|
||||
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
|
||||
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
|
||||
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
|
||||
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
|
||||
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
|
||||
|
||||
### Components
|
||||
|
||||
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
|
||||
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
|
||||
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
|
||||
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ https://shakespeare.diy
|
||||
|
||||
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
|
||||
- **Buy credits anonymously** with Nostr and Lightning ⚡
|
||||
- **Redeem gift cards** with shareable links for instant credits
|
||||
- **Runs entirely in the browser** No backend required
|
||||
|
||||
## How it Works
|
||||
@@ -29,15 +28,6 @@ Shakespeare can work on any type of project. But it is specialized to build Reac
|
||||
|
||||
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.
|
||||
|
||||
## Mirrors
|
||||
|
||||
Shakespeare is available on the following URLs:
|
||||
|
||||
- [shakespeare.diy](https://shakespeare.diy)
|
||||
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
|
||||
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
|
||||
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
|
||||
|
||||
## Alternatives
|
||||
|
||||
- [goose](https://github.com/block/goose) - open-source desktop app and cli utilizing your full computer for AI tasks
|
||||
|
||||
-278
@@ -1,278 +0,0 @@
|
||||
# Shakespeare Plugins System
|
||||
|
||||
Shakespeare now includes a comprehensive plugins system that allows you to extend the AI's capabilities with reusable skills.
|
||||
|
||||
## Overview
|
||||
|
||||
Plugins are Git repositories that can contain **skills** - specialized AI workflows that help the AI assistant perform specific tasks more effectively. Skills are automatically discovered and made available to the AI through the `skill` tool.
|
||||
|
||||
## Features
|
||||
|
||||
- **Git-based plugins**: Clone plugins from any Git repository (GitHub, GitLab, etc.)
|
||||
- **Automatic skill discovery**: Skills are automatically found and registered from all installed plugins
|
||||
- **Configurable storage**: Plugin directory is configurable in System Settings
|
||||
- **Sync support**: Pull latest changes from plugin repositories
|
||||
- **Delete support**: Remove plugins when no longer needed
|
||||
- **AI integration**: Skills are automatically included in the system prompt and accessible via the `skill` tool
|
||||
|
||||
## User Interface
|
||||
|
||||
### AI Settings Page (`/settings/ai`)
|
||||
|
||||
The AI Settings page now includes a **Plugins** section with:
|
||||
|
||||
1. **Add Plugin**: Clone a new plugin by entering its Git URL
|
||||
2. **Plugin List**: View all installed plugins with their skills
|
||||
3. **Sync**: Pull latest changes from a plugin's Git repository
|
||||
4. **Delete**: Remove a plugin and all its skills
|
||||
|
||||
### System Settings Page (`/settings/system`)
|
||||
|
||||
The System Settings page includes a **Filesystem Paths** section where you can configure:
|
||||
|
||||
- **Plugins Directory**: Path where plugins are stored (default: `/plugins`)
|
||||
|
||||
## Plugin Structure
|
||||
|
||||
A plugin is a Git repository with the following structure:
|
||||
|
||||
```
|
||||
my-plugin/
|
||||
├── skills/
|
||||
│ ├── skill1/
|
||||
│ │ └── SKILL.md
|
||||
│ ├── skill2/
|
||||
│ │ └── SKILL.md
|
||||
│ └── ...
|
||||
└── README.md (optional)
|
||||
```
|
||||
|
||||
### Skill Format
|
||||
|
||||
Each skill is defined by a `SKILL.md` file with YAML frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: skillname
|
||||
description: A brief description of what this skill does
|
||||
---
|
||||
|
||||
# Skill Content
|
||||
|
||||
The rest of the file contains instructions, examples, and context
|
||||
that will be provided to the AI when this skill is invoked.
|
||||
|
||||
This can include:
|
||||
- Step-by-step workflows
|
||||
- Code examples
|
||||
- Best practices
|
||||
- Domain-specific knowledge
|
||||
```
|
||||
|
||||
#### Required Frontmatter Fields
|
||||
|
||||
- **`name`**: Skill identifier (must be lowercase alphanumeric with hyphens, e.g., `myskill`, `skill-123`, `condition-based-waiting`)
|
||||
- **`description`**: Human-readable description of what the skill does
|
||||
|
||||
#### Skill Name Validation
|
||||
|
||||
Skill names must:
|
||||
- Contain only lowercase letters (a-z), numbers (0-9), and hyphens (-)
|
||||
- No spaces, underscores, uppercase letters, or other special characters
|
||||
- Examples: ✅ `myskill`, `skill-123`, `condition-based-waiting` | ❌ `My-Skill`, `skill_name`, `SKILL`
|
||||
|
||||
## How It Works
|
||||
|
||||
### For Users
|
||||
|
||||
1. **Add a Plugin**:
|
||||
- Go to Settings > AI
|
||||
- Scroll to the Plugins section
|
||||
- Click "Add Plugin"
|
||||
- Enter the Git URL (e.g., `https://github.com/user/shakespeare-skills.git`)
|
||||
- Click "Add Plugin"
|
||||
|
||||
2. **View Skills**:
|
||||
- Installed plugins show the number of skills they contain
|
||||
- Expand a plugin to see all its skills with descriptions
|
||||
|
||||
3. **Sync a Plugin**:
|
||||
- Click the "Sync" button next to a plugin to pull latest changes
|
||||
- Useful when the plugin repository is updated with new skills
|
||||
|
||||
4. **Delete a Plugin**:
|
||||
- Click the "Delete" button next to a plugin to remove it
|
||||
- All skills from that plugin will no longer be available
|
||||
|
||||
### For the AI
|
||||
|
||||
The AI assistant automatically:
|
||||
|
||||
1. **Discovers Skills**: All skills from installed plugins are scanned on startup
|
||||
2. **Includes in System Prompt**: Skills are listed in the system prompt with their names, descriptions, and paths
|
||||
3. **Enforces Usage**: The system prompt instructs the AI to use skills whenever applicable
|
||||
4. **Accesses via Tool**: The AI calls the `skill` tool with a skill name to load its content
|
||||
|
||||
Example AI workflow:
|
||||
```
|
||||
User: "Help me build a Nostr marketplace"
|
||||
|
||||
AI: [Sees "nostrmarket" skill in system prompt]
|
||||
[Calls skill tool with name="nostrmarket"]
|
||||
[Receives SKILL.md content with marketplace implementation guide]
|
||||
[Follows the skill's instructions to build the marketplace]
|
||||
```
|
||||
|
||||
## Technical Implementation
|
||||
|
||||
### Key Files
|
||||
|
||||
- **`src/lib/plugins.ts`**: Core plugin and skill management functions
|
||||
- **`src/lib/tools/SkillTool.ts`**: AI tool for loading skill content
|
||||
- **`src/hooks/usePlugins.ts`**: React hook for plugin CRUD operations
|
||||
- **`src/components/PluginsSection.tsx`**: UI component for managing plugins
|
||||
- **`src/lib/system.ts`**: Updated to include skills in system prompt
|
||||
|
||||
### API
|
||||
|
||||
#### `getPlugins(fs, pluginsPath)`
|
||||
Returns array of plugin names (directory basenames).
|
||||
|
||||
#### `getAllSkills(fs, pluginsPath)`
|
||||
Returns array of all skills from all plugins.
|
||||
|
||||
#### `findSkill(fs, pluginsPath, skillName)`
|
||||
Finds a skill by name across all plugins.
|
||||
|
||||
#### `readSkillContent(fs, skill)`
|
||||
Reads the SKILL.md content for a skill.
|
||||
|
||||
#### `deletePlugin(fs, pluginsPath, pluginName)`
|
||||
Recursively deletes a plugin directory.
|
||||
|
||||
### Skill Tool
|
||||
|
||||
The `SkillTool` is exposed to the AI as the `skill` function:
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "skill",
|
||||
description: "Load and execute a skill from the configured plugins",
|
||||
parameters: {
|
||||
name: "The name of the skill to execute"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When called, it:
|
||||
1. Searches all plugins for a skill with the matching name
|
||||
2. Returns the full SKILL.md content
|
||||
3. Includes metadata (plugin name, description, path)
|
||||
|
||||
### Storage
|
||||
|
||||
Plugins are stored in the configured plugins directory:
|
||||
|
||||
- **Browser**: `/plugins` (IndexedDB via LightningFS)
|
||||
- **Electron (Windows)**: `~/AppData/Local/shakespeare/plugins`
|
||||
- **Electron (macOS)**: `~/Library/Application Support/shakespeare/plugins`
|
||||
- **Electron (Linux)**: `~/.config/shakespeare/plugins`
|
||||
|
||||
## System Prompt Integration
|
||||
|
||||
The system prompt now includes a **Skills** section that:
|
||||
|
||||
1. Lists all available skills with their names, descriptions, plugins, and paths
|
||||
2. Instructs the AI to use skills whenever applicable
|
||||
3. Provides the Settings > AI URL for users to configure skills
|
||||
4. Includes this section even when no skills are configured (to inform users about the feature)
|
||||
|
||||
Example system prompt section:
|
||||
|
||||
```
|
||||
## Skills
|
||||
|
||||
You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.
|
||||
|
||||
Available skills:
|
||||
|
||||
- **nostrmarket**: Build a Nostr marketplace application
|
||||
- Plugin: nostr-skills
|
||||
- Path: /plugins/nostr-skills/skills/nostrmarket
|
||||
|
||||
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.
|
||||
|
||||
Users can configure skills in Settings > AI (https://shakespeare.diy/settings/ai) by adding plugins that contain skills.
|
||||
```
|
||||
|
||||
## Creating Your Own Plugin
|
||||
|
||||
1. **Create a Git repository** with the plugin structure
|
||||
2. **Add skills** in the `skills/` directory
|
||||
3. **Write SKILL.md files** with frontmatter and content
|
||||
4. **Push to GitHub/GitLab** or any Git hosting service
|
||||
5. **Share the Git URL** with others to install your plugin
|
||||
|
||||
### Example Plugin Repository
|
||||
|
||||
```
|
||||
my-shakespeare-skills/
|
||||
├── README.md
|
||||
└── skills/
|
||||
├── webdesign/
|
||||
│ └── SKILL.md
|
||||
└── database/
|
||||
└── SKILL.md
|
||||
```
|
||||
|
||||
**skills/webdesign/SKILL.md**:
|
||||
```markdown
|
||||
---
|
||||
name: webdesign
|
||||
description: Create beautiful, modern web designs with best practices
|
||||
---
|
||||
|
||||
# Web Design Skill
|
||||
|
||||
When designing web interfaces, follow these principles:
|
||||
|
||||
1. **Use a consistent color palette** (3-5 colors + neutrals)
|
||||
2. **Implement proper spacing** (8px grid system)
|
||||
3. **Choose readable fonts** (18px+ for body text)
|
||||
4. **Ensure accessibility** (WCAG 2.1 AA compliance)
|
||||
|
||||
[... detailed instructions ...]
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Plugins Directory Path
|
||||
|
||||
Configure in **Settings > System > Filesystem Paths**:
|
||||
|
||||
- Default browser: `/plugins`
|
||||
- Default Electron: OS-specific (see Storage section)
|
||||
- Custom: Any absolute path
|
||||
|
||||
Changes take effect immediately.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Plugins must be Git repositories (no ZIP uploads)
|
||||
- Skills must be in `skills/` subdirectory
|
||||
- Skill names must be alphanumeric lowercase only
|
||||
- Each skill must have a `SKILL.md` file with required frontmatter
|
||||
- No automatic skill updates (users must manually sync)
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential future features:
|
||||
|
||||
- Plugin marketplace/registry
|
||||
- Automatic skill updates
|
||||
- Skill versioning
|
||||
- Skill dependencies
|
||||
- Plugin configuration files
|
||||
- Skill categories/tags
|
||||
- Skill search functionality
|
||||
- Plugin publishing workflow
|
||||
@@ -1,5 +0,0 @@
|
||||
package.json
|
||||
package-lock.json
|
||||
README.md
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -1,582 +0,0 @@
|
||||
# Shakespeare Electron - Complete Guide
|
||||
|
||||
This guide provides comprehensive documentation for developing, building, and troubleshooting the Shakespeare Electron desktop application.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Filesystem Architecture](#filesystem-architecture)
|
||||
2. [Terminal Integration](#terminal-integration)
|
||||
3. [Development Workflow](#development-workflow)
|
||||
4. [Building for Distribution](#building-for-distribution)
|
||||
5. [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
## Filesystem Architecture
|
||||
|
||||
### Overview
|
||||
|
||||
The Electron version uses your local OS filesystem at `~/shakespeare` instead of IndexedDB, providing direct file access and unlimited storage.
|
||||
|
||||
### Path Resolution
|
||||
|
||||
All paths are relative to `~/shakespeare`:
|
||||
- `/projects/my-app/` → `~/shakespeare/projects/my-app/`
|
||||
- `/tmp/upload.txt` → `~/shakespeare/tmp/upload.txt`
|
||||
- `/config/ai.json` → `~/shakespeare/config/ai.json`
|
||||
|
||||
### Implementation
|
||||
|
||||
**Automatic Adapter Selection** (`src/App.tsx`):
|
||||
```typescript
|
||||
const fs = window.electron?.isElectron
|
||||
? new NodeFSAdapter() // Real filesystem
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
```
|
||||
|
||||
**IPC Communication Flow:**
|
||||
1. **Renderer** (`NodeFSAdapter.ts`) - Calls `window.electron.fs.*` methods
|
||||
2. **Preload** (`preload.js`) - Exposes API via `contextBridge`
|
||||
3. **Main** (`main.js`) - Handles IPC with `ipcMain.handle()`, performs filesystem operations
|
||||
|
||||
### Supported Operations
|
||||
|
||||
All standard filesystem operations are supported:
|
||||
- **Files**: `readFile`, `writeFile`, `unlink`, `rename`
|
||||
- **Directories**: `readdir`, `mkdir`, `rmdir`
|
||||
- **Metadata**: `stat`, `lstat`
|
||||
- **Symlinks**: `readlink`, `symlink`
|
||||
|
||||
### Benefits
|
||||
|
||||
✅ **No storage limits** - Only limited by disk space
|
||||
✅ **Direct access** - Use any editor, file manager, or Git client
|
||||
✅ **Easy backup** - Standard backup tools work
|
||||
✅ **Better performance** - Faster for large projects
|
||||
✅ **Data portability** - Copy projects between machines
|
||||
|
||||
### Data Migration
|
||||
|
||||
**Browser to Electron:**
|
||||
1. Export project as ZIP from browser
|
||||
2. Import ZIP in Electron version
|
||||
|
||||
**Electron to Browser:**
|
||||
1. Export project as ZIP from Electron
|
||||
2. Import ZIP in browser version
|
||||
|
||||
---
|
||||
|
||||
## Terminal Integration
|
||||
|
||||
### Overview
|
||||
|
||||
The Electron version uses the **real OS terminal** instead of the virtual terminal, providing access to all system commands.
|
||||
|
||||
### Architecture
|
||||
|
||||
**ShellTool Detection** (`src/lib/tools/ShellTool.ts`):
|
||||
```typescript
|
||||
if (window.electron?.shell) {
|
||||
// Use real OS shell
|
||||
const result = await window.electron.shell.exec(command, workingDir);
|
||||
} else {
|
||||
// Use virtual command system
|
||||
const result = await executeCommand(command, workingDir, fs);
|
||||
}
|
||||
```
|
||||
|
||||
**Shell Execution** (`electron/main.js`):
|
||||
- Uses `child_process.spawn()` to execute commands
|
||||
- Windows: Uses `cmd.exe`
|
||||
- macOS/Linux: Uses `/bin/sh`
|
||||
- Executes in project directory: `~/shakespeare/projects/{projectId}`
|
||||
|
||||
### Features
|
||||
|
||||
**All OS Commands Available:**
|
||||
```bash
|
||||
# Package managers
|
||||
$ npm install
|
||||
$ yarn add lodash
|
||||
$ pnpm update
|
||||
|
||||
# Build tools
|
||||
$ vite build
|
||||
$ webpack --config webpack.config.js
|
||||
$ tsc --noEmit
|
||||
|
||||
# Git operations
|
||||
$ git commit -m "Update"
|
||||
$ git push origin main
|
||||
|
||||
# System utilities
|
||||
$ grep -r "TODO" src/
|
||||
$ curl https://api.example.com
|
||||
$ python script.py
|
||||
```
|
||||
|
||||
**Native Shell Features:**
|
||||
- Pipes: `ls | grep ".ts$"`
|
||||
- Redirection: `echo "test" > file.txt`
|
||||
- Environment variables: `$PATH`, `$HOME`
|
||||
- Command chaining: `npm install && npm run build`
|
||||
|
||||
### ANSI Code Stripping
|
||||
|
||||
Output from shell commands is cleaned for AI consumption:
|
||||
- Color codes removed (e.g., `\u001b[31m`)
|
||||
- Cursor control sequences stripped
|
||||
- Text formatting removed (bold, italic)
|
||||
- Newlines preserved
|
||||
|
||||
**Example:**
|
||||
```
|
||||
Input: \u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s
|
||||
Output: added 142 packages in 3s
|
||||
```
|
||||
|
||||
Terminal UI still shows colored output for users.
|
||||
|
||||
### Platform Support
|
||||
|
||||
| Platform | Shell | Notes |
|
||||
|----------|-------|-------|
|
||||
| macOS | `/bin/sh` | All Unix commands available |
|
||||
| Linux | `/bin/sh` | Standard Linux utilities |
|
||||
| Windows | `cmd.exe` | Windows commands, consider Git Bash for Unix tools |
|
||||
|
||||
### Security
|
||||
|
||||
- Commands run with user permissions (no sudo/elevation)
|
||||
- Working directory sandboxed to `~/shakespeare`
|
||||
- Environment variables inherited from Electron process
|
||||
|
||||
---
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Running in Development Mode
|
||||
|
||||
```bash
|
||||
npm run electron:dev
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Start Vite dev server on http://localhost:5173
|
||||
2. Wait for server to be ready
|
||||
3. Launch Electron with hot reload
|
||||
4. Open DevTools automatically
|
||||
|
||||
### Testing Shell Execution
|
||||
|
||||
Use the provided test script to verify shell functionality:
|
||||
|
||||
```bash
|
||||
# Start Electron in dev mode
|
||||
npm run electron:dev
|
||||
|
||||
# Open DevTools (View > Toggle Developer Tools)
|
||||
# Paste contents of electron/test-terminal.js into console
|
||||
```
|
||||
|
||||
The test script verifies:
|
||||
- Basic command execution
|
||||
- File listing
|
||||
- Node.js version check
|
||||
- Error handling
|
||||
- Working directory
|
||||
|
||||
### Debugging
|
||||
|
||||
**Renderer Process:**
|
||||
- DevTools open automatically in dev mode
|
||||
- Or press `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux)
|
||||
|
||||
**Main Process:**
|
||||
```bash
|
||||
# Enable verbose logging
|
||||
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
|
||||
```
|
||||
|
||||
**Check Configuration:**
|
||||
```bash
|
||||
node electron/test-config.js
|
||||
```
|
||||
|
||||
### File Watching
|
||||
|
||||
In development mode:
|
||||
- Vite provides hot module replacement
|
||||
- Changes to React components reload instantly
|
||||
- Electron process restarts on main.js changes (via `nodemon` in the script)
|
||||
|
||||
---
|
||||
|
||||
## Building for Distribution
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+ installed
|
||||
- All dependencies installed: `npm install`
|
||||
- Web build completed: `npm run build`
|
||||
|
||||
### Build Commands
|
||||
|
||||
**Current Platform:**
|
||||
```bash
|
||||
npm run electron:build
|
||||
```
|
||||
|
||||
**Specific Platforms:**
|
||||
```bash
|
||||
npm run electron:build:mac # macOS (DMG + ZIP)
|
||||
npm run electron:build:win # Windows (NSIS + Portable)
|
||||
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
|
||||
npm run electron:build:all # All platforms
|
||||
```
|
||||
|
||||
### Build Output
|
||||
|
||||
```
|
||||
electron-dist/
|
||||
├── mac/
|
||||
│ ├── Shakespeare.app # macOS application bundle
|
||||
│ ├── Shakespeare.dmg # DMG installer
|
||||
│ └── Shakespeare-mac.zip # ZIP archive
|
||||
├── win-unpacked/
|
||||
│ └── Shakespeare.exe # Windows executable
|
||||
├── Shakespeare Setup.exe # NSIS installer
|
||||
├── Shakespeare Portable.exe # Portable executable
|
||||
├── shakespeare-*.AppImage # Linux AppImage
|
||||
├── shakespeare_*.deb # Debian package
|
||||
└── shakespeare-*.rpm # RPM package
|
||||
```
|
||||
|
||||
### Platform-Specific Notes
|
||||
|
||||
**macOS:**
|
||||
- Builds for Intel (x64) and Apple Silicon (arm64)
|
||||
- Code signing optional for development
|
||||
- For distribution: Requires Apple Developer account
|
||||
|
||||
**Windows:**
|
||||
- Builds for x64 and ARM64
|
||||
- No code signing required for development
|
||||
- For distribution: EV certificate recommended for SmartScreen
|
||||
|
||||
**Linux:**
|
||||
- Builds for x64 and ARM64
|
||||
- AppImage requires FUSE: `sudo apt-get install fuse`
|
||||
- DEB/RPM packages can be installed with package managers
|
||||
|
||||
### Cross-Platform Limitations
|
||||
|
||||
- **macOS builds require macOS** (for code signing)
|
||||
- Windows/Linux can be built from any platform
|
||||
- Use GitHub Actions or CI/CD for multi-platform builds
|
||||
|
||||
### Code Signing
|
||||
|
||||
**Development (Disable Signing):**
|
||||
|
||||
Edit `electron/builder.config.js`:
|
||||
```javascript
|
||||
mac: {
|
||||
identity: null, // Disable code signing
|
||||
}
|
||||
```
|
||||
|
||||
**Production (macOS):**
|
||||
1. Obtain Apple Developer account
|
||||
2. Create certificates in Xcode
|
||||
3. Configure signing in builder.config.js
|
||||
4. See: https://www.electron.build/code-signing
|
||||
|
||||
**Production (Windows):**
|
||||
1. Obtain EV code signing certificate
|
||||
2. Configure in builder.config.js
|
||||
3. Builds reputation with SmartScreen over time
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Development Issues
|
||||
|
||||
#### Port 5173 Already in Use
|
||||
|
||||
**Solution:**
|
||||
```bash
|
||||
# Find and kill the process
|
||||
lsof -i :5173 # macOS/Linux
|
||||
netstat -ano | findstr :5173 # Windows
|
||||
|
||||
# Or change the port in vite.config.ts
|
||||
export default defineConfig({
|
||||
server: { port: 5174 },
|
||||
});
|
||||
```
|
||||
|
||||
#### Blank Screen on Launch
|
||||
|
||||
**Browser Mode:**
|
||||
1. Check Vite server is running: http://localhost:5173
|
||||
2. Check Electron console for errors
|
||||
3. Verify URL in `electron/main.js` matches Vite server
|
||||
4. Clear cache: Delete `node_modules/.vite`
|
||||
|
||||
**Production Build:**
|
||||
1. Ensure `base: './'` is set in `vite.config.ts`
|
||||
2. Check `dist/` directory contains all files
|
||||
3. Look for "Failed to load resource" errors in console
|
||||
4. Verify file:// protocol is used in loadURL
|
||||
|
||||
#### Assets Fail to Load: "net::ERR_FILE_NOT_FOUND"
|
||||
|
||||
**Problem:** CSS/JS fail to load with `file:///assets/npm/...` errors
|
||||
|
||||
**Solution:** Add to `vite.config.ts`:
|
||||
```typescript
|
||||
export default defineConfig(() => ({
|
||||
base: './', // Required for Electron
|
||||
// ... rest of config
|
||||
}))
|
||||
```
|
||||
|
||||
Then rebuild: `npm run build`
|
||||
|
||||
#### 404 Error: Page Not Found
|
||||
|
||||
**Problem:** App shows "404: Oops! Page not found" on launch
|
||||
|
||||
**Solution:** Verify `HashRouter` is used in Electron.
|
||||
|
||||
Check `src/AppRouter.tsx`:
|
||||
```typescript
|
||||
const Router = window.electron?.isElectron ? HashRouter : BrowserRouter;
|
||||
```
|
||||
|
||||
Rebuild: `npm run build && npm run electron:build`
|
||||
|
||||
#### Service Worker Errors
|
||||
|
||||
**Solution:** Service workers don't work with `file://` protocol.
|
||||
|
||||
Check `src/main.tsx`:
|
||||
```typescript
|
||||
if ('serviceWorker' in navigator && !window.electron?.isElectron) {
|
||||
// Only register in web environment
|
||||
}
|
||||
```
|
||||
|
||||
#### CSP Font Errors
|
||||
|
||||
**Solution:** Update CSP in `index.html`:
|
||||
```html
|
||||
<meta http-equiv="content-security-policy"
|
||||
content="... font-src 'self' data:; ...">
|
||||
```
|
||||
|
||||
#### Broken SVG Images
|
||||
|
||||
**Problem:** Logo/SVG files show as broken
|
||||
|
||||
**Solution:** Import SVG files properly:
|
||||
```typescript
|
||||
// ❌ Wrong
|
||||
<img src="/shakespeare.svg" alt="Logo" />
|
||||
|
||||
// ✅ Correct
|
||||
import logo from '/shakespeare.svg?url';
|
||||
<img src={logo} alt="Logo" />
|
||||
```
|
||||
|
||||
#### Preload Script ESM Errors
|
||||
|
||||
**Solution:** Requires `sandbox: false` in webPreferences.
|
||||
|
||||
Check `electron/main.js`:
|
||||
```javascript
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true, // Still enabled
|
||||
sandbox: false, // Disabled for ESM
|
||||
webSecurity: true,
|
||||
}
|
||||
```
|
||||
|
||||
### Build Issues
|
||||
|
||||
#### Build Fails with "Cannot find module"
|
||||
|
||||
**Solutions:**
|
||||
1. Install dependencies: `npm install`
|
||||
2. Clear and reinstall: `rm -rf node_modules package-lock.json && npm install`
|
||||
3. Build web first: `npm run build`
|
||||
4. Verify `dist/` exists
|
||||
5. Check config: `node electron/test-config.js`
|
||||
|
||||
#### Icons Not Appearing
|
||||
|
||||
**Solution:** Should work automatically with `public/shakespeare-512x512.png`.
|
||||
|
||||
If not:
|
||||
1. Verify PNG exists
|
||||
2. Check build output for icon errors
|
||||
3. Try: `npm run electron:icons` (requires ImageMagick)
|
||||
4. Check paths in `electron/builder.config.js`
|
||||
|
||||
#### Code Signing Errors (macOS)
|
||||
|
||||
**Development:** Disable signing:
|
||||
```javascript
|
||||
mac: {
|
||||
identity: null,
|
||||
}
|
||||
```
|
||||
|
||||
**Production:** Requires Apple Developer account and certificates.
|
||||
|
||||
#### App Won't Launch After Build
|
||||
|
||||
**Solutions:**
|
||||
1. Check console/terminal for errors
|
||||
2. Try unpacked version first
|
||||
3. macOS: Check Security & Privacy settings
|
||||
4. Windows: Check Windows Defender logs
|
||||
5. Verify `dist/` contains valid files
|
||||
|
||||
### Runtime Issues
|
||||
|
||||
#### App Crashes on Startup
|
||||
|
||||
**Solutions:**
|
||||
1. Check crash logs:
|
||||
- macOS: `~/Library/Logs/Shakespeare/`
|
||||
- Windows: `%APPDATA%\Shakespeare\logs\`
|
||||
- Linux: `~/.config/Shakespeare/logs/`
|
||||
2. Run from terminal to see errors
|
||||
3. Test web build in browser first
|
||||
|
||||
#### Shell Execution Error: "spawn /bin/sh ENOENT"
|
||||
|
||||
**Problem:** Terminal commands fail with spawn error
|
||||
|
||||
**Root Cause:** Working directory doesn't exist
|
||||
|
||||
**Solution:** Should be fixed - main.js creates directories automatically.
|
||||
|
||||
**Debug:**
|
||||
1. Open DevTools
|
||||
2. Check console for "Shell exec in directory: ..."
|
||||
3. Verify directory exists: `ls -la ~/shakespeare/projects/`
|
||||
4. Manually create if needed: `mkdir -p ~/shakespeare/projects`
|
||||
|
||||
#### External Links Not Opening
|
||||
|
||||
**Solution:** Should open in default browser automatically.
|
||||
|
||||
Check `electron/main.js` has:
|
||||
```javascript
|
||||
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
```
|
||||
|
||||
### Platform-Specific Issues
|
||||
|
||||
#### macOS: "App is damaged and can't be opened"
|
||||
|
||||
**Solutions:**
|
||||
1. Development: `xattr -cr /path/to/Shakespeare.app`
|
||||
2. Distribution: Requires code signing
|
||||
3. Users: Right-click → Open (instead of double-click)
|
||||
|
||||
#### Windows: "Windows protected your PC"
|
||||
|
||||
**Solutions:**
|
||||
1. Testing: Click "More info" → "Run anyway"
|
||||
2. Distribution: Requires EV code signing
|
||||
3. Build reputation over time
|
||||
|
||||
#### Linux: "Permission denied"
|
||||
|
||||
**Solutions:**
|
||||
1. Make executable: `chmod +x Shakespeare*.AppImage`
|
||||
2. Install FUSE: `sudo apt-get install fuse`
|
||||
3. Try DEB/RPM package instead
|
||||
|
||||
### Performance Issues
|
||||
|
||||
#### App Feels Slow
|
||||
|
||||
**Solutions:**
|
||||
1. Close DevTools
|
||||
2. Check system resources
|
||||
3. Use production build
|
||||
4. Disable hardware acceleration in `main.js`:
|
||||
```javascript
|
||||
app.disableHardwareAcceleration();
|
||||
```
|
||||
|
||||
#### High Memory Usage
|
||||
|
||||
**Solutions:**
|
||||
1. Normal for Chromium-based apps
|
||||
2. Close unused projects
|
||||
3. Restart app periodically
|
||||
4. Check for memory leaks in web code
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
If issues persist:
|
||||
|
||||
1. **Check existing issues:** https://gitlab.com/soapbox-pub/shakespeare/-/issues
|
||||
2. **Create new issue** with:
|
||||
- OS and version
|
||||
- Electron version: `npm list electron`
|
||||
- Steps to reproduce
|
||||
- Error messages/logs
|
||||
- Screenshots
|
||||
3. **Community support:** Check project README for links
|
||||
|
||||
## Useful Commands
|
||||
|
||||
**Complete rebuild:**
|
||||
```bash
|
||||
rm -rf node_modules dist electron-dist package-lock.json
|
||||
npm install
|
||||
npm run build
|
||||
npm run electron:build
|
||||
```
|
||||
|
||||
**Check versions:**
|
||||
```bash
|
||||
npm list electron
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
**Verbose logging:**
|
||||
```bash
|
||||
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
|
||||
```
|
||||
|
||||
**Check build contents:**
|
||||
```bash
|
||||
npm run electron:build -- --dir
|
||||
ls -la electron-dist/[platform]-unpacked/
|
||||
```
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Documentation](https://www.electronjs.org/docs)
|
||||
- [electron-builder Documentation](https://www.electron.build/)
|
||||
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security)
|
||||
- [Debugging Electron](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process)
|
||||
- [Shakespeare Main Docs](../README.md)
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
import electron from 'electron';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const appPath = join(__dirname, '..');
|
||||
|
||||
const child = spawn(electron, [appPath], {
|
||||
stdio: 'inherit',
|
||||
windowsHide: false,
|
||||
});
|
||||
|
||||
child.on('close', code => process.exit(code ?? 0));
|
||||
child.on('error', err => {
|
||||
console.error('Failed to launch Electron:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => child.kill('SIGINT'));
|
||||
process.on('SIGTERM', () => child.kill('SIGTERM'));
|
||||
Vendored
-99
@@ -1,99 +0,0 @@
|
||||
/**
|
||||
* TypeScript definitions for the Electron API exposed to the renderer process.
|
||||
*
|
||||
* Add this to your tsconfig.json include array to use these types:
|
||||
* "include": ["src", "electron/electron.d.ts"]
|
||||
*/
|
||||
|
||||
interface DirectoryEntry {
|
||||
name: string;
|
||||
isDirectory: boolean;
|
||||
isFile: boolean;
|
||||
}
|
||||
|
||||
interface StatResult {
|
||||
isDirectory: boolean;
|
||||
isFile: boolean;
|
||||
isBlockDevice: boolean;
|
||||
isCharacterDevice: boolean;
|
||||
isSymbolicLink: boolean;
|
||||
isFIFO: boolean;
|
||||
isSocket: boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
// Timestamps (serialized as numbers for IPC)
|
||||
mtime: number;
|
||||
ctime: number;
|
||||
atime: number;
|
||||
}
|
||||
|
||||
interface ElectronFSAPI {
|
||||
readFile(path: string, encoding?: string): Promise<string | number[]>;
|
||||
writeFile(path: string, data: string | number[], encoding?: string): Promise<void>;
|
||||
readdir(path: string, withFileTypes?: boolean): Promise<string[] | DirectoryEntry[]>;
|
||||
mkdir(path: string, recursive?: boolean): Promise<void>;
|
||||
stat(path: string): Promise<StatResult>;
|
||||
lstat(path: string): Promise<StatResult>;
|
||||
unlink(path: string): Promise<void>;
|
||||
rmdir(path: string): Promise<void>;
|
||||
rename(oldPath: string, newPath: string): Promise<void>;
|
||||
readlink(path: string): Promise<string>;
|
||||
symlink(target: string, path: string): Promise<void>;
|
||||
}
|
||||
|
||||
interface ShellExecResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
interface ElectronShellAPI {
|
||||
/**
|
||||
* Execute a shell command on the host OS.
|
||||
* @param command - The command to execute
|
||||
* @param cwd - Working directory (relative to ~/shakespeare)
|
||||
* @returns Promise with stdout, stderr, and exit code
|
||||
*/
|
||||
exec(command: string, cwd?: string): Promise<ShellExecResult>;
|
||||
}
|
||||
|
||||
interface ElectronAPI {
|
||||
/**
|
||||
* Get the user's home directory path.
|
||||
*/
|
||||
homedir: string;
|
||||
|
||||
/**
|
||||
* Get the current platform.
|
||||
* @returns 'darwin' | 'win32' | 'linux'
|
||||
*/
|
||||
platform(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Get the application version from package.json.
|
||||
* @returns Version string (e.g., "1.0.0")
|
||||
*/
|
||||
version(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Filesystem API for accessing the local OS filesystem.
|
||||
* All paths are relative to ~/shakespeare directory.
|
||||
*/
|
||||
fs: ElectronFSAPI;
|
||||
|
||||
/**
|
||||
* Shell API for executing real shell commands on the host OS.
|
||||
* All paths in commands are relative to ~/shakespeare directory.
|
||||
*/
|
||||
shell: ElectronShellAPI;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
/**
|
||||
* Electron API exposed via preload script.
|
||||
* Only available when running in Electron.
|
||||
*/
|
||||
electron?: ElectronAPI;
|
||||
}
|
||||
@@ -1,532 +0,0 @@
|
||||
import { app, BrowserWindow, ipcMain, shell, Menu, protocol } from 'electron';
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs/promises';
|
||||
import os from 'os';
|
||||
|
||||
// ESM equivalent of __dirname
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
let mainWindow;
|
||||
|
||||
function createWindow() {
|
||||
// Remove the default menu (File, Edit, View, etc.)
|
||||
Menu.setApplicationMenu(null);
|
||||
|
||||
// Create the browser window.
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1400,
|
||||
height: 900,
|
||||
minWidth: 800,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
sandbox: false, // Disabled to support ESM in preload
|
||||
webSecurity: true,
|
||||
},
|
||||
icon: path.join(__dirname, 'dist/shakespeare-512x512.png'),
|
||||
title: 'Shakespeare',
|
||||
backgroundColor: '#ffffff',
|
||||
});
|
||||
|
||||
// Enable DevTools keyboard shortcut (Ctrl+Shift+I / Cmd+Option+I)
|
||||
mainWindow.webContents.on('before-input-event', (event, input) => {
|
||||
// Check for Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac)
|
||||
if (input.control && input.shift && input.key.toLowerCase() === 'i') {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
}
|
||||
// Also support F12
|
||||
if (input.key === 'F12') {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Load the app
|
||||
if (process.env.ELECTRON_DEV) {
|
||||
// Development mode - load from Vite dev server
|
||||
console.log('Loading from Vite dev server: http://localhost:5173');
|
||||
mainWindow.loadURL('http://localhost:5173');
|
||||
mainWindow.webContents.openDevTools();
|
||||
} else {
|
||||
// Production mode - load from custom protocol
|
||||
// This allows absolute paths like /shakespeare.svg to work naturally
|
||||
console.log('Loading from app:// protocol: app://./index.html');
|
||||
mainWindow.loadURL('app://./index.html');
|
||||
}
|
||||
|
||||
// Log any load errors
|
||||
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
|
||||
console.error('Failed to load:', validatedURL, errorCode, errorDescription);
|
||||
});
|
||||
|
||||
// Log successful load
|
||||
mainWindow.webContents.on('did-finish-load', () => {
|
||||
console.log('Successfully loaded app');
|
||||
});
|
||||
|
||||
// Handle window close
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
|
||||
// Register custom protocol scheme before app is ready (required for privileges)
|
||||
if (!process.env.ELECTRON_DEV) {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: 'app',
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
// This method will be called when Electron has finished
|
||||
// initialization and is ready to create browser windows.
|
||||
app.whenReady().then(async () => {
|
||||
// Register the app:// protocol to serve files from dist/
|
||||
// This allows absolute paths (/) to work naturally without base: './'
|
||||
if (!process.env.ELECTRON_DEV) {
|
||||
protocol.registerFileProtocol('app', (request, callback) => {
|
||||
// Remove 'app://' prefix and normalize path
|
||||
let filePath = request.url.replace('app://', '');
|
||||
|
||||
// Remove trailing slashes
|
||||
filePath = filePath.replace(/\/+$/, '');
|
||||
|
||||
// Handle root path
|
||||
if (filePath === '' || filePath === '/') {
|
||||
filePath = 'index.html';
|
||||
}
|
||||
|
||||
// Remove leading slash if present
|
||||
if (filePath.startsWith('/')) {
|
||||
filePath = filePath.substring(1);
|
||||
}
|
||||
|
||||
// Resolve to dist directory
|
||||
const fullPath = path.join(__dirname, 'dist', filePath);
|
||||
|
||||
console.log('Protocol handler:', request.url, '->', fullPath);
|
||||
callback({ path: fullPath });
|
||||
});
|
||||
}
|
||||
|
||||
createWindow();
|
||||
|
||||
app.on('activate', () => {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Quit when all windows are closed, except on macOS.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle app-level events
|
||||
app.on('web-contents-created', (event, contents) => {
|
||||
// Security: Prevent navigation to external sites
|
||||
contents.on('will-navigate', (event, navigationUrl) => {
|
||||
const parsedUrl = new URL(navigationUrl);
|
||||
|
||||
// Allow navigation within the app
|
||||
if (parsedUrl.origin === 'http://localhost:5173' ||
|
||||
parsedUrl.protocol === 'file:') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Block all other navigation
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
// Security: Prevent opening new windows
|
||||
contents.setWindowOpenHandler(({ url }) => {
|
||||
// Open external links in the default browser
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
});
|
||||
|
||||
// IPC handlers can be added here if needed for future Electron-specific features
|
||||
// For example: file system access, native dialogs, etc.
|
||||
|
||||
// Example: Handle getting app version
|
||||
ipcMain.handle('get-app-version', () => {
|
||||
return app.getVersion();
|
||||
});
|
||||
|
||||
// Example: Handle getting platform
|
||||
ipcMain.handle('get-platform', () => {
|
||||
return process.platform;
|
||||
});
|
||||
|
||||
// Helper function to expand tilde (~) in paths
|
||||
function expandTilde(filepath) {
|
||||
if (filepath.startsWith('~/') || filepath === '~') {
|
||||
return path.join(os.homedir(), filepath.slice(1));
|
||||
}
|
||||
return filepath;
|
||||
}
|
||||
|
||||
// Filesystem IPC handlers
|
||||
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to read file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
// Don't log - empty paths are expected from isomorphic-git's ref resolution
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const data = await fs.readFile(fullPath, encoding ? { encoding } : undefined);
|
||||
// If no encoding, convert Buffer to array for IPC serialization
|
||||
return encoding ? data : Array.from(data);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// Serialize the error code as a regular property so it survives IPC
|
||||
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
|
||||
// Copy enumerable properties including code
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
|
||||
// Only log unexpected errors
|
||||
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:writeFile', async (event, filePath, data, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to write file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
// Convert array back to Buffer if needed
|
||||
const dataToWrite = Array.isArray(data) ? Buffer.from(data) : data;
|
||||
await fs.writeFile(fullPath, dataToWrite, encoding ? { encoding } : undefined);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to write file ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
const entries = await fs.readdir(fullPath, { withFileTypes: !!withFileTypes });
|
||||
|
||||
if (withFileTypes) {
|
||||
// Convert Dirent objects to plain objects for IPC
|
||||
return entries.map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: entry.isDirectory(),
|
||||
isFile: entry.isFile(),
|
||||
}));
|
||||
}
|
||||
|
||||
return entries;
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
|
||||
if (error.code !== 'ENOTDIR') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:mkdir', async (event, dirPath, recursive) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
await fs.mkdir(fullPath, { recursive: !!recursive });
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to create directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:stat', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const stats = await fs.stat(fullPath);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: stats.isDirectory(),
|
||||
isFile: stats.isFile(),
|
||||
isBlockDevice: stats.isBlockDevice(),
|
||||
isCharacterDevice: stats.isCharacterDevice(),
|
||||
isSymbolicLink: stats.isSymbolicLink(),
|
||||
isFIFO: stats.isFIFO(),
|
||||
isSocket: stats.isSocket(),
|
||||
size: stats.size,
|
||||
mtimeMs: stats.mtimeMs ?? now,
|
||||
ctimeMs: stats.ctimeMs ?? now,
|
||||
atimeMs: stats.atimeMs ?? now,
|
||||
// Date objects need to be serialized as timestamps for IPC
|
||||
// Use optional chaining and fallback to now to prevent valueOf errors
|
||||
mtime: stats.mtime?.getTime() ?? now,
|
||||
ctime: stats.ctime?.getTime() ?? now,
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:lstat', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const stats = await fs.lstat(fullPath);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: stats.isDirectory(),
|
||||
isFile: stats.isFile(),
|
||||
isBlockDevice: stats.isBlockDevice(),
|
||||
isCharacterDevice: stats.isCharacterDevice(),
|
||||
isSymbolicLink: stats.isSymbolicLink(),
|
||||
isFIFO: stats.isFIFO(),
|
||||
isSocket: stats.isSocket(),
|
||||
size: stats.size,
|
||||
mtimeMs: stats.mtimeMs ?? now,
|
||||
ctimeMs: stats.ctimeMs ?? now,
|
||||
atimeMs: stats.atimeMs ?? now,
|
||||
// Date objects need to be serialized as timestamps for IPC
|
||||
// Use optional chaining and fallback to now to prevent valueOf errors
|
||||
mtime: stats.mtime?.getTime() ?? now,
|
||||
ctime: stats.ctime?.getTime() ?? now,
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:unlink', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
await fs.unlink(fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:rmdir', async (event, dirPath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
await fs.rmdir(fullPath);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to remove directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:rename', async (event, oldPath, newPath) => {
|
||||
try {
|
||||
const fullOldPath = expandTilde(oldPath);
|
||||
const fullNewPath = expandTilde(newPath);
|
||||
// Ensure parent directory of new path exists
|
||||
await fs.mkdir(path.dirname(fullNewPath), { recursive: true });
|
||||
await fs.rename(fullOldPath, fullNewPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to rename ${oldPath} to ${newPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:readlink', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
return await fs.readlink(fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to read link ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:symlink', async (event, target, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
await fs.symlink(target, fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to create symlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// Shell execution handler
|
||||
ipcMain.handle('shell:exec', async (event, command, cwd) => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
// Determine the shell and command execution method based on platform
|
||||
const isWindows = process.platform === 'win32';
|
||||
const shellCmd = isWindows ? 'cmd.exe' : '/bin/sh';
|
||||
const shellArgs = isWindows ? ['/c', command] : ['-c', command];
|
||||
|
||||
// Expand tilde in working directory if provided, otherwise use home directory
|
||||
const workingDir = cwd ? expandTilde(cwd) : os.homedir();
|
||||
|
||||
// Ensure the working directory exists before spawning
|
||||
try {
|
||||
await fs.mkdir(workingDir, { recursive: true });
|
||||
console.log(`Shell exec in directory: ${workingDir}`);
|
||||
console.log(`Command: ${command}`);
|
||||
} catch (mkdirError) {
|
||||
console.warn(`Failed to create directory ${workingDir}:`, mkdirError.message);
|
||||
// Continue anyway - directory might already exist
|
||||
}
|
||||
|
||||
const child = spawn(shellCmd, shellArgs, {
|
||||
cwd: workingDir,
|
||||
env: { ...process.env },
|
||||
shell: false, // We're already using the shell
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
child.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
console.error('Shell execution error:', error);
|
||||
console.error('Working directory:', workingDir);
|
||||
console.error('Shell command:', shellCmd);
|
||||
console.error('Shell args:', shellArgs);
|
||||
reject(new Error(`Failed to execute command: ${error.message} (cwd: ${workingDir})`));
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode: code ?? 0,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Shell setup error:', error);
|
||||
reject(new Error(`Failed to setup shell execution: ${error.message}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
import os from 'node:os';
|
||||
|
||||
// Expose protected methods that allow the renderer process to use
|
||||
// ipcRenderer without exposing the entire object
|
||||
contextBridge.exposeInMainWorld('electron', {
|
||||
// Get the home directory
|
||||
homedir: os.homedir(),
|
||||
|
||||
// Platform information
|
||||
platform: () => ipcRenderer.invoke('get-platform'),
|
||||
|
||||
// App version
|
||||
version: () => ipcRenderer.invoke('get-app-version'),
|
||||
|
||||
// Filesystem API - paths support tilde (~) expansion for home directory
|
||||
fs: {
|
||||
readFile: (path, encoding) => ipcRenderer.invoke('fs:readFile', path, encoding),
|
||||
writeFile: (path, data, encoding) => ipcRenderer.invoke('fs:writeFile', path, data, encoding),
|
||||
readdir: (path, withFileTypes) => ipcRenderer.invoke('fs:readdir', path, withFileTypes),
|
||||
mkdir: (path, recursive) => ipcRenderer.invoke('fs:mkdir', path, recursive),
|
||||
stat: (path) => ipcRenderer.invoke('fs:stat', path),
|
||||
lstat: (path) => ipcRenderer.invoke('fs:lstat', path),
|
||||
unlink: (path) => ipcRenderer.invoke('fs:unlink', path),
|
||||
rmdir: (path) => ipcRenderer.invoke('fs:rmdir', path),
|
||||
rename: (oldPath, newPath) => ipcRenderer.invoke('fs:rename', oldPath, newPath),
|
||||
readlink: (path) => ipcRenderer.invoke('fs:readlink', path),
|
||||
symlink: (target, path) => ipcRenderer.invoke('fs:symlink', target, path),
|
||||
},
|
||||
|
||||
// Shell API - execute real shell commands
|
||||
shell: {
|
||||
exec: (command, cwd) => ipcRenderer.invoke('shell:exec', command, cwd),
|
||||
},
|
||||
});
|
||||
+1
-1
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist", "electron/dist"] },
|
||||
{ ignores: ["dist"] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
|
||||
Generated
+115
-4900
File diff suppressed because it is too large.
Load diff
+6
-22
@@ -1,25 +1,14 @@
|
||||
{
|
||||
"name": "shakespeare.diy",
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"homepage": "https://shakespeare.diy",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"name": "mkstack",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://gitlab.com/soapbox-pub/shakespeare.git"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "npm i --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"typecheck": "npm i --silent && tsc --noEmit",
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && electron electron",
|
||||
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -28,10 +17,11 @@
|
||||
"@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": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.5",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.9",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -59,7 +49,6 @@
|
||||
"@radix-ui/react-toggle": "^1.1.0",
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@sentry/react": "^10.22.0",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
@@ -71,7 +60,6 @@
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"gray-matter": "^4.0.3",
|
||||
"i18next": "^25.5.2",
|
||||
"ignore": "^7.0.5",
|
||||
"input-otp": "^1.2.4",
|
||||
@@ -88,7 +76,6 @@
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-error-boundary": "^6.0.0",
|
||||
"react-hook-form": "^7.53.0",
|
||||
"react-i18next": "^15.7.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -105,7 +92,6 @@
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"workbox-window": "^7.3.0",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -127,7 +113,6 @@
|
||||
"@types/uri-templates": "^0.1.34",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"electron": "^39.0.0",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.9",
|
||||
@@ -138,7 +123,6 @@
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
"vitest": "^3.1.4"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
});
|
||||
@@ -1,78 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFileSync, writeFileSync, copyFileSync, rmSync, cpSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const rootDir = join(__dirname, '..');
|
||||
const electronDir = join(rootDir, 'electron');
|
||||
const distDir = join(rootDir, 'dist');
|
||||
const electronDistDir = join(electronDir, 'dist');
|
||||
|
||||
// Read root package.json
|
||||
const rootPackage = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
|
||||
|
||||
// Generate CalVer version (YYYY.MM.DDHHMM) in UTC
|
||||
const now = new Date();
|
||||
const year = now.getUTCFullYear();
|
||||
const month = String(now.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getUTCDate()).padStart(2, '0');
|
||||
const hour = String(now.getUTCHours()).padStart(2, '0');
|
||||
const minute = String(now.getUTCMinutes()).padStart(2, '0');
|
||||
const version = `${year}.${month}.${day}${hour}${minute}`;
|
||||
|
||||
// Get electron version from root devDependencies
|
||||
const electronVersion = rootPackage.devDependencies.electron;
|
||||
|
||||
// Remove old electron/dist and copy new one
|
||||
console.log('Removing old electron/dist...');
|
||||
rmSync(electronDistDir, { recursive: true, force: true });
|
||||
|
||||
console.log('Copying dist to electron/dist...');
|
||||
cpSync(distDir, electronDistDir, { recursive: true });
|
||||
|
||||
// Create electron package.json
|
||||
const electronPackage = {
|
||||
name: rootPackage.name,
|
||||
description: rootPackage.description,
|
||||
homepage: rootPackage.homepage,
|
||||
license: rootPackage.license,
|
||||
version: version,
|
||||
type: "module",
|
||||
main: "main.js",
|
||||
bin: {
|
||||
shakespeare: "./bin/shakespeare.js"
|
||||
},
|
||||
files: [
|
||||
"bin/",
|
||||
"dist/",
|
||||
"main.js",
|
||||
"package.json",
|
||||
"preload.js",
|
||||
"LICENSE",
|
||||
"README.md"
|
||||
],
|
||||
author: rootPackage.author,
|
||||
repository: rootPackage.repository,
|
||||
dependencies: {
|
||||
electron: electronVersion
|
||||
}
|
||||
};
|
||||
|
||||
// Write electron package.json
|
||||
writeFileSync(
|
||||
join(electronDir, 'package.json'),
|
||||
JSON.stringify(electronPackage, null, 2) + '\n',
|
||||
'utf-8'
|
||||
);
|
||||
|
||||
// Copy README.md to electron directory
|
||||
copyFileSync(
|
||||
join(rootDir, 'README.md'),
|
||||
join(electronDir, 'README.md')
|
||||
);
|
||||
|
||||
console.log(`✓ Generated electron/package.json with version ${version}`);
|
||||
console.log('✓ Copied README.md to electron/');
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Favicon Proxy Service
|
||||
*
|
||||
* Proxies favicon requests to DuckDuckGo's favicon service.
|
||||
* This allows fetching favicons for any domain without CORS issues.
|
||||
*
|
||||
* Usage: GET /favicon?url=https://example.com
|
||||
* Returns: The favicon image for the specified domain
|
||||
*/
|
||||
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
const targetUrl = requestUrl.searchParams.get('url');
|
||||
|
||||
if (!targetUrl) {
|
||||
return new Response('Missing url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(targetUrl);
|
||||
} catch {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
let hostname = url.hostname;
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'api.z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
return fetchFavicon(hostname);
|
||||
},
|
||||
};
|
||||
|
||||
function fetchFavicon(hostname: string): Promise<Response> {
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
}
|
||||
+45
-116
@@ -7,14 +7,11 @@ import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||
import { Suspense, useEffect } from 'react';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { NostrSync } from '@/components/NostrSync';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { SentryProvider } from '@/components/SentryProvider';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
|
||||
@@ -22,12 +19,8 @@ import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -47,137 +40,73 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
// Get OS-specific default paths for Electron
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } {
|
||||
if (!globalThis.electron) {
|
||||
// Browser defaults - use virtual filesystem paths
|
||||
return {
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathPlugins: "/plugins",
|
||||
};
|
||||
}
|
||||
|
||||
// Electron defaults - use OS-specific paths
|
||||
// Note: The ~ will be expanded by the Electron main process
|
||||
const platform = navigator.platform.toLowerCase();
|
||||
|
||||
if (platform.includes('win')) {
|
||||
// Windows
|
||||
return {
|
||||
fsPathProjects: "~/Documents/Projects",
|
||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
||||
};
|
||||
} else if (platform.includes('mac')) {
|
||||
// macOS
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
||||
};
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/.config/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/.config/shakespeare/plugins",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const electronPaths = getElectronDefaultPaths();
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
{ url: 'wss://relay.primal.net', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
relayUrl: "wss://relay.ditto.pub",
|
||||
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
esmUrl: "https://esm.sh",
|
||||
esmUrl: "https://esm.shakespeare.diy",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||
previewDomain: "local-shakespeare.dev",
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
|
||||
fsPathProjects: electronPaths.fsPathProjects,
|
||||
fsPathConfig: electronPaths.fsPathConfig,
|
||||
fsPathTmp: electronPaths.fsPathTmp,
|
||||
fsPathPlugins: electronPaths.fsPathPlugins,
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||
sentryEnabled: true,
|
||||
};
|
||||
|
||||
// Initialize filesystem adapter based on environment
|
||||
// In Electron, use Electron filesystem at ~/shakespeare
|
||||
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
|
||||
const fs = globalThis.electron
|
||||
? new ElectronFSAdapter()
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
const presetRelays = [
|
||||
{ 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' },
|
||||
];
|
||||
|
||||
// Initialize LightningFS
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from tmp directory
|
||||
// Automatically removes files older than 1 hour from /tmp directory
|
||||
function FSCleanupHandler() {
|
||||
const { config } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs, config.fsPathTmp).catch(console.error);
|
||||
}, [config.fsPathTmp]);
|
||||
cleanupTmpDirectory(fs).catch(console.error);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<UnheadProvider head={head}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||
<SentryProvider>
|
||||
<FSProvider fs={fs}>
|
||||
<ConsoleErrorProvider>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
</FSProvider>
|
||||
</SentryProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
</ErrorBoundary>
|
||||
<UnheadProvider head={head}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<ConsoleErrorProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+3
-7
@@ -1,4 +1,4 @@
|
||||
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
@@ -24,17 +24,13 @@ import { ProjectView } from "./pages/ProjectView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
// Use HashRouter in Electron, BrowserRouter in web
|
||||
const Router = globalThis.electron ? HashRouter : BrowserRouter;
|
||||
|
||||
return (
|
||||
<Router>
|
||||
<BrowserRouter>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<URLFragmentHandler />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
@@ -56,7 +52,7 @@ export function AppRouter() {
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
export default AppRouter;
|
||||
@@ -1,6 +1,6 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs, Send, Puzzle } from 'lucide-react';
|
||||
import { 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';
|
||||
@@ -141,13 +141,6 @@ export const AIMessageItem = memo(({
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
|
||||
};
|
||||
case 'nostr_publish_events': {
|
||||
const eventCount = args.events?.length || 0;
|
||||
return {
|
||||
icon: Send,
|
||||
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event'
|
||||
};
|
||||
}
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
@@ -163,11 +156,6 @@ export const AIMessageItem = memo(({
|
||||
icon: Logs,
|
||||
title: 'Read Console'
|
||||
};
|
||||
case 'skill':
|
||||
return {
|
||||
icon: Puzzle,
|
||||
title: args.name ? `Skill: ${args.name}` : 'Skill'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
|
||||
interface AISettingsProviderProps {
|
||||
@@ -17,7 +16,6 @@ const DEFAULT_SETTINGS: AISettings = {
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
@@ -25,7 +23,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readAISettings(fs, configPath);
|
||||
const settings = await readAISettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize AI settings:', error);
|
||||
@@ -36,7 +34,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs, configPath]);
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
@@ -44,14 +42,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeAISettings(fs, settings, configPath);
|
||||
await writeAISettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save AI settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized, configPath]);
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<AISettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Check, Sparkles, ArrowRight, AlertCircle, ExternalLink } from 'lucide-react';
|
||||
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 { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
@@ -15,7 +14,6 @@ interface AddProviderDialogProps {
|
||||
|
||||
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
|
||||
const { settings, setProvider } = useAISettings();
|
||||
|
||||
@@ -27,26 +25,27 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
existingProvider.nostr === provider.nostr &&
|
||||
existingProvider.proxy === provider.proxy;
|
||||
|
||||
// Get provider preset if available
|
||||
const preset = AI_PROVIDER_PRESETS.find(
|
||||
p => p.id === provider.id && p.baseURL === provider.baseURL
|
||||
);
|
||||
const providerName = preset?.name || provider.id;
|
||||
// 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);
|
||||
};
|
||||
|
||||
// Reset agreed to terms when dialog opens or provider changes
|
||||
// Scroll to top when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAgreedToTerms(false);
|
||||
if (scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
if (open && scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [open, provider.id]);
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -165,40 +164,8 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
{preset?.tosURL && (
|
||||
<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={agreedToTerms}
|
||||
onCheckedChange={(checked) => setAgreedToTerms(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 {providerName}'s{' '}
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline inline-flex items-center gap-1"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Terms of Service
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleAddProvider}
|
||||
disabled={preset?.tosURL ? !agreedToTerms : false}
|
||||
>
|
||||
<Button onClick={handleAddProvider}>
|
||||
Add Provider
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ReactNode, useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
|
||||
import i18n from '@/lib/i18n';
|
||||
|
||||
interface AppProviderProps {
|
||||
@@ -10,37 +10,22 @@ interface AppProviderProps {
|
||||
storageKey: string;
|
||||
/** Default app configuration */
|
||||
defaultConfig: AppConfig;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
// Zod schema for RelayMetadata
|
||||
const RelayMetadataSchema = z.object({
|
||||
relays: z.array(z.object({
|
||||
url: z.string().url(),
|
||||
read: z.boolean(),
|
||||
write: z.boolean(),
|
||||
})),
|
||||
updatedAt: z.number(),
|
||||
}) satisfies z.ZodType<RelayMetadata>;
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayMetadata: RelayMetadataSchema,
|
||||
relayUrl: z.string().url(),
|
||||
projectTemplate: z.string().url(),
|
||||
esmUrl: z.string().url(),
|
||||
corsProxy: z.string().url(),
|
||||
faviconUrl: z.string().url(),
|
||||
previewDomain: z.string().min(1),
|
||||
language: z.string(),
|
||||
showcaseEnabled: z.boolean(),
|
||||
showcaseModerator: z.string(),
|
||||
ngitServers: z.array(z.string()),
|
||||
fsPathProjects: z.string().min(1),
|
||||
fsPathConfig: z.string().min(1),
|
||||
fsPathTmp: z.string().min(1),
|
||||
fsPathPlugins: z.string().min(1),
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
@@ -48,6 +33,7 @@ export function AppProvider(props: AppProviderProps) {
|
||||
children,
|
||||
storageKey,
|
||||
defaultConfig,
|
||||
presetRelays,
|
||||
} = props;
|
||||
|
||||
// App configuration state with localStorage persistence
|
||||
@@ -68,18 +54,12 @@ export function AppProvider(props: AppProviderProps) {
|
||||
setConfig(updater);
|
||||
};
|
||||
|
||||
// Merge default config with stored config
|
||||
const config = { ...defaultConfig, ...rawConfig };
|
||||
|
||||
// Expand filesystem paths
|
||||
config.fsPathConfig = expandPath(config.fsPathConfig);
|
||||
config.fsPathProjects = expandPath(config.fsPathProjects);
|
||||
config.fsPathTmp = expandPath(config.fsPathTmp);
|
||||
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
updateConfig,
|
||||
presetRelays,
|
||||
};
|
||||
|
||||
// Apply theme effects to document
|
||||
@@ -143,18 +123,4 @@ function useApplyLanguage(language?: string): void {
|
||||
useEffect(() => {
|
||||
i18n.changeLanguage(language ?? navigator.language);
|
||||
}, [language]);
|
||||
}
|
||||
|
||||
/** Expand FS paths with the user's home directory, if available. */
|
||||
function expandPath(path: string): string {
|
||||
const homedir = window.electron?.homedir;
|
||||
if (!homedir) {
|
||||
return path;
|
||||
} else if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
} else if (path === '~') {
|
||||
return homedir;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,10 @@ 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";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Settings } from 'lucide-react';
|
||||
|
||||
export function AppShowcase() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { data: submissions = [], isLoading } = useAppSubmissions();
|
||||
@@ -36,7 +33,7 @@ export function AppShowcase() {
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Filter and shuffle submissions - memoized with stable dependency
|
||||
const { templateApps, featuredApps, approvedApps } = useMemo(() => {
|
||||
const { templateApps, halloweenApps, featuredApps, approvedApps } = useMemo(() => {
|
||||
// Filter visible submissions
|
||||
const visibleSubmissions = submissions.filter(app => !app.isHidden);
|
||||
|
||||
@@ -44,12 +41,23 @@ export function AppShowcase() {
|
||||
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(nonTemplateSubmissions.filter(app => app.isFeatured));
|
||||
const approved = shuffleArray(nonTemplateSubmissions.filter(app => app.isApproved && !app.isFeatured));
|
||||
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,
|
||||
};
|
||||
@@ -63,7 +71,7 @@ export function AppShowcase() {
|
||||
// Don't show showcase if no apps exist
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<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">
|
||||
@@ -99,19 +107,14 @@ export function AppShowcase() {
|
||||
|
||||
if (!submissions.length) {
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<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">
|
||||
{t('noAppsFound')}
|
||||
No apps found. Try another relay?
|
||||
</p>
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<Link to="/settings/nostr">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
{t('relayConfiguration')}
|
||||
</Link>
|
||||
</Button>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -120,19 +123,19 @@ export function AppShowcase() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<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-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
|
||||
<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">{t('featuredApps')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('featuredAppsDescription')}</p>
|
||||
<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">
|
||||
@@ -148,16 +151,41 @@ export function AppShowcase() {
|
||||
</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-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
|
||||
<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">{t('templates')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('templatesDescription')}</p>
|
||||
<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">
|
||||
@@ -179,16 +207,16 @@ export function AppShowcase() {
|
||||
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-none w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center">
|
||||
<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">
|
||||
{t('moreAppsCount', { count: approvedApps.length })}
|
||||
More Apps ({approvedApps.length})
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
|
||||
{showAllApps ? 'Click to collapse' : 'Click to view more community apps'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -132,7 +132,7 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-homepage-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
}]);
|
||||
|
||||
const currentHomepageList = currentHomepageLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
@@ -175,7 +175,7 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
}]);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
@@ -214,7 +214,7 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-featured-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
}]);
|
||||
|
||||
const currentFeaturedList = currentFeaturedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
@@ -257,7 +257,7 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
}]);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
@@ -296,7 +296,7 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
}]);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
|
||||
+186
-877
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { SiNetlify, SiVercel } from '@icons-pack/react-simple-icons';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -24,67 +24,16 @@ import { useDeploySettings } from '@/hooks/useDeploySettings';
|
||||
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import 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';
|
||||
|
||||
/**
|
||||
* Helper function to get provider URL for favicon
|
||||
*/
|
||||
function getProviderUrl(provider: DeployProvider): string | null {
|
||||
switch (provider.type) {
|
||||
case 'shakespeare':
|
||||
if (provider.host) {
|
||||
return `https://${provider.host}`;
|
||||
}
|
||||
return 'https://shakespeare.diy';
|
||||
|
||||
case 'netlify':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://netlify.com';
|
||||
|
||||
case 'vercel':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://vercel.com';
|
||||
|
||||
case 'nsite':
|
||||
return null;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render provider icon using favicon or fallback
|
||||
*/
|
||||
function renderProviderIcon(provider: DeployProvider, size = 14) {
|
||||
const url = getProviderUrl(provider);
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
<ExternalFavicon
|
||||
url={url}
|
||||
size={size}
|
||||
fallback={<Rocket size={size} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <Rocket size={size} />;
|
||||
}
|
||||
|
||||
interface DeployDialogProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
@@ -116,7 +65,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
|
||||
const { user } = useCurrentUser();
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
@@ -167,7 +115,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setDeployResult(null);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
let adapter: DeployAdapter;
|
||||
|
||||
@@ -440,7 +388,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
<SelectTrigger id="provider">
|
||||
{selectedProvider ? (
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderIcon(selectedProvider, 14)}
|
||||
{selectedProvider.id === 'netlify' && <SiNetlify size={14} />}
|
||||
{selectedProvider.id === 'vercel' && <SiVercel size={14} />}
|
||||
<span>{selectedProvider.name}</span>
|
||||
</div>
|
||||
) : (
|
||||
@@ -451,7 +400,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
{settings.providers.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderIcon(provider, 14)}
|
||||
{provider.id === 'netlify' && <SiNetlify size={14} />}
|
||||
{provider.id === 'vercel' && <SiVercel size={14} />}
|
||||
<span>{provider.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState, useEffect, useMemo, type ReactNode } from 'react';
|
||||
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||
|
||||
const DEFAULT_SETTINGS: DeploySettings = {
|
||||
@@ -10,7 +9,6 @@ const DEFAULT_SETTINGS: DeploySettings = {
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<DeploySettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
@@ -18,7 +16,7 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readDeploySettings(fs, configPath);
|
||||
const settings = await readDeploySettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize deploy settings:', error);
|
||||
@@ -29,7 +27,7 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs, configPath]);
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
@@ -37,14 +35,14 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeDeploySettings(fs, settings, configPath);
|
||||
await writeDeploySettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save deploy settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized, configPath]);
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (updates: Partial<DeploySettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...updates }));
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { ErrorBoundary } from './ErrorBoundary';
|
||||
|
||||
// Component that throws an error
|
||||
function ThrowError({ shouldThrow }: { shouldThrow: boolean }) {
|
||||
if (shouldThrow) {
|
||||
throw new Error('Test error message');
|
||||
}
|
||||
return <div>No error</div>;
|
||||
}
|
||||
|
||||
describe('ErrorBoundary', () => {
|
||||
// Suppress console.error during tests to avoid noise
|
||||
const originalError = console.error;
|
||||
beforeEach(() => {
|
||||
console.error = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.error = originalError;
|
||||
});
|
||||
|
||||
it('renders children when there is no error', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<div>Test content</div>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Test content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders error UI when child component throws', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test error message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders custom fallback when provided as ReactNode', () => {
|
||||
const customFallback = <div>Custom error UI</div>;
|
||||
|
||||
render(
|
||||
<ErrorBoundary fallback={customFallback}>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Custom error UI')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders custom fallback when provided as function', () => {
|
||||
const customFallback = ({ error }: { error: Error }) => (
|
||||
<div>Error: {error.message}</div>
|
||||
);
|
||||
|
||||
render(
|
||||
<ErrorBoundary fallback={customFallback}>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Error: Test error message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onError callback when error occurs', () => {
|
||||
const onError = vi.fn();
|
||||
|
||||
render(
|
||||
<ErrorBoundary onError={onError}>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(onError).toHaveBeenCalledWith(
|
||||
expect.any(Error),
|
||||
expect.objectContaining({
|
||||
componentStack: expect.any(String),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('shows action buttons in error state', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /reload page/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /go home/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows stack trace in development mode', () => {
|
||||
const originalEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = 'development';
|
||||
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Stack Trace')).toBeInTheDocument();
|
||||
|
||||
process.env.NODE_ENV = originalEnv;
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { ErrorBoundary as ReactErrorBoundary, FallbackProps } from 'react-error-boundary';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
|
||||
import { getSentryInstance } from '@/lib/sentry';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
|
||||
onError?: (error: Error, info: { componentStack: string | null }) => void;
|
||||
/** Whether to report errors to Sentry (default: true) */
|
||||
reportToSentry?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default error fallback component
|
||||
*/
|
||||
function ErrorFallback({ error }: FallbackProps) {
|
||||
const handleReload = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const handleGoHome = () => {
|
||||
window.location.href = '/';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4 bg-background">
|
||||
<Card className="max-w-2xl w-full">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-destructive/10 rounded-full">
|
||||
<AlertTriangle className="h-6 w-6 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-2xl">Something went wrong</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
We encountered an unexpected error. Don't worry, your data is safe.
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>Error Details</AlertTitle>
|
||||
<AlertDescription className="mt-2 font-mono text-xs break-all">
|
||||
{error.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{process.env.NODE_ENV === 'development' && error.stack && (
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-sm font-medium mb-2">
|
||||
Stack Trace
|
||||
</summary>
|
||||
<pre className="text-xs bg-muted p-4 rounded-md overflow-auto max-h-64">
|
||||
{error.stack}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex flex-wrap gap-2">
|
||||
<Button onClick={handleReload} variant="outline" className="gap-2">
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Reload Page
|
||||
</Button>
|
||||
<Button onClick={handleGoHome} variant="outline" className="gap-2">
|
||||
<Home className="h-4 w-4" />
|
||||
Go Home
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Error Boundary component that catches React rendering errors and displays a fallback UI.
|
||||
* Prevents the entire app from crashing when a component throws an error.
|
||||
*
|
||||
* Built on top of react-error-boundary for robust error handling.
|
||||
*/
|
||||
export function ErrorBoundary({
|
||||
children,
|
||||
fallback,
|
||||
onError,
|
||||
reportToSentry = true,
|
||||
}: ErrorBoundaryProps) {
|
||||
const handleError = (error: Error, info: { componentStack: string | null }) => {
|
||||
// Log error details for debugging
|
||||
console.error('ErrorBoundary caught an error:', error, info);
|
||||
|
||||
// Report to Sentry if enabled
|
||||
if (reportToSentry) {
|
||||
const Sentry = getSentryInstance();
|
||||
if (Sentry) {
|
||||
Sentry.captureException(error, {
|
||||
contexts: {
|
||||
react: {
|
||||
componentStack: info.componentStack,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Call optional error handler
|
||||
onError?.(error, info);
|
||||
};
|
||||
|
||||
// Determine fallback render
|
||||
const fallbackRender = typeof fallback === 'function'
|
||||
? fallback
|
||||
: fallback
|
||||
? () => fallback
|
||||
: ErrorFallback;
|
||||
|
||||
return (
|
||||
<ReactErrorBoundary
|
||||
fallbackRender={fallbackRender}
|
||||
onError={handleError}
|
||||
>
|
||||
{children}
|
||||
</ReactErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
url: string;
|
||||
/** Size of the favicon in pixels */
|
||||
size?: number;
|
||||
/** Fallback element to display if favicon fails to load */
|
||||
fallback?: ReactNode;
|
||||
/** Additional CSS classes */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalFavicon component that fetches and displays a favicon for a given URL
|
||||
* using the configurable favicon service from app settings.
|
||||
*/
|
||||
export function ExternalFavicon({
|
||||
url,
|
||||
size = 16,
|
||||
fallback,
|
||||
className = '',
|
||||
}: ExternalFaviconProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center justify-center ${className}`}>
|
||||
<img
|
||||
src={faviconSrc}
|
||||
alt=""
|
||||
className="object-contain"
|
||||
style={{ width: size, height: size }}
|
||||
onError={(e) => {
|
||||
// Hide the image and show the fallback on error
|
||||
e.currentTarget.style.display = 'none';
|
||||
const fallbackElement = e.currentTarget.nextElementSibling as HTMLElement;
|
||||
if (fallbackElement) {
|
||||
fallbackElement.style.display = 'inline-block';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{fallback && (
|
||||
<span style={{ display: 'none' }}>
|
||||
{fallback}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GiftCardRedeemDialog } from './GiftCardRedeemDialog';
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn();
|
||||
|
||||
describe('GiftCardRedeemDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders loading state initially', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockImplementation(() =>
|
||||
new Promise(() => {}) // Never resolves to keep it loading
|
||||
);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show loading skeleton
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error for invalid gift card', async () => {
|
||||
// Mock the gift card check endpoint to return an error
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({
|
||||
error: {
|
||||
message: 'No giftcard found with code "INVALID-CODE"',
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="INVALID-CODE"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for error message to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Invalid Gift Card')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows already redeemed message for redeemed gift card', async () => {
|
||||
// Mock the gift card check endpoint to return a redeemed gift card
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: true,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for redeemed message to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Already Redeemed')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows gift card amount for valid unredeemed gift card', async () => {
|
||||
// Mock the gift card check endpoint to return a valid gift card
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for gift card amount to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows provider name when matching preset is found', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 10.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for provider name to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Shakespeare AI')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,357 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Gift, Check } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { generateSecretKey, nip19 } from 'nostr-tools';
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface GiftCardRedeemDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
baseURL: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface Giftcard {
|
||||
object: 'giftcard';
|
||||
id: string;
|
||||
code: string;
|
||||
amount: number;
|
||||
redeemed: boolean;
|
||||
created_at?: number;
|
||||
}
|
||||
|
||||
interface GiftcardRedemption {
|
||||
object: 'giftcard_redemption';
|
||||
amount: number;
|
||||
}
|
||||
|
||||
// No steps needed - everything on one screen!
|
||||
|
||||
/**
|
||||
* Gift Card Redemption Dialog
|
||||
*
|
||||
* This component handles the complete gift card redemption flow, including:
|
||||
* - Fetching gift card details from the provider API
|
||||
* - Multi-step wizard for login and provider setup
|
||||
* - Account switching before redemption
|
||||
* - Automatic provider matching against presets
|
||||
*
|
||||
* Flow:
|
||||
* 1. Check if gift card is valid (unauthenticated API call)
|
||||
* 2. Determine required steps based on user state:
|
||||
* - Not logged in? → Show login step
|
||||
* - Provider not configured? → Show provider setup step
|
||||
* - Ready to redeem? → Show preview with account switcher
|
||||
* 3. Redeem gift card and add credits to user's account
|
||||
* 4. Navigate to AI Settings to show new balance
|
||||
*
|
||||
* @param open - Whether the dialog is open
|
||||
* @param onOpenChange - Callback when dialog open state changes
|
||||
* @param baseURL - Provider base URL (e.g., https://ai.shakespeare.diy/v1)
|
||||
* @param code - Gift card code to redeem (e.g., XXXX-XXXX-XXXX-XXXX)
|
||||
*/
|
||||
export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: GiftCardRedeemDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { settings, setProvider } = useAISettings();
|
||||
const { config } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const login = useLoginActions();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [generatedNsec, setGeneratedNsec] = useState<string>('');
|
||||
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
|
||||
const hasInitialized = useRef(false);
|
||||
|
||||
// Find matching provider by baseURL
|
||||
const matchingProvider = settings.providers.find(p => p.baseURL === baseURL);
|
||||
const matchingPreset = AI_PROVIDER_PRESETS.find(p => p.baseURL === baseURL);
|
||||
|
||||
// Query gift card details without authentication
|
||||
const { data: giftcard, isLoading: isLoadingGiftcard, error: giftcardError } = useQuery({
|
||||
queryKey: ['giftcard-check', baseURL, code],
|
||||
queryFn: async (): Promise<Giftcard> => {
|
||||
const response = await fetch(`${baseURL}/credits/giftcards/check/${code}`);
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error?.message || 'Failed to fetch gift card details');
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
enabled: open && !!baseURL && !!code,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
// Mutation for redeeming gift card
|
||||
const redeemMutation = useMutation({
|
||||
mutationFn: async (): Promise<GiftcardRedemption> => {
|
||||
if (!matchingProvider) {
|
||||
throw new Error('Provider not configured');
|
||||
}
|
||||
const ai = createAIClient(matchingProvider, user, config.corsProxy);
|
||||
return await ai.post('/credits/giftcards/redeem', {
|
||||
body: { code },
|
||||
}) as GiftcardRedemption;
|
||||
},
|
||||
onSuccess: (redemption) => {
|
||||
toast({
|
||||
title: '🎉 ' + t('giftCardRedeemed'),
|
||||
description: t('creditsAddedToAccount', { amount: formatCurrency(redemption.amount) }),
|
||||
});
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: t('redemptionFailed'),
|
||||
description: error.message || t('failedToRedeemGiftCard'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Reset state and initialize when dialog opens
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
// Clear state when closing
|
||||
setGeneratedNsec('');
|
||||
setAgreedToProviderTerms(false);
|
||||
hasInitialized.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Only initialize once when dialog opens
|
||||
if (!hasInitialized.current) {
|
||||
hasInitialized.current = true;
|
||||
|
||||
// Auto-generate account if needed
|
||||
if (!user && !generatedNsec) {
|
||||
const secretKey = generateSecretKey();
|
||||
const nsec = nip19.nsecEncode(secretKey);
|
||||
setGeneratedNsec(nsec);
|
||||
login.nsec(nsec);
|
||||
}
|
||||
}
|
||||
}, [open, user, generatedNsec, login]);
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
const handleRedeem = () => {
|
||||
// Check prerequisites
|
||||
if (!user) return;
|
||||
|
||||
// If provider not configured, add it first
|
||||
if (!matchingProvider && matchingPreset) {
|
||||
if (!agreedToProviderTerms) return;
|
||||
|
||||
const providerConfig = {
|
||||
id: matchingPreset.id,
|
||||
baseURL: matchingPreset.baseURL,
|
||||
nostr: matchingPreset.nostr || undefined,
|
||||
};
|
||||
|
||||
setProvider(providerConfig);
|
||||
}
|
||||
|
||||
// Redeem the gift card
|
||||
redeemMutation.mutate(undefined, {
|
||||
onSuccess() {
|
||||
// Invalidate AI credits query for this provider and user
|
||||
const providerId = matchingProvider?.id || matchingPreset?.id;
|
||||
if (providerId) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits', user.pubkey, providerId] });
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Error state
|
||||
if (giftcardError) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8">
|
||||
<div className="mb-4">
|
||||
<Gift className="h-16 w-16 mx-auto text-muted-foreground opacity-50" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">{t('invalidGiftCard')}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{giftcardError instanceof Error ? giftcardError.message : t('giftCardNotFound')}
|
||||
</p>
|
||||
<Button onClick={() => onOpenChange(false)} className="mt-6">
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (isLoadingGiftcard) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8 space-y-4">
|
||||
<Skeleton className="h-16 w-16 rounded-full mx-auto" />
|
||||
<Skeleton className="h-8 w-48 mx-auto" />
|
||||
<Skeleton className="h-4 w-64 mx-auto" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Already redeemed
|
||||
if (giftcard?.redeemed) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8">
|
||||
<div className="mb-4">
|
||||
<Check className="h-16 w-16 mx-auto text-green-500" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">{t('alreadyRedeemed')}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{t('giftCardAlreadyRedeemed')}
|
||||
</p>
|
||||
<Button onClick={() => onOpenChange(false)} className="mt-6">
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8 space-y-6">
|
||||
{/* Animated gift icon */}
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="h-24 w-24 rounded-full bg-primary/10 animate-pulse" />
|
||||
</div>
|
||||
<div className="relative flex items-center justify-center">
|
||||
<Gift className="h-16 w-16 text-primary animate-bounce" style={{ animationDuration: '2s' }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title and amount */}
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('youveGotCredits', { amount: giftcard && formatCurrency(giftcard.amount) })}
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{t('readyToAddCredits')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Provider info */}
|
||||
{matchingPreset && (
|
||||
<div className="bg-muted/50 rounded-lg p-4 text-sm">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<span className="text-muted-foreground">{t('provider')}:</span>
|
||||
<span className="font-medium">{matchingPreset.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Account selector - always show */}
|
||||
<div className="border rounded-lg p-4">
|
||||
<p className="text-xs text-muted-foreground mb-3 text-left">
|
||||
{t('redeemingToAccount')}
|
||||
</p>
|
||||
<LoginArea className="w-full" />
|
||||
</div>
|
||||
|
||||
{/* Provider ToS - only show if provider not configured */}
|
||||
{!matchingProvider && matchingPreset && (
|
||||
<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"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: matchingPreset.name })}{' '}
|
||||
{matchingPreset.tosURL ? (
|
||||
<a
|
||||
href={matchingPreset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={handleRedeem}
|
||||
disabled={
|
||||
!user ||
|
||||
redeemMutation.isPending ||
|
||||
(!matchingProvider && !agreedToProviderTerms)
|
||||
}
|
||||
size="lg"
|
||||
className="w-full text-lg h-14 font-semibold"
|
||||
>
|
||||
{redeemMutation.isPending ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2" />
|
||||
{t('redeeming')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Gift className="h-5 w-5 mr-2" />
|
||||
{t('redeemNow')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="w-full"
|
||||
>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+38
-265
@@ -46,41 +46,22 @@ import {
|
||||
Settings2,
|
||||
GitPullRequest,
|
||||
ExternalLink,
|
||||
Copy,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { usePullRequests } from '@/hooks/usePullRequests';
|
||||
import { useGitFetch } from '@/hooks/useGitFetch';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { GitManagementDialog } from '@/components/git/GitManagementDialog';
|
||||
import { MergeDialog } from '@/components/git/MergeDialog';
|
||||
import { PullRequestDialog } from '@/components/git/PullRequestDialog';
|
||||
import { AnnounceRepositoryDialog, type AnnounceRepositoryResult } from '@/components/git/AnnounceRepositoryDialog';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
// Helper function to format fetch timestamp with special "fetched" prefix
|
||||
function formatFetchTime(date: Date | number): string {
|
||||
const timestamp = typeof date === 'number' ? date : date.getTime();
|
||||
const now = Date.now();
|
||||
const diffMs = now - timestamp;
|
||||
|
||||
// Less than 20 seconds - use special "fetched just now" message
|
||||
if (diffMs < 20 * 1000) {
|
||||
return 'fetched just now';
|
||||
}
|
||||
|
||||
// Otherwise use the standard relative time formatter
|
||||
return formatRelativeTime(timestamp);
|
||||
}
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -93,8 +74,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [isPulling, setIsPulling] = useState(false);
|
||||
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
|
||||
const [isAnnounceDialogOpen, setIsAnnounceDialogOpen] = useState(false);
|
||||
const [editNaddr, setEditNaddr] = useState<string | undefined>(undefined);
|
||||
const [originUrl, setOriginUrl] = useState('');
|
||||
const [isSavingOrigin, setIsSavingOrigin] = useState(false);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -107,55 +86,26 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false);
|
||||
const [, setUpdateTrigger] = useState(0);
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl);
|
||||
const { data: gitFetchData, isFetching: isFetchingRemote, refetch: refetchRemote } = useGitFetch(projectId);
|
||||
const { config } = useAppContext();
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Update the "last fetched" timestamp display every 10 seconds
|
||||
// Initialize origin URL from git status
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setUpdateTrigger(prev => prev + 1);
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// Initialize origin URL from git status and load nostr.repo config
|
||||
useEffect(() => {
|
||||
const loadGitConfig = async () => {
|
||||
if (gitStatus?.remotes) {
|
||||
const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin');
|
||||
setOriginUrl(originRemote?.url || '');
|
||||
|
||||
// Load nostr.repo config if origin is a nostr:// URL
|
||||
if (originRemote?.url.startsWith('nostr://')) {
|
||||
try {
|
||||
const naddr = await git.getConfig({
|
||||
dir: projectPath,
|
||||
path: 'nostr.repo',
|
||||
});
|
||||
setEditNaddr(naddr || undefined);
|
||||
} catch {
|
||||
setEditNaddr(undefined);
|
||||
}
|
||||
} else {
|
||||
setEditNaddr(undefined);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadGitConfig();
|
||||
}, [gitStatus?.remotes, git, projectPath]);
|
||||
if (gitStatus?.remotes) {
|
||||
const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin');
|
||||
setOriginUrl(originRemote?.url || '');
|
||||
}
|
||||
}, [gitStatus?.remotes]);
|
||||
|
||||
const loadBranches = useCallback(async () => {
|
||||
setIsLoadingBranches(true);
|
||||
@@ -182,7 +132,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
force: true,
|
||||
});
|
||||
|
||||
toast({
|
||||
@@ -353,27 +302,22 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`);
|
||||
}
|
||||
|
||||
// Open the announcement dialog
|
||||
setIsAnnounceDialogOpen(true);
|
||||
onOpenChange?.(false);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: "Cannot push to Nostr",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
// Create repo announcement event (NIP-34 kind 30617)
|
||||
const cloneUrls = config.ngitServers.map(server =>
|
||||
`https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git`
|
||||
);
|
||||
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
|
||||
|
||||
await publishEvent({
|
||||
kind: 30617,
|
||||
content: "",
|
||||
tags: [
|
||||
["d", projectId],
|
||||
["clone", ...cloneUrls],
|
||||
["relays", ...relayUrls],
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
setIsPushingToNostr(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAnnounceSuccess = async (result: AnnounceRepositoryResult) => {
|
||||
if (!user) return;
|
||||
|
||||
setIsPushingToNostr(true);
|
||||
|
||||
try {
|
||||
// Get current repository state
|
||||
const refTags: string[][] = [];
|
||||
|
||||
@@ -469,31 +413,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
|
||||
// Create repo state event (NIP-34 kind 30618)
|
||||
const stateEvent = {
|
||||
await publishEvent({
|
||||
kind: 30618,
|
||||
content: '',
|
||||
content: "",
|
||||
tags: [
|
||||
['d', result.repoId],
|
||||
["d", projectId],
|
||||
...refTags,
|
||||
...(headRef ? [['HEAD', headRef]] : []),
|
||||
...(headRef ? [["HEAD", headRef]] : []),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
console.log('Creating repository state event:', stateEvent);
|
||||
|
||||
// Sign and publish the state event
|
||||
const signedStateEvent = await user.signer.signEvent(stateEvent);
|
||||
|
||||
// State events only go to the relays specified in the repo announcement
|
||||
console.log('Publishing repository state to relays:', result.relays);
|
||||
await nostr.event(signedStateEvent, { relays: result.relays });
|
||||
|
||||
console.log('Published repository state to Nostr relays');
|
||||
});
|
||||
|
||||
// Set origin remote to Nostr URL
|
||||
// Format: nostr://<npub>/<repo-id>
|
||||
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/${result.repoId}`;
|
||||
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/${projectId}`;
|
||||
|
||||
try {
|
||||
// Remove existing origin if it exists
|
||||
@@ -511,24 +443,22 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
url: nostrUrl,
|
||||
});
|
||||
|
||||
console.log('Set Git origin to:', nostrUrl);
|
||||
|
||||
// Set nostr.repo config
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: 'nostr.repo',
|
||||
value: result.naddr,
|
||||
value: nip19.naddrEncode({
|
||||
kind: 30617,
|
||||
pubkey: user.pubkey,
|
||||
identifier: projectId,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log('Set nostr.repo config to:', result.naddr);
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Waiting for GRASP servers to update...',
|
||||
title: "Repository published to Nostr",
|
||||
description: "Waiting for GRASP servers to update...",
|
||||
});
|
||||
|
||||
// Refresh git status to pick up the new remote
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
@@ -750,81 +680,9 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
const syncStatus = getSyncStatus();
|
||||
|
||||
// Check if the nostr:// remote belongs to the current user
|
||||
const isOwnNostrRepo = () => {
|
||||
if (!originUrl.startsWith('nostr://') || !user?.pubkey) return false;
|
||||
|
||||
try {
|
||||
// Parse nostr://<npub>/<repo-id>
|
||||
const urlParts = originUrl.replace('nostr://', '').split('/');
|
||||
if (urlParts.length < 1) return false;
|
||||
|
||||
const npub = urlParts[0];
|
||||
const decoded = nip19.decode(npub);
|
||||
|
||||
return decoded.type === 'npub' && decoded.data === user.pubkey;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const [isGitManagementOpen, setIsGitManagementOpen] = useState(false);
|
||||
const [gitManagementDefaultTab, setGitManagementDefaultTab] = useState<string>('branches');
|
||||
|
||||
const handleCopyShakespeareURL = async () => {
|
||||
if (!originUrl.trim()) {
|
||||
toast({
|
||||
title: "No repository URL",
|
||||
description: "Please enter a Git URL first",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the Shakespeare clone URL by encoding the origin URL
|
||||
const shakespeareURL = `${location.origin}/clone?url=${encodeURIComponent(originUrl.trim())}`;
|
||||
|
||||
// Try modern clipboard API first
|
||||
try {
|
||||
await navigator.clipboard.writeText(shakespeareURL);
|
||||
toast({
|
||||
title: "Copied to clipboard",
|
||||
description: "Edit with Shakespeare URL copied",
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
// Fallback to older method
|
||||
try {
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = shakespeareURL;
|
||||
textArea.style.position = 'fixed';
|
||||
textArea.style.left = '-999999px';
|
||||
textArea.style.top = '-999999px';
|
||||
document.body.appendChild(textArea);
|
||||
textArea.focus();
|
||||
textArea.select();
|
||||
|
||||
const successful = document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
|
||||
if (successful) {
|
||||
toast({
|
||||
title: "Copied to clipboard",
|
||||
description: "Edit with Shakespeare URL copied",
|
||||
});
|
||||
} else {
|
||||
throw new Error('execCommand failed');
|
||||
}
|
||||
} catch {
|
||||
toast({
|
||||
title: "Failed to copy",
|
||||
description: "Could not copy to clipboard. Please copy manually.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -894,45 +752,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Edit with Shakespeare URL */}
|
||||
{originUrl.trim() ? (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
Edit with Shakespeare URL
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={`${location.origin}/clone?url=${encodeURIComponent(originUrl.trim())}`}
|
||||
readOnly
|
||||
className="flex-1 text-xs text-muted-foreground bg-muted cursor-default h-8 truncate"
|
||||
tabIndex={-1}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCopyShakespeareURL}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 px-3"
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
Edit with Shakespeare URL
|
||||
</Label>
|
||||
<div className="p-3 rounded-md border-2 border-dashed border-muted-foreground/30 bg-muted/20">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
Push your repository to get a shareable Shakespeare link
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Credentials Warning */}
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
(() => {
|
||||
@@ -1070,29 +889,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
|
||||
{/* Last Fetched Info - inline with sync status */}
|
||||
{gitStatus.remotes.length > 0 && gitFetchData?.fetchedAt && (
|
||||
<>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
· {formatFetchTime(gitFetchData.fetchedAt)}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => refetchRemote()}
|
||||
disabled={isFetchingRemote}
|
||||
className="h-5 w-5 p-0 -ml-1 hover:bg-transparent"
|
||||
title="Refresh remote status"
|
||||
>
|
||||
{isFetchingRemote ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3 hover:text-foreground transition-colors" />
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
@@ -1145,19 +941,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Edit Nostr Repository Settings */}
|
||||
{gitStatus.remotes.length > 0 && isOwnNostrRepo() && editNaddr && (
|
||||
<Button
|
||||
onClick={() => setIsAnnounceDialogOpen(true)}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full mt-2 h-8 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Settings2 className="h-3 w-3 mr-2" />
|
||||
Edit Nostr Repository Settings
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Merge Branch Action */}
|
||||
@@ -1246,7 +1029,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: pr.sourceBranch,
|
||||
force: true,
|
||||
});
|
||||
await refetchGitStatus();
|
||||
toast({
|
||||
@@ -1417,15 +1199,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Announce Repository Dialog */}
|
||||
<AnnounceRepositoryDialog
|
||||
projectId={projectId}
|
||||
open={isAnnounceDialogOpen}
|
||||
onOpenChange={setIsAnnounceDialogOpen}
|
||||
onSuccess={handleAnnounceSuccess}
|
||||
editNaddr={editNaddr}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -171,8 +171,7 @@ describe('GitSettingsProvider', () => {
|
||||
password: 'test-token',
|
||||
}
|
||||
}
|
||||
}),
|
||||
'/config' // configPath
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
|
||||
interface GitSettingsProviderProps {
|
||||
@@ -15,7 +14,6 @@ const DEFAULT_SETTINGS: GitSettings = {
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<GitSettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
@@ -23,7 +21,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readGitSettings(fs, configPath);
|
||||
const settings = await readGitSettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Git settings:', error);
|
||||
@@ -34,7 +32,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs, configPath]);
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
@@ -42,14 +40,14 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeGitSettings(fs, settings, configPath);
|
||||
await writeGitSettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save Git settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized, configPath]);
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<GitSettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
@@ -17,7 +17,7 @@ const GIT_KINDS = [
|
||||
|
||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
const { children } = props;
|
||||
const { config } = useAppContext();
|
||||
const { config, presetRelays } = useAppContext();
|
||||
|
||||
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -26,13 +26,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
const pool = useRef<NPool | undefined>(undefined);
|
||||
|
||||
// Use refs so the pool always has the latest data
|
||||
const relayMetadata = useRef(config.relayMetadata);
|
||||
const relayUrl = useRef<string>(config.relayUrl);
|
||||
|
||||
// Update refs when config changes
|
||||
useEffect(() => {
|
||||
relayMetadata.current = config.relayMetadata;
|
||||
relayUrl.current = config.relayUrl;
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||
}, [config.relayMetadata, queryClient]);
|
||||
}, [config.relayUrl, queryClient]);
|
||||
|
||||
// Initialize NPool only once
|
||||
if (!pool.current) {
|
||||
@@ -42,32 +42,19 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
},
|
||||
reqRouter(filters) {
|
||||
const routes = new Map<string, NostrFilter[]>();
|
||||
routes.set(relayUrl.current, filters);
|
||||
|
||||
// Route to all read relays
|
||||
const readRelays = relayMetadata.current.relays
|
||||
.filter(r => r.read)
|
||||
.map(r => r.url);
|
||||
|
||||
for (const url of readRelays) {
|
||||
routes.set(url, filters);
|
||||
}
|
||||
|
||||
// If all filters are git-related, also route to all git relays
|
||||
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 gitRelays) {
|
||||
routes.set(url, filters);
|
||||
}
|
||||
}
|
||||
|
||||
return routes;
|
||||
},
|
||||
eventRouter(event: NostrEvent) {
|
||||
// Get write relays from metadata
|
||||
const writeRelays = relayMetadata.current.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
|
||||
const allRelays = new Set<string>(writeRelays);
|
||||
// Publish to the selected relay
|
||||
const allRelays = new Set<string>([relayUrl.current]);
|
||||
|
||||
// If it's a git-related event, also publish to the git relays
|
||||
if (GIT_KINDS.includes(event.kind)) {
|
||||
@@ -76,6 +63,15 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Also publish to the preset relays, capped to 5
|
||||
for (const { url } of (presetRelays ?? [])) {
|
||||
allRelays.add(url);
|
||||
|
||||
if (allRelays.size >= 5) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [...allRelays];
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
/**
|
||||
* NostrSync - Syncs user's Nostr data
|
||||
*
|
||||
* This component runs globally to sync various Nostr data when the user logs in.
|
||||
* Currently syncs:
|
||||
* - NIP-65 relay list (kind 10002)
|
||||
*/
|
||||
export function NostrSync() {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
const syncRelaysFromNostr = async () => {
|
||||
try {
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [10002], authors: [user.pubkey], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
if (events.length > 0) {
|
||||
const event = events[0];
|
||||
|
||||
// Only update if the event is newer than our stored data
|
||||
if (event.created_at > config.relayMetadata.updatedAt) {
|
||||
const fetchedRelays = event.tags
|
||||
.filter(([name]) => name === 'r')
|
||||
.map(([_, url, marker]) => ({
|
||||
url,
|
||||
read: !marker || marker === 'read',
|
||||
write: !marker || marker === 'write',
|
||||
}));
|
||||
|
||||
if (fetchedRelays.length > 0) {
|
||||
console.log('Syncing relay list from Nostr:', fetchedRelays);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
relayMetadata: {
|
||||
relays: fetchedRelays,
|
||||
updatedAt: event.created_at,
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to sync relays from Nostr:', error);
|
||||
}
|
||||
};
|
||||
|
||||
syncRelaysFromNostr();
|
||||
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { WifiOff, Wifi } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useOffline } from '@/hooks/useOffline';
|
||||
|
||||
/**
|
||||
* Component that displays an indicator when the app is offline
|
||||
*/
|
||||
export function OfflineIndicator() {
|
||||
const { isOffline, isOnline } = useOffline();
|
||||
const [showOnlineNotification, setShowOnlineNotification] = useState(false);
|
||||
const [wasOffline, setWasOffline] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOffline) {
|
||||
setWasOffline(true);
|
||||
}
|
||||
|
||||
if (isOnline && wasOffline) {
|
||||
// Show "back online" notification briefly
|
||||
setShowOnlineNotification(true);
|
||||
const timer = setTimeout(() => {
|
||||
setShowOnlineNotification(false);
|
||||
setWasOffline(false);
|
||||
}, 3000);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [isOffline, isOnline, wasOffline]);
|
||||
|
||||
if (!isOffline && !showOnlineNotification) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 animate-in slide-in-from-bottom-4">
|
||||
{isOffline ? (
|
||||
<Alert variant="destructive" className="shadow-lg border-2">
|
||||
<WifiOff className="h-4 w-4" />
|
||||
<AlertDescription className="font-medium">
|
||||
You're offline. Some features may be limited.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<Alert className="shadow-lg border-2 border-green-500 bg-green-50 dark:bg-green-950">
|
||||
<Wifi className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
<AlertDescription className="font-medium text-green-600 dark:text-green-400">
|
||||
You're back online!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ vi.mock('@/hooks/useAISettings', () => ({
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
isConfigured: false,
|
||||
@@ -42,11 +42,9 @@ describe('OnboardingDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Translations are rendered, so we check for the actual English text
|
||||
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument();
|
||||
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
// The button now shows the translated text "Get Started"
|
||||
expect(screen.getByRole('button', { name: 'Get Started' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
|
||||
@@ -1,38 +1,32 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ModelPricing } from '@/components/ModelPricing';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'nostr-identity' | 'model-selection' | 'conclusion';
|
||||
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion';
|
||||
|
||||
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [step, setStep] = useState<OnboardingStep>('welcome');
|
||||
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
|
||||
const [providerApiKey, setProviderApiKey] = useState<string>('');
|
||||
@@ -41,8 +35,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
|
||||
const [modelSearchQuery, setModelSearchQuery] = useState('');
|
||||
const [generatedNsec, setGeneratedNsec] = useState<string>('');
|
||||
|
||||
// Ref for the scrollable content area
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
@@ -52,35 +44,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
const login = useLoginActions();
|
||||
const { models, isLoading: isLoadingModels } = useProviderModels();
|
||||
|
||||
// Fetch credits for the selected provider (only if it's a Nostr provider and user is logged in)
|
||||
const creditsQuery = useAICredits(
|
||||
selectedProvider && selectedProvider.nostr && user
|
||||
? {
|
||||
id: selectedProvider.id,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr,
|
||||
}
|
||||
: { id: '', baseURL: '', nostr: undefined }
|
||||
);
|
||||
|
||||
// Filter models to only show selected provider models
|
||||
const providerModels = selectedProvider
|
||||
? models.filter(model => model.provider === selectedProvider.id)
|
||||
: [];
|
||||
|
||||
// Filter models by search query
|
||||
const filteredModels = modelSearchQuery
|
||||
? providerModels.filter(model => {
|
||||
const searchLower = modelSearchQuery.toLowerCase();
|
||||
const modelName = (model.name || model.id).toLowerCase();
|
||||
const modelDescription = (model.description || '').toLowerCase();
|
||||
return modelName.includes(searchLower) || modelDescription.includes(searchLower);
|
||||
})
|
||||
: providerModels;
|
||||
|
||||
// Determine if we should show descriptions (only if 8 or fewer models)
|
||||
const showDescriptions = providerModels.length <= 8;
|
||||
|
||||
const handleGetStarted = () => {
|
||||
setStep('open-source');
|
||||
};
|
||||
@@ -111,14 +79,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
setIsSettingUp(true);
|
||||
|
||||
try {
|
||||
// If user is not logged in and provider uses Nostr auth, generate key and show identity step
|
||||
// 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);
|
||||
setGeneratedNsec(nsec);
|
||||
setStep('nostr-identity');
|
||||
setIsSettingUp(false);
|
||||
return;
|
||||
login.nsec(nsec);
|
||||
}
|
||||
|
||||
// Add selected provider to their config
|
||||
@@ -139,34 +104,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}
|
||||
};
|
||||
|
||||
const handleContinueFromNostrIdentity = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
setIsSettingUp(true);
|
||||
|
||||
try {
|
||||
// If no user is logged in yet, log in with generated key
|
||||
if (!user && generatedNsec) {
|
||||
login.nsec(generatedNsec);
|
||||
}
|
||||
|
||||
// Add selected provider to their config
|
||||
const providerConfig = {
|
||||
id: selectedProvider.id,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
};
|
||||
setProvider(providerConfig);
|
||||
|
||||
// Move to model selection
|
||||
setStep('model-selection');
|
||||
} catch (error) {
|
||||
console.error('Failed to set up user:', error);
|
||||
} finally {
|
||||
setIsSettingUp(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleModelSelect = (modelFullId: string) => {
|
||||
setSelectedModel(modelFullId);
|
||||
};
|
||||
@@ -183,12 +120,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
|
||||
);
|
||||
|
||||
// Only show credits dialog if the provider uses Nostr AND the model is paid
|
||||
if (!isFreeModel && selectedProvider?.nostr) {
|
||||
setShowCreditsDialog(true);
|
||||
} else {
|
||||
// Free model or non-Nostr provider, go straight to conclusion
|
||||
if (isFreeModel) {
|
||||
// Free model, go straight to conclusion
|
||||
setStep('conclusion');
|
||||
} else {
|
||||
// Paid model, show credits dialog
|
||||
setShowCreditsDialog(true);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -212,8 +149,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
setShowCreditsDialog(false);
|
||||
setAgreedToTerms(false);
|
||||
setAgreedToProviderTerms(false);
|
||||
setModelSearchQuery('');
|
||||
setGeneratedNsec('');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
@@ -250,24 +185,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'nostr-identity' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('provider-selection')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'model-selection' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
// Go back to nostr-identity if we have a generated key, otherwise provider-selection
|
||||
setStep(generatedNsec ? 'nostr-identity' : 'provider-selection');
|
||||
}}
|
||||
onClick={() => setStep('provider-selection')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
@@ -284,7 +206,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xl">
|
||||
{step === 'model-selection' && t('chooseYourAIModel')}
|
||||
{step === 'model-selection' && 'Choose Your AI Model'}
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -297,25 +219,26 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</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">
|
||||
{t('welcomeToShakespeareOnboarding')}
|
||||
Welcome to Shakespeare!
|
||||
</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
{t('aiPoweredDevelopmentAssistant')}
|
||||
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>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-lg mx-auto">
|
||||
<div className="text-center space-y-2">
|
||||
<div className="text-2xl">💡</div>
|
||||
<p className="text-sm text-muted-foreground">{t('aiPoweredDevelopment')}</p>
|
||||
<p className="text-sm text-muted-foreground">AI-Powered Development</p>
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<div className="text-2xl">⚡</div>
|
||||
<p className="text-sm text-muted-foreground">{t('nostrIntegration')}</p>
|
||||
<p className="text-sm text-muted-foreground">Nostr Integration</p>
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<div className="text-2xl">🚀</div>
|
||||
<p className="text-sm text-muted-foreground">{t('instantPreview')}</p>
|
||||
<p className="text-sm text-muted-foreground">Instant Preview</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
@@ -327,12 +250,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
{isSettingUp ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
|
||||
{t('settingUp')}
|
||||
Setting up...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
{t('getStarted')}
|
||||
Get Started
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
@@ -344,36 +267,38 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">
|
||||
{t('shakespeareOpenSource')}
|
||||
Shakespeare is Open Source software that runs entirely in your web 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">{t('yourDeviceConnects')}</p>
|
||||
<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">{t('filesStoredOnDevice')}</p>
|
||||
<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">{t('carefulBrowserData')}</p>
|
||||
<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">{t('responsibleBackups')}</p>
|
||||
<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">{t('qualityDependsOnInput')}</p>
|
||||
<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">
|
||||
{t('shakespeareNotCloudService')}
|
||||
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">
|
||||
@@ -386,7 +311,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
htmlFor="agree-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('iAgree')}
|
||||
I agree
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -397,7 +322,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
disabled={!agreedToTerms}
|
||||
className="gap-2 rounded-full w-full max-w-md"
|
||||
>
|
||||
{t('continueButton')}
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -407,9 +332,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
{step === 'provider-selection' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">{t('chooseAIProvider')}</h2>
|
||||
<h2 className="text-2xl font-bold">Choose your AI provider</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
{t('selectAIProviderDescription')}
|
||||
Select an AI provider to power your development assistant. You can add more providers later in settings.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -427,12 +352,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
onClick={() => handleProviderSelect(provider)}
|
||||
>
|
||||
<div className="flex items-center justify-between p-3">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<ExternalFavicon
|
||||
url={provider.baseURL}
|
||||
size={20}
|
||||
fallback={<Bot size={20} />}
|
||||
/>
|
||||
<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,
|
||||
})}>
|
||||
@@ -458,28 +378,27 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
{selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedProvider.id === 'routstr' ? (
|
||||
t('requiresCashuToken', { providerName: selectedProvider.name })
|
||||
<>{selectedProvider.name} requires a Cashu token</>
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
|
||||
{selectedProvider.apiKeysURL ? (
|
||||
{selectedProvider.name} requires an {selectedProvider.apiKeysURL ? (
|
||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
||||
{t('apiKey')}
|
||||
API key
|
||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
t('apiKey')
|
||||
<>API key</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<PasswordInput
|
||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
placeholder={selectedProvider.id === 'routstr' ? 'Enter a Cashu Token' : 'Enter your API key'}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -504,7 +423,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: selectedProvider.name })}{' '}
|
||||
I agree to {selectedProvider.name}'s{' '}
|
||||
{selectedProvider.tosURL ? (
|
||||
<a
|
||||
href={selectedProvider.tosURL}
|
||||
@@ -513,10 +432,10 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
className="text-primary underline hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{t('termsOfService')}
|
||||
Terms of Service
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
'Terms of Service'
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
@@ -533,50 +452,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
!!(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" />
|
||||
{t('settingUp')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{t('continueButton')}
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'nostr-identity' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">Your Nostr Account</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
This is the account that will be used with {selectedProvider?.name}.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center space-y-4">
|
||||
<LoginArea className="w-full max-w-xs" />
|
||||
|
||||
{user && creditsQuery.data && (
|
||||
<div className="flex items-center gap-2 text-sm bg-muted/50 px-4 py-2 rounded-full">
|
||||
<Coins className="h-4 w-4 text-primary" />
|
||||
<span className="font-semibold">
|
||||
{creditsQuery.data.amount.toLocaleString()} credits available
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleContinueFromNostrIdentity}
|
||||
disabled={isSettingUp}
|
||||
className="gap-2 rounded-full w-full max-w-md"
|
||||
>
|
||||
{isSettingUp ? (
|
||||
<>
|
||||
@@ -596,22 +471,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
|
||||
{step === 'model-selection' && (
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Search filter - only show if more than 8 models */}
|
||||
{!isLoadingModels && providerModels.length > 8 && (
|
||||
<div className="mb-4 flex-shrink-0">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={t('searchModels')}
|
||||
value={modelSearchQuery}
|
||||
onChange={(e) => setModelSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-y-auto min-h-0 my-4">
|
||||
<div className="space-y-3 p-1">
|
||||
{isLoadingModels ? (
|
||||
@@ -632,17 +491,17 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</Card>
|
||||
))}
|
||||
</>
|
||||
) : filteredModels.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" />
|
||||
<p className="text-muted-foreground">
|
||||
{modelSearchQuery ? t('noModelsMatchingSearch') : t('noModelsAvailable')}
|
||||
No models available. Please check your connection and try again.
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
filteredModels.map((model) => {
|
||||
providerModels.map((model) => {
|
||||
const isSelected = selectedModel === model.fullId;
|
||||
const modelName = model.name || model.id;
|
||||
|
||||
@@ -661,7 +520,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<span>{modelName}</span>
|
||||
{model.pricing && <ModelPricing pricing={model.pricing} />}
|
||||
</CardTitle>
|
||||
{showDescriptions && model.description && (
|
||||
{model.description && (
|
||||
<p className="text-lg text-muted-foreground mt-1">
|
||||
{model.description.length > 500
|
||||
? model.description.slice(0, 500) + '...'
|
||||
@@ -689,7 +548,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
disabled={!selectedModel}
|
||||
className="gap-2"
|
||||
>
|
||||
{t('continueButton')}
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -700,14 +559,15 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<div className="text-center space-y-6 py-8">
|
||||
<div className="text-5xl mb-4">🎉</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">{t('nowYoureReady')}</h2>
|
||||
<h2 className="text-2xl font-bold">Now you're ready to build!</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
{t('aiAssistantConfigured')}
|
||||
Your AI assistant is configured and ready to help.
|
||||
Just enter your prompt to start building amazing Nostr applications.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleFinish} size="lg" className="gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
{t('startBuilding')}
|
||||
Start Building
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRegisterSW } from 'virtual:pwa-register/react';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Component that prompts users to update when a new service worker is available
|
||||
*/
|
||||
export function PWAUpdatePrompt() {
|
||||
const [showPrompt, setShowPrompt] = useState(false);
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
|
||||
const {
|
||||
offlineReady: [offlineReady],
|
||||
needRefresh: [needRefresh],
|
||||
updateServiceWorker,
|
||||
} = useRegisterSW({
|
||||
onRegisteredSW(swUrl, registration) {
|
||||
console.log('[PWA] Service worker registered:', swUrl);
|
||||
|
||||
// Check for updates periodically (every hour)
|
||||
if (registration) {
|
||||
const intervalId = setInterval(async () => {
|
||||
try {
|
||||
await registration.update();
|
||||
} catch (error) {
|
||||
// Registration may no longer be valid, clear the interval
|
||||
console.warn('[PWA] Failed to check for updates:', error);
|
||||
clearInterval(intervalId);
|
||||
}
|
||||
}, 60 * 60 * 1000);
|
||||
}
|
||||
},
|
||||
onRegisterError(error) {
|
||||
console.error('[PWA] Service worker registration error:', error);
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (offlineReady) {
|
||||
console.log('[PWA] App ready to work offline');
|
||||
}
|
||||
}, [offlineReady]);
|
||||
|
||||
useEffect(() => {
|
||||
if (needRefresh) {
|
||||
setShowPrompt(true);
|
||||
}
|
||||
}, [needRefresh]);
|
||||
|
||||
const handleUpdate = () => {
|
||||
setIsUpdating(true);
|
||||
updateServiceWorker(true);
|
||||
};
|
||||
|
||||
if (!showPrompt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full">
|
||||
<button
|
||||
onClick={handleUpdate}
|
||||
disabled={isUpdating}
|
||||
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
|
||||
>
|
||||
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
|
||||
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
|
||||
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { usePlugins } from '@/hooks/usePlugins';
|
||||
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
export function PluginsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
|
||||
const [gitUrl, setGitUrl] = useState('');
|
||||
|
||||
const handleAddPlugin = async () => {
|
||||
if (!gitUrl.trim()) return;
|
||||
|
||||
try {
|
||||
const pluginName = await clonePlugin.mutateAsync({ gitUrl: gitUrl.trim() });
|
||||
toast({
|
||||
title: t('pluginAdded'),
|
||||
description: t('pluginAddedDescription', { name: pluginName }),
|
||||
});
|
||||
setGitUrl('');
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('pluginAddFailed'),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleSyncPlugin = async (pluginName: string) => {
|
||||
try {
|
||||
await syncPlugin.mutateAsync(pluginName);
|
||||
toast({
|
||||
title: t('pluginSynced'),
|
||||
description: t('pluginSyncedDescription', { name: pluginName }),
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('pluginSyncFailed'),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeletePlugin = async (pluginName: string) => {
|
||||
try {
|
||||
await deletePlugin.mutateAsync(pluginName);
|
||||
toast({
|
||||
title: t('pluginDeleted'),
|
||||
description: t('pluginDeletedDescription', { name: pluginName }),
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('pluginDeleteFailed'),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Group skills by plugin
|
||||
const skillsByPlugin = skills.reduce((acc, skill) => {
|
||||
if (!acc[skill.plugin]) {
|
||||
acc[skill.plugin] = [];
|
||||
}
|
||||
acc[skill.plugin].push(skill);
|
||||
return acc;
|
||||
}, {} as Record<string, typeof skills>);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Divider */}
|
||||
<Separator className="my-6" />
|
||||
|
||||
{/* Plugins Header */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Puzzle className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('plugins')}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('pluginsDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Configured Plugins List */}
|
||||
{plugins.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{plugins.map((pluginName) => {
|
||||
const pluginSkills = skillsByPlugin[pluginName] || [];
|
||||
const isSyncing = syncPlugin.isPending && syncPlugin.variables === pluginName;
|
||||
const isDeleting = deletePlugin.isPending && deletePlugin.variables === pluginName;
|
||||
|
||||
return <PluginItem
|
||||
key={pluginName}
|
||||
pluginName={pluginName}
|
||||
pluginSkills={pluginSkills}
|
||||
isSyncing={isSyncing}
|
||||
isDeleting={isDeleting}
|
||||
onSync={handleSyncPlugin}
|
||||
onDelete={handleDeletePlugin}
|
||||
/>;
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Alert>
|
||||
<AlertDescription className="text-sm">
|
||||
{t('noPluginsConfigured')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Add Plugin Section */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="add-plugin" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">{t('addPlugin')}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="plugin-git-url">{t('gitRepositoryUrl')}</Label>
|
||||
<Input
|
||||
id="plugin-git-url"
|
||||
placeholder="https://github.com/user/plugin.git"
|
||||
value={gitUrl}
|
||||
onChange={(e) => setGitUrl(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && gitUrl.trim()) {
|
||||
handleAddPlugin();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleAddPlugin}
|
||||
disabled={!gitUrl.trim() || clonePlugin.isPending}
|
||||
className="gap-2 w-full"
|
||||
>
|
||||
{clonePlugin.isPending ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t('cloning')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Check className="h-4 w-4" />
|
||||
{t('addPlugin')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('pluginDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface PluginItemProps {
|
||||
pluginName: string;
|
||||
pluginSkills: Array<{ name: string; description: string; path: string; plugin: string }>;
|
||||
isSyncing: boolean;
|
||||
isDeleting: boolean;
|
||||
onSync: (pluginName: string) => void;
|
||||
onDelete: (pluginName: string) => void;
|
||||
}
|
||||
|
||||
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete }: PluginItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: gitInfo } = usePluginGitInfo(pluginName);
|
||||
|
||||
return (
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value={pluginName} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Puzzle className="h-4 w-4 text-primary" />
|
||||
<span className="font-medium">{pluginName}</span>
|
||||
{pluginSkills.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
({pluginSkills.length} {pluginSkills.length === 1 ? 'skill' : 'skills'})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
{/* Skills List */}
|
||||
{pluginSkills.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">{t('skills')}</Label>
|
||||
<div className="space-y-1">
|
||||
{pluginSkills.map((skill) => (
|
||||
<div
|
||||
key={skill.name}
|
||||
className="flex items-start gap-2 p-2 rounded-md bg-muted/50"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium font-mono">{skill.name}</div>
|
||||
<div className="text-xs text-muted-foreground line-clamp-2">
|
||||
{skill.description}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pluginSkills.length === 0 && (
|
||||
<Alert>
|
||||
<AlertDescription className="text-xs">
|
||||
{t('noSkillsFound')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Plugin Actions and Git Info */}
|
||||
<div className="space-y-2 pt-2">
|
||||
{gitInfo && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<code className="bg-muted px-1.5 py-0.5 rounded">{gitInfo.commitHash.substring(0, 7)}</code>
|
||||
<span>•</span>
|
||||
<span>{gitInfo.commitDate.toLocaleDateString()}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onSync(pluginName)}
|
||||
disabled={isSyncing || isDeleting}
|
||||
className="flex-1"
|
||||
>
|
||||
{isSyncing ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('syncing')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
{t('sync')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => onDelete(pluginName)}
|
||||
disabled={isSyncing || isDeleting}
|
||||
className="flex-1"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('deleting')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,6 @@ import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
@@ -51,7 +50,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
const [newProjectName, setNewProjectName] = useState(project.id);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -145,7 +143,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const zip = new JSZip();
|
||||
const projectPath = `${projectsPath}/${project.id}`;
|
||||
const projectPath = `/projects/${project.id}`;
|
||||
|
||||
// Recursive function to add files and directories to zip from a specific project
|
||||
const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { GitBranch, Upload, AlertTriangle, X } from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
|
||||
interface PushReminderDialogProps {
|
||||
projectId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onDisableReminders: () => void;
|
||||
onDismiss: () => void;
|
||||
}
|
||||
|
||||
export function PushReminderDialog({
|
||||
projectId,
|
||||
open,
|
||||
onOpenChange,
|
||||
onDisableReminders,
|
||||
onDismiss,
|
||||
}: PushReminderDialogProps) {
|
||||
const [dontShowAgain, setDontShowAgain] = useState(false);
|
||||
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Close the reminder dialog when git dialog opens
|
||||
useEffect(() => {
|
||||
if (isGitDialogOpen) {
|
||||
onOpenChange(false);
|
||||
onDismiss();
|
||||
}
|
||||
}, [isGitDialogOpen, onOpenChange, onDismiss]);
|
||||
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasNoRemote = gitStatus.remotes.length === 0;
|
||||
const hasCommitsAhead = gitStatus.ahead > 0;
|
||||
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
|
||||
|
||||
const handleDismiss = () => {
|
||||
if (dontShowAgain) {
|
||||
onDisableReminders();
|
||||
}
|
||||
onDismiss();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handlePrimaryAction = () => {
|
||||
if (dontShowAgain) {
|
||||
onDisableReminders();
|
||||
}
|
||||
|
||||
if (hasNoRemote) {
|
||||
// Close reminder dialog and open git dialog
|
||||
onOpenChange(false);
|
||||
setIsGitDialogOpen(true);
|
||||
} else {
|
||||
// Close reminder dialog and open git dialog for push
|
||||
onOpenChange(false);
|
||||
setIsGitDialogOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
// Determine dialog content based on git status
|
||||
let icon = AlertTriangle;
|
||||
let iconColor = 'text-amber-600 dark:text-amber-500';
|
||||
let title = '';
|
||||
let description = '';
|
||||
let primaryActionLabel = '';
|
||||
|
||||
if (hasNoRemote) {
|
||||
icon = GitBranch;
|
||||
iconColor = 'text-yellow-600 dark:text-yellow-500';
|
||||
title = 'No Remote Repository Configured';
|
||||
description = 'Your work is only stored locally in your browser. Configure a remote repository to prevent data loss if you clear your browser data.';
|
||||
primaryActionLabel = 'Configure Remote';
|
||||
} else if (hasCommitsAhead) {
|
||||
icon = Upload;
|
||||
iconColor = 'text-blue-600 dark:text-blue-500';
|
||||
title = 'Unpushed Commits';
|
||||
description = `You have ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} that ${gitStatus.ahead !== 1 ? 'haven\'t' : 'hasn\'t'} been pushed to your remote repository. Push your changes to prevent data loss.`;
|
||||
primaryActionLabel = 'Push Changes';
|
||||
} else if (hasUncommittedChanges) {
|
||||
icon = AlertTriangle;
|
||||
iconColor = 'text-amber-600 dark:text-amber-500';
|
||||
title = 'Uncommitted Changes';
|
||||
description = `You have ${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}. Commit and push your changes to keep your work safe.`;
|
||||
primaryActionLabel = 'Commit & Push';
|
||||
}
|
||||
|
||||
const Icon = icon;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className={`rounded-full p-2 bg-muted ${iconColor}`}>
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<DialogTitle className="text-left">{title}</DialogTitle>
|
||||
<DialogDescription className="text-left mt-2">
|
||||
{description}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 -mt-1"
|
||||
onClick={handleDismiss}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-start gap-2 p-3 rounded-md bg-muted/50 border">
|
||||
<Checkbox
|
||||
id="dont-show"
|
||||
checked={dontShowAgain}
|
||||
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
|
||||
/>
|
||||
<div className="grid gap-1.5 leading-none">
|
||||
<Label
|
||||
htmlFor="dont-show"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
Don't show this again
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
You can re-enable push reminders in Settings > Preferences
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex-col sm:flex-row gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleDismiss}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
Remind Me Later
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handlePrimaryAction}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{primaryActionLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Git Dialog - opened when user clicks primary action */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={isGitDialogOpen}
|
||||
onOpenChange={setIsGitDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { AlertTriangle, Upload, GitBranch } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
|
||||
interface PushWarningButtonProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
variant?: 'icon' | 'full';
|
||||
}
|
||||
|
||||
export function PushWarningButton({
|
||||
projectId,
|
||||
className,
|
||||
variant = 'icon'
|
||||
}: PushWarningButtonProps) {
|
||||
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Determine warning state
|
||||
const hasNoRemote = gitStatus.remotes.length === 0;
|
||||
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
|
||||
const hasCommitsAhead = gitStatus.ahead > 0;
|
||||
|
||||
// Don't show if everything is synced
|
||||
if (!hasNoRemote && !hasUncommittedChanges && !hasCommitsAhead) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Determine icon and message
|
||||
let icon = AlertTriangle;
|
||||
let message = '';
|
||||
let action = '';
|
||||
|
||||
if (hasNoRemote) {
|
||||
icon = GitBranch;
|
||||
message = 'No remote configured';
|
||||
action = 'Configure remote to prevent data loss';
|
||||
} else if (hasCommitsAhead) {
|
||||
icon = Upload;
|
||||
message = `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} not pushed`;
|
||||
action = 'Push to remote';
|
||||
} else if (hasUncommittedChanges) {
|
||||
icon = AlertTriangle;
|
||||
message = `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`;
|
||||
action = 'Commit and push your changes';
|
||||
}
|
||||
|
||||
const Icon = icon;
|
||||
|
||||
const handleClick = () => {
|
||||
if (hasNoRemote) {
|
||||
// If no remote, open git dialog to configure
|
||||
setIsGitDialogOpen(true);
|
||||
} else {
|
||||
// If remote exists, open git dialog for push/commit
|
||||
setIsGitDialogOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
if (variant === 'icon') {
|
||||
return (
|
||||
<>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleClick}
|
||||
className={cn(
|
||||
"h-8 w-8 p-0",
|
||||
hasNoRemote && "text-yellow-600 hover:text-yellow-700 dark:text-yellow-500 dark:hover:text-yellow-400",
|
||||
hasCommitsAhead && "text-blue-600 hover:text-blue-700 dark:text-blue-500 dark:hover:text-blue-400",
|
||||
hasUncommittedChanges && !hasCommitsAhead && "text-amber-600 hover:text-amber-700 dark:text-amber-500 dark:hover:text-amber-400",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 animate-pulse" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">{message}</p>
|
||||
<p className="text-xs text-muted-foreground">{action}</p>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={isGitDialogOpen}
|
||||
onOpenChange={setIsGitDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Full button variant
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClick}
|
||||
className={cn(
|
||||
"gap-2 border-2",
|
||||
hasNoRemote && "border-yellow-500/50 bg-yellow-50 hover:bg-yellow-100 dark:bg-yellow-950/20 dark:hover:bg-yellow-950/30 text-yellow-700 dark:text-yellow-400",
|
||||
hasCommitsAhead && "border-blue-500/50 bg-blue-50 hover:bg-blue-100 dark:bg-blue-950/20 dark:hover:bg-blue-950/30 text-blue-700 dark:text-blue-400",
|
||||
hasUncommittedChanges && !hasCommitsAhead && "border-amber-500/50 bg-amber-50 hover:bg-amber-100 dark:bg-amber-950/20 dark:hover:bg-amber-950/30 text-amber-700 dark:text-amber-400",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 animate-pulse" />
|
||||
<span className="text-sm font-medium">{message}</span>
|
||||
</Button>
|
||||
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={isGitDialogOpen}
|
||||
onOpenChange={setIsGitDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, X, Wifi, Settings } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
interface Relay {
|
||||
url: string;
|
||||
read: boolean;
|
||||
write: boolean;
|
||||
}
|
||||
|
||||
export function RelayListManager() {
|
||||
const { t } = useTranslation();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent } = useNostrPublish();
|
||||
|
||||
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
|
||||
const [newRelayUrl, setNewRelayUrl] = useState('');
|
||||
|
||||
// Sync local state with config when it changes (e.g., from NostrProvider sync)
|
||||
useEffect(() => {
|
||||
setRelays(config.relayMetadata.relays);
|
||||
}, [config.relayMetadata.relays]);
|
||||
|
||||
const normalizeRelayUrl = (url: string): string => {
|
||||
url = url.trim();
|
||||
try {
|
||||
return new URL(url).toString();
|
||||
} catch {
|
||||
try {
|
||||
return new URL(`wss://${url}`).toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const isValidRelayUrl = (url: string): boolean => {
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return false;
|
||||
|
||||
const normalized = normalizeRelayUrl(trimmed);
|
||||
try {
|
||||
new URL(normalized);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddRelay = () => {
|
||||
if (!isValidRelayUrl(newRelayUrl)) {
|
||||
toast({
|
||||
title: t('invalidRelayUrl'),
|
||||
description: t('invalidRelayUrlDescription'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = normalizeRelayUrl(newRelayUrl);
|
||||
|
||||
if (relays.some(r => r.url === normalized)) {
|
||||
toast({
|
||||
title: t('relayAlreadyExists'),
|
||||
description: t('relayAlreadyExistsDescription'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newRelays = [...relays, { url: normalized, read: true, write: true }];
|
||||
setRelays(newRelays);
|
||||
setNewRelayUrl('');
|
||||
|
||||
saveRelays(newRelays);
|
||||
};
|
||||
|
||||
const handleRemoveRelay = (url: string) => {
|
||||
const newRelays = relays.filter(r => r.url !== url);
|
||||
setRelays(newRelays);
|
||||
saveRelays(newRelays);
|
||||
};
|
||||
|
||||
const handleToggleRead = (url: string) => {
|
||||
const newRelays = relays.map(r =>
|
||||
r.url === url ? { ...r, read: !r.read } : r
|
||||
);
|
||||
setRelays(newRelays);
|
||||
saveRelays(newRelays);
|
||||
};
|
||||
|
||||
const handleToggleWrite = (url: string) => {
|
||||
const newRelays = relays.map(r =>
|
||||
r.url === url ? { ...r, write: !r.write } : r
|
||||
);
|
||||
setRelays(newRelays);
|
||||
saveRelays(newRelays);
|
||||
};
|
||||
|
||||
const saveRelays = (newRelays: Relay[]) => {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Update local config
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
relayMetadata: {
|
||||
relays: newRelays,
|
||||
updatedAt: now,
|
||||
},
|
||||
}));
|
||||
|
||||
// Publish to Nostr if user is logged in
|
||||
if (user) {
|
||||
publishNIP65RelayList(newRelays);
|
||||
}
|
||||
};
|
||||
|
||||
const publishNIP65RelayList = (relayList: Relay[]) => {
|
||||
const tags = relayList.map(relay => {
|
||||
if (relay.read && relay.write) {
|
||||
return ['r', relay.url];
|
||||
} else if (relay.read) {
|
||||
return ['r', relay.url, 'read'];
|
||||
} else if (relay.write) {
|
||||
return ['r', relay.url, 'write'];
|
||||
}
|
||||
// If neither read nor write, don't include (shouldn't happen)
|
||||
return null;
|
||||
}).filter((tag): tag is string[] => tag !== null);
|
||||
|
||||
publishEvent(
|
||||
{
|
||||
kind: 10002,
|
||||
content: '',
|
||||
tags,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: t('relayListPublished'),
|
||||
description: t('relayListPublishedDescription'),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to publish relay list:', error);
|
||||
toast({
|
||||
title: t('relayListPublishFailed'),
|
||||
description: t('relayListPublishFailedDescription'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const renderRelayUrl = (url: string): string => {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol === 'wss:') {
|
||||
if (parsed.pathname === '/') {
|
||||
return parsed.host;
|
||||
} else {
|
||||
return parsed.host + parsed.pathname;
|
||||
}
|
||||
} else {
|
||||
return parsed.href;
|
||||
}
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Relay List */}
|
||||
<div className="space-y-2">
|
||||
{relays.map((relay) => (
|
||||
<div
|
||||
key={relay.url}
|
||||
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
|
||||
>
|
||||
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
|
||||
{renderRelayUrl(relay.url)}
|
||||
</span>
|
||||
|
||||
{/* Settings Popover */}
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-48" align="end">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
|
||||
{t('read')}
|
||||
</Label>
|
||||
<Switch
|
||||
id={`read-${relay.url}`}
|
||||
checked={relay.read}
|
||||
onCheckedChange={() => handleToggleRead(relay.url)}
|
||||
className="data-[state=checked]:bg-green-500 scale-75"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
|
||||
{t('write')}
|
||||
</Label>
|
||||
<Switch
|
||||
id={`write-${relay.url}`}
|
||||
checked={relay.write}
|
||||
onCheckedChange={() => handleToggleWrite(relay.url)}
|
||||
className="data-[state=checked]:bg-blue-500 scale-75"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Remove Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemoveRelay(relay.url)}
|
||||
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
|
||||
disabled={relays.length <= 1}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add Relay Form */}
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="new-relay-url" className="sr-only">
|
||||
{t('relayUrl')}
|
||||
</Label>
|
||||
<Input
|
||||
id="new-relay-url"
|
||||
placeholder={t('enterRelayUrl')}
|
||||
value={newRelayUrl}
|
||||
onChange={(e) => setNewRelayUrl(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleAddRelay();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleAddRelay}
|
||||
disabled={!newRelayUrl.trim()}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-10 shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t('addRelay')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{!user && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('loginToSyncRelays')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { useState } from "react";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
|
||||
interface RelaySelectorProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RelaySelector(props: RelaySelectorProps) {
|
||||
const { className } = props;
|
||||
const { config, updateConfig, presetRelays = [] } = useAppContext();
|
||||
|
||||
const selectedRelay = config.relayUrl;
|
||||
const setSelectedRelay = (relay: string) => {
|
||||
updateConfig((current) => ({ ...current, relayUrl: relay }));
|
||||
};
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [inputValue, setInputValue] = useState("");
|
||||
|
||||
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
|
||||
|
||||
// Function to normalize relay URL by adding wss:// if no protocol is present
|
||||
const normalizeRelayUrl = (url: string): string => {
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return trimmed;
|
||||
|
||||
// Check if it already has a protocol
|
||||
if (trimmed.includes('://')) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// Add wss:// prefix
|
||||
return `wss://${trimmed}`;
|
||||
};
|
||||
|
||||
// Handle adding a custom relay
|
||||
const handleAddCustomRelay = (url: string) => {
|
||||
setSelectedRelay?.(normalizeRelayUrl(url));
|
||||
setOpen(false);
|
||||
setInputValue("");
|
||||
};
|
||||
|
||||
// Check if input value looks like a valid relay URL
|
||||
const isValidRelayInput = (value: string): boolean => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return false;
|
||||
|
||||
// Basic validation - should contain at least a domain-like structure
|
||||
const normalized = normalizeRelayUrl(trimmed);
|
||||
try {
|
||||
new URL(normalized);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn("justify-between", className)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Wifi className="h-4 w-4" />
|
||||
<span className="truncate">
|
||||
{selectedOption
|
||||
? selectedOption.name
|
||||
: selectedRelay
|
||||
? selectedRelay.replace(/^wss?:\/\//, '')
|
||||
: "Select relay..."
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[300px] p-0">
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder="Search relays or type URL..."
|
||||
value={inputValue}
|
||||
onValueChange={setInputValue}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{inputValue && isValidRelayInput(inputValue) ? (
|
||||
<CommandItem
|
||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">Add custom relay</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{normalizeRelayUrl(inputValue)}
|
||||
</span>
|
||||
</div>
|
||||
</CommandItem>
|
||||
) : (
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
{inputValue ? "Invalid relay URL" : "No relay found."}
|
||||
</div>
|
||||
)}
|
||||
</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{presetRelays
|
||||
.filter((option) =>
|
||||
!inputValue ||
|
||||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
|
||||
option.url.toLowerCase().includes(inputValue.toLowerCase())
|
||||
)
|
||||
.map((option) => (
|
||||
<CommandItem
|
||||
key={option.url}
|
||||
value={option.url}
|
||||
onSelect={(currentValue) => {
|
||||
setSelectedRelay(normalizeRelayUrl(currentValue));
|
||||
setOpen(false);
|
||||
setInputValue("");
|
||||
}}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedRelay === option.url ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{option.name}</span>
|
||||
<span className="text-xs text-muted-foreground">{option.url}</span>
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
{inputValue && isValidRelayInput(inputValue) && (
|
||||
<CommandItem
|
||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
||||
className="cursor-pointer border-t"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">Add custom relay</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{normalizeRelayUrl(inputValue)}
|
||||
</span>
|
||||
</div>
|
||||
</CommandItem>
|
||||
)}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import { SentryProvider } from './SentryProvider';
|
||||
import { AppContext } from '@/contexts/AppContext';
|
||||
import * as sentryModule from '@/lib/sentry';
|
||||
|
||||
// Mock the sentry module
|
||||
vi.mock('@/lib/sentry', () => ({
|
||||
initializeSentry: vi.fn(() => Promise.resolve()),
|
||||
disableSentry: vi.fn(() => Promise.resolve()),
|
||||
isSentryInitialized: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
describe('SentryProvider', () => {
|
||||
const mockUpdateConfig = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('initializes Sentry when both DSN and sentryEnabled are true', async () => {
|
||||
const config = {
|
||||
sentryDsn: 'https://[email protected]/123',
|
||||
sentryEnabled: true,
|
||||
theme: 'light' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
</AppContext.Provider>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sentryModule.initializeSentry).toHaveBeenCalledWith('https://[email protected]/123');
|
||||
});
|
||||
});
|
||||
|
||||
it('does not initialize Sentry when DSN is empty', async () => {
|
||||
const config = {
|
||||
sentryDsn: '',
|
||||
sentryEnabled: true,
|
||||
theme: 'light' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
</AppContext.Provider>
|
||||
);
|
||||
|
||||
// Wait a bit to ensure no initialization happens
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(sentryModule.initializeSentry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not initialize Sentry when sentryEnabled is false', async () => {
|
||||
const config = {
|
||||
sentryDsn: 'https://[email protected]/123',
|
||||
sentryEnabled: false,
|
||||
theme: 'light' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
</AppContext.Provider>
|
||||
);
|
||||
|
||||
// Wait a bit to ensure no initialization happens
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(sentryModule.initializeSentry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables Sentry when it was initialized but conditions change', async () => {
|
||||
// Mock that Sentry is initialized
|
||||
vi.mocked(sentryModule.isSentryInitialized).mockReturnValue(true);
|
||||
|
||||
const config = {
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
theme: 'light' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
</AppContext.Provider>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sentryModule.disableSentry).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { ReactNode, useEffect } from 'react';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { initializeSentry, disableSentry, isSentryInitialized } from '@/lib/sentry';
|
||||
|
||||
interface SentryProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SentryProvider({ children }: SentryProviderProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
const shouldEnableSentry = config.sentryDsn && config.sentryEnabled;
|
||||
|
||||
if (shouldEnableSentry && !isSentryInitialized()) {
|
||||
// Initialize Sentry
|
||||
initializeSentry(config.sentryDsn).catch(console.error);
|
||||
} else if (!shouldEnableSentry && isSentryInitialized()) {
|
||||
// Disable Sentry
|
||||
disableSentry().catch(console.error);
|
||||
}
|
||||
}, [config.sentryDsn, config.sentryEnabled]);
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { ReactNode, useMemo, useEffect } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
@@ -17,7 +16,6 @@ interface SessionManagerProviderProps {
|
||||
*/
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath, pluginsPath } = useFSPaths();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
@@ -26,8 +24,8 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
|
||||
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy);
|
||||
}, [fs, settings, models, user, metadata, config.corsProxy]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -7,13 +7,11 @@ import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Loader2, ChevronDown } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
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 { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
@@ -30,11 +28,9 @@ import { NostrReadTagTool } from '@/lib/tools/NostrReadTagTool';
|
||||
import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool';
|
||||
import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { SkillTool } from '@/lib/tools/SkillTool';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
@@ -52,7 +48,6 @@ interface ChatPaneProps {
|
||||
onNewChat: () => void;
|
||||
onFirstInteraction?: () => void;
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
onMessageSent?: () => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
consoleError?: ProjectPreviewConsoleError | null;
|
||||
@@ -68,7 +63,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onNewChat,
|
||||
onFirstInteraction,
|
||||
onLoadingChange,
|
||||
onMessageSent,
|
||||
isLoading: externalIsLoading,
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
consoleError,
|
||||
@@ -81,7 +75,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
const { config } = useAppContext();
|
||||
const { projectsPath, tmpPath, pluginsPath } = useFSPaths();
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
@@ -140,22 +133,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const esmUrlRef = useRef(config.esmUrl);
|
||||
const sessionManager = useSessionManager();
|
||||
|
||||
// Callback to emit file changes for auto-build
|
||||
const handleFileChanged = useCallback((filePath: string) => {
|
||||
// Emit the fileChanged event through the session manager
|
||||
sessionManager.emit('fileChanged', projectId, filePath);
|
||||
}, [sessionManager, projectId]);
|
||||
|
||||
const customTools = useMemo(() => {
|
||||
const baseTools = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
||||
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd),
|
||||
text_editor_write: new TextEditorWriteTool(fs, cwd),
|
||||
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, esmUrlRef.current),
|
||||
@@ -167,10 +152,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_protocol: new NostrReadProtocolTool(),
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
nostr_publish_events: new NostrPublishEventsTool(),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
skill: new SkillTool(fs, pluginsPath),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
@@ -182,7 +165,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
|
||||
}, [fs, git, cwd, user, projectId]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
@@ -455,7 +438,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
||||
const savedPath = await saveFileToTmp(fs, file);
|
||||
return `Added file: ${savedPath}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
@@ -480,12 +463,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
|
||||
// Notify parent that a message was sent (for push reminder tracking)
|
||||
if (onMessageSent) {
|
||||
onMessageSent();
|
||||
}
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, onMessageSent]);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
|
||||
|
||||
// Handle textarea focus - show onboarding if not configured
|
||||
const handleTextareaFocus = useCallback(() => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
@@ -90,7 +89,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Use console error state from provider
|
||||
@@ -508,7 +506,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
if (!selectedFile) return;
|
||||
|
||||
try {
|
||||
await fs.writeFile(`${projectsPath}/${projectId}/${selectedFile}`, content);
|
||||
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
|
||||
setFileContent(content);
|
||||
|
||||
// Automatically trigger a rebuild after saving a file
|
||||
@@ -741,10 +739,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<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" />
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-medium">Building project...</span>
|
||||
<span className="text-xs text-muted-foreground">Preview will update automatically</span>
|
||||
</div>
|
||||
<span className="text-sm font-medium">Building project...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -4,9 +4,9 @@ export interface ShakespeareLogoProps {
|
||||
|
||||
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
|
||||
return (
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
|
||||
+17
-59
@@ -5,9 +5,7 @@ import { Copy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
@@ -34,13 +32,11 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const shellToolRef = useRef<ShellTool | null>(null);
|
||||
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
|
||||
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
@@ -49,7 +45,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git, projectsPath, user?.signer]);
|
||||
}, [projectId, fs, git]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
@@ -83,7 +79,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
}, []);
|
||||
|
||||
const executeCommand = useCallback(async (command: string) => {
|
||||
if (!command.trim()) return;
|
||||
if (!shellToolRef.current || !command.trim()) return;
|
||||
|
||||
// Add command to history
|
||||
if (command.trim() && !commandHistory.includes(command.trim())) {
|
||||
@@ -97,59 +93,21 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
setIsExecuting(true);
|
||||
|
||||
try {
|
||||
// Handle special clear command
|
||||
if (command.trim() === 'clear') {
|
||||
// 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([]);
|
||||
setIsExecuting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if running in Electron - use real shell
|
||||
if (window.electron?.shell) {
|
||||
// Use the full path (with ~ if present) - Electron will expand it
|
||||
const fullCwd = `${projectsPath}/${projectId}`;
|
||||
|
||||
const result = await window.electron.shell.exec(command, fullCwd);
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
|
||||
if (result.stdout) {
|
||||
output += result.stdout;
|
||||
}
|
||||
|
||||
if (result.stderr) {
|
||||
if (output) output += '\n';
|
||||
output += result.stderr;
|
||||
}
|
||||
|
||||
// Add exit code info for non-zero exits
|
||||
if (result.exitCode !== 0) {
|
||||
if (output) output += '\n';
|
||||
output += `Exit code: ${result.exitCode}`;
|
||||
}
|
||||
|
||||
if (output) {
|
||||
addLine('output', output);
|
||||
}
|
||||
} else {
|
||||
// Use virtual shell (browser mode)
|
||||
if (!shellToolRef.current) return;
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -157,7 +115,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory, projectId, projectsPath]);
|
||||
}, [addLine, commandHistory]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -232,7 +190,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{containsAnsiCodes(line.content)
|
||||
{containsAnsiCodes(line.content)
|
||||
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
|
||||
: line.content}
|
||||
</pre>
|
||||
|
||||
@@ -6,11 +6,9 @@ import { Button } from '@/components/ui/button';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -47,7 +45,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
|
||||
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { git } = useGit();
|
||||
const { toast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
@@ -58,7 +55,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Check if git repository exists
|
||||
try {
|
||||
@@ -81,7 +78,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [git, projectId, projectsPath]);
|
||||
}, [git, projectId]);
|
||||
|
||||
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
|
||||
if (!fs) return;
|
||||
@@ -89,7 +86,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
setIsRollingBack(targetCommit.oid);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Get the current HEAD commit
|
||||
const currentCommit = await git.resolveRef({
|
||||
@@ -230,7 +227,7 @@ ${commitsToRevert.map(c => {
|
||||
} finally {
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]);
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen]);
|
||||
|
||||
const resetToHead = useCallback(async () => {
|
||||
if (!fs) return;
|
||||
@@ -238,7 +235,7 @@ ${commitsToRevert.map(c => {
|
||||
setIsRollingBack('HEAD');
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Get the current HEAD commit
|
||||
const headCommit = await git.resolveRef({
|
||||
@@ -329,7 +326,7 @@ ${commitsToRevert.map(c => {
|
||||
} finally {
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]);
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -337,6 +334,24 @@ ${commitsToRevert.map(c => {
|
||||
}
|
||||
}, [isOpen, loadGitHistory]);
|
||||
|
||||
const formatRelativeTime = (timestamp: number) => {
|
||||
const now = Date.now();
|
||||
const commitTime = timestamp * 1000;
|
||||
const diffMs = now - commitTime;
|
||||
|
||||
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffMinutes < 60) {
|
||||
return `${diffMinutes} minutes ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours} hours ago`;
|
||||
} else {
|
||||
return `${diffDays} days ago`;
|
||||
}
|
||||
};
|
||||
|
||||
const getCommitMessageLines = (message: string) => {
|
||||
const lines = message.split('\n').filter(line => line.trim() !== '');
|
||||
return {
|
||||
|
||||
@@ -9,6 +9,13 @@ vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
|
||||
// Mock the RelaySelector component
|
||||
vi.mock('@/components/RelaySelector', () => ({
|
||||
RelaySelector: ({ className }: { className?: string }) => (
|
||||
<div data-testid="relay-selector" className={className}>Relay Selector</div>
|
||||
)
|
||||
}));
|
||||
|
||||
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
|
||||
|
||||
describe('AccountSwitcher', () => {
|
||||
|
||||
@@ -31,7 +31,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-muted/50 transition-all w-full text-foreground'>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
|
||||
<Avatar className='w-10 h-10'>
|
||||
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
|
||||
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
|
||||
|
||||
@@ -29,6 +29,12 @@ vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('@/components/RelaySelector', () => ({
|
||||
RelaySelector: ({ className }: { className?: string }) => (
|
||||
<div data-testid="relay-selector" className={className}>Relay Selector</div>
|
||||
)
|
||||
}));
|
||||
|
||||
vi.mock('./SimpleLoginDialog', () => ({
|
||||
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
|
||||
isOpen ? <div data-testid="login-dialog">Login Dialog</div> : null
|
||||
|
||||
@@ -42,7 +42,7 @@ export function LoginArea({ className }: LoginAreaProps) {
|
||||
) : (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-muted/50 transition-all w-full text-foreground'>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
|
||||
<Avatar className='w-10 h-10'>
|
||||
<AvatarFallback>
|
||||
<User className='w-5 h-5 text-muted-foreground' />
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
describe('AnnounceRepositoryDialog - NIP-34 Tag Structure', () => {
|
||||
it('should create tags with multiple values in single tag per NIP-34', () => {
|
||||
// Test the tag structure that would be created
|
||||
const webUrls = ['https://example.com/browse', 'https://mirror.example.com'];
|
||||
const cloneUrls = [
|
||||
'https://git.shakespeare.diy/npub1.../repo.git',
|
||||
'https://relay.ngit.dev/npub1.../repo.git',
|
||||
];
|
||||
const relays = ['wss://git.shakespeare.diy', 'wss://relay.ngit.dev'];
|
||||
|
||||
const tags: string[][] = [['d', 'test-repo']];
|
||||
|
||||
// Simulate the tag creation logic from AnnounceRepositoryDialog
|
||||
if (webUrls.length > 0) {
|
||||
const trimmedUrls = webUrls.map((url) => url.trim()).filter((url) => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['web', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
if (cloneUrls.length > 0) {
|
||||
const trimmedUrls = cloneUrls.map((url) => url.trim()).filter((url) => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['clone', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
if (relays.length > 0) {
|
||||
const trimmedRelays = relays.map((relay) => relay.trim()).filter((relay) => relay);
|
||||
if (trimmedRelays.length > 0) {
|
||||
tags.push(['relays', ...trimmedRelays]);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the structure matches NIP-34 spec
|
||||
expect(tags).toEqual([
|
||||
['d', 'test-repo'],
|
||||
['web', 'https://example.com/browse', 'https://mirror.example.com'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../repo.git',
|
||||
'https://relay.ngit.dev/npub1.../repo.git',
|
||||
],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
|
||||
]);
|
||||
|
||||
// Verify we have single tags with multiple values, not multiple tags
|
||||
const cloneTags = tags.filter((t) => t[0] === 'clone');
|
||||
expect(cloneTags.length).toBe(1);
|
||||
expect(cloneTags[0].length).toBe(3); // ['clone', url1, url2]
|
||||
|
||||
const relayTags = tags.filter((t) => t[0] === 'relays');
|
||||
expect(relayTags.length).toBe(1);
|
||||
expect(relayTags[0].length).toBe(3); // ['relays', relay1, relay2]
|
||||
});
|
||||
|
||||
it('should handle reading relays from single tag with multiple values', () => {
|
||||
// Simulate the event structure from Nostr
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
|
||||
],
|
||||
};
|
||||
|
||||
// Simulate the reading logic from PullRequestDialog
|
||||
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
|
||||
let publishRelays: string[] = [];
|
||||
|
||||
if (relayTag && relayTag.length > 1) {
|
||||
publishRelays = relayTag.slice(1);
|
||||
}
|
||||
|
||||
// Verify we extracted all relay URLs correctly
|
||||
expect(publishRelays).toEqual(['wss://git.shakespeare.diy', 'wss://relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should handle reading clone URLs from single tag with multiple values', () => {
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
],
|
||||
],
|
||||
};
|
||||
|
||||
const cloneTag = repoEvent.tags.find((t: string[]) => t[0] === 'clone');
|
||||
let cloneUrls: string[] = [];
|
||||
|
||||
if (cloneTag && cloneTag.length > 1) {
|
||||
cloneUrls = cloneTag.slice(1);
|
||||
}
|
||||
|
||||
expect(cloneUrls).toEqual([
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle reading maintainers from single tag with multiple values', () => {
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
|
||||
],
|
||||
};
|
||||
|
||||
// Simulate the reading logic from NostrGitProvider
|
||||
const maintainerTag = repoEvent.tags.find((t: string[]) => t[0] === 'maintainers');
|
||||
const maintainers = maintainerTag ? maintainerTag.slice(1) : [];
|
||||
|
||||
expect(maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
|
||||
});
|
||||
});
|
||||
@@ -9,88 +9,61 @@ import {
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
GitBranch,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
Plus,
|
||||
X,
|
||||
Settings,
|
||||
ChevronDown,
|
||||
Megaphone,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import {
|
||||
createRepositoryAnnouncementEvent,
|
||||
createRepositoryNaddr,
|
||||
validateRepositoryAnnouncementData,
|
||||
validateRepositoryId,
|
||||
parseRepositoryAnnouncement,
|
||||
} from '@/lib/announceRepository';
|
||||
|
||||
export interface AnnounceRepositoryResult {
|
||||
repoId: string;
|
||||
cloneUrls: string[];
|
||||
relays: string[];
|
||||
naddr: string;
|
||||
}
|
||||
|
||||
interface AnnounceRepositoryDialogProps {
|
||||
projectId: string;
|
||||
remoteUrl?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onSuccess?: (result: AnnounceRepositoryResult) => void;
|
||||
/** Repository naddr to edit (if editing existing repo) */
|
||||
editNaddr?: string;
|
||||
}
|
||||
|
||||
export function AnnounceRepositoryDialog({
|
||||
projectId,
|
||||
remoteUrl,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
editNaddr,
|
||||
}: AnnounceRepositoryDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(open ?? false);
|
||||
const [isPrepopulated, setIsPrepopulated] = useState(false);
|
||||
const [repoId, setRepoId] = useState('');
|
||||
const [repoIdError, setRepoIdError] = useState<string | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [webUrls, setWebUrls] = useState<string[]>([]);
|
||||
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
|
||||
const [relays, setRelays] = 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 { projectsPath } = useFSPaths();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
const { config } = useAppContext();
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
@@ -98,24 +71,22 @@ export function AnnounceRepositoryDialog({
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Convert projectId to kebab-case for repo ID
|
||||
const toKebabCase = (str: string): string => {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
};
|
||||
|
||||
// Validate repository ID on change
|
||||
const handleRepoIdChange = (value: string) => {
|
||||
setRepoId(value);
|
||||
try {
|
||||
validateRepositoryId(value);
|
||||
setRepoIdError(null);
|
||||
} catch (err) {
|
||||
setRepoIdError(err instanceof Error ? err.message : 'Invalid repository ID');
|
||||
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 {
|
||||
@@ -134,111 +105,14 @@ export function AnnounceRepositoryDialog({
|
||||
}
|
||||
}, [git, projectPath]);
|
||||
|
||||
const prepopulateFields = useCallback(async () => {
|
||||
// Set default repo ID from project ID (kebab-case)
|
||||
const defaultRepoId = toKebabCase(projectId);
|
||||
setRepoId(defaultRepoId);
|
||||
|
||||
// Set default name from project ID (title case)
|
||||
const defaultName = projectId
|
||||
.split(/[-_]/)
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
setName(defaultName);
|
||||
|
||||
// Only prepopulate if the arrays are empty (user hasn't made changes yet)
|
||||
if (cloneUrls.length === 0 && relays.length === 0) {
|
||||
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
|
||||
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
|
||||
// Clone URLs: https://{server}/{npub}/{repo-id}.git
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const cloneUrls = config.ngitServers.map(server =>
|
||||
`https://${server}/${npub}/${defaultRepoId}.git`
|
||||
);
|
||||
setCloneUrls(cloneUrls);
|
||||
|
||||
// Relay URLs: wss://{server}
|
||||
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
|
||||
setRelays(relayUrls);
|
||||
} else {
|
||||
// Fallback to write relays if no ngitServers configured
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
|
||||
}
|
||||
}
|
||||
|
||||
// Get earliest commit
|
||||
await getEarliestCommit();
|
||||
}, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]);
|
||||
|
||||
// Load existing repository data if editing
|
||||
useEffect(() => {
|
||||
const loadExistingRepo = async () => {
|
||||
if (!editNaddr || !isOpen) return;
|
||||
|
||||
try {
|
||||
// Decode the naddr to get repository coordinates
|
||||
const decoded = nip19.decode(editNaddr);
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Invalid repository identifier');
|
||||
}
|
||||
|
||||
const { identifier, pubkey, kind, relays: naddrRelays } = decoded.data;
|
||||
|
||||
// Query for the repository announcement event
|
||||
const filter = {
|
||||
kinds: [kind],
|
||||
authors: [pubkey],
|
||||
'#d': [identifier],
|
||||
};
|
||||
|
||||
const signal = AbortSignal.timeout(3000);
|
||||
const readRelays = config.relayMetadata.relays
|
||||
.filter(r => r.read)
|
||||
.map(r => r.url);
|
||||
const events = await nostr.query([filter], {
|
||||
signal,
|
||||
relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : readRelays
|
||||
});
|
||||
|
||||
if (events.length === 0) {
|
||||
throw new Error('Repository announcement not found');
|
||||
}
|
||||
|
||||
// Use the most recent event
|
||||
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
setRepoId(parsed.identifier);
|
||||
setName(parsed.name || '');
|
||||
setDescription(parsed.description || '');
|
||||
setWebUrls(parsed.webUrls);
|
||||
setCloneUrls(parsed.httpsCloneUrls);
|
||||
setRelays(parsed.relays);
|
||||
setEarliestCommit(parsed.earliestCommit || '');
|
||||
|
||||
setIsPrepopulated(true);
|
||||
} catch (error) {
|
||||
console.error('Failed to load repository data:', error);
|
||||
toast({
|
||||
title: 'Failed to load repository',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen && editNaddr) {
|
||||
loadExistingRepo();
|
||||
} else if (isOpen && !isPrepopulated) {
|
||||
prepopulateFields();
|
||||
setIsPrepopulated(true);
|
||||
if (isOpen && remoteUrl) {
|
||||
// Parse remote URL to pre-fill data
|
||||
parseRemoteUrl(remoteUrl);
|
||||
// Get earliest commit
|
||||
getEarliestCommit();
|
||||
}
|
||||
}, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]);
|
||||
}, [isOpen, remoteUrl, parseRemoteUrl, getEarliestCommit]);
|
||||
|
||||
const addWebUrl = () => {
|
||||
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
|
||||
@@ -252,20 +126,8 @@ export function AnnounceRepositoryDialog({
|
||||
};
|
||||
|
||||
const addCloneUrl = () => {
|
||||
const trimmedUrl = newCloneUrl.trim();
|
||||
|
||||
// Prevent nostr:// URLs in clone URLs
|
||||
if (trimmedUrl.startsWith('nostr://')) {
|
||||
toast({
|
||||
title: 'Invalid clone URL',
|
||||
description: 'Clone URLs must be HTTPS URLs, not nostr:// URLs',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (trimmedUrl && !cloneUrls.includes(trimmedUrl)) {
|
||||
setCloneUrls([...cloneUrls, trimmedUrl]);
|
||||
if (newCloneUrl.trim() && !cloneUrls.includes(newCloneUrl.trim())) {
|
||||
setCloneUrls([...cloneUrls, newCloneUrl.trim()]);
|
||||
setNewCloneUrl('');
|
||||
}
|
||||
};
|
||||
@@ -295,27 +157,69 @@ export function AnnounceRepositoryDialog({
|
||||
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 {
|
||||
// Validate data
|
||||
validateRepositoryAnnouncementData({
|
||||
repoId,
|
||||
cloneUrls,
|
||||
// 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()]);
|
||||
});
|
||||
|
||||
// Create repository announcement event using shared utility
|
||||
const repoEvent = createRepositoryAnnouncementEvent({
|
||||
repoId,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
earliestCommit,
|
||||
// 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);
|
||||
@@ -328,35 +232,24 @@ export function AnnounceRepositoryDialog({
|
||||
console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`);
|
||||
|
||||
// Publish to Nostr relays
|
||||
// Repository announcements go to: write relays + relays specified in the announcement
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
const publishRelays = [...new Set([...writeRelays, ...relays])];
|
||||
console.log('Publishing repository announcement to relays:', publishRelays);
|
||||
|
||||
await nostr.event(signedEvent, { relays: publishRelays });
|
||||
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 using shared utility
|
||||
const naddr = createRepositoryNaddr(repoId, user.pubkey, relays);
|
||||
|
||||
toast({
|
||||
title: 'Published Nostr announcement',
|
||||
description: 'Configuring repository...',
|
||||
// Create naddr for the repository
|
||||
const naddr = nip19.naddrEncode({
|
||||
identifier: repoId.trim(),
|
||||
pubkey: user.pubkey,
|
||||
kind: 30617,
|
||||
relays: relays.length > 0 ? relays : undefined,
|
||||
});
|
||||
|
||||
// Close the dialog
|
||||
handleOpenChange(false);
|
||||
setCreatedNaddr(naddr);
|
||||
|
||||
// Call success callback with the data needed for Git operations
|
||||
onSuccess?.({
|
||||
repoId: repoId.trim(),
|
||||
cloneUrls,
|
||||
relays,
|
||||
naddr,
|
||||
toast({
|
||||
title: 'Repository announced!',
|
||||
description: 'Your repository has been announced on Nostr',
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
@@ -365,7 +258,6 @@ export function AnnounceRepositoryDialog({
|
||||
title: 'Failed to announce repository',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
@@ -378,7 +270,6 @@ export function AnnounceRepositoryDialog({
|
||||
|
||||
// Reset form when closing
|
||||
if (!newOpen) {
|
||||
setIsPrepopulated(false);
|
||||
setRepoId('');
|
||||
setName('');
|
||||
setDescription('');
|
||||
@@ -386,6 +277,7 @@ export function AnnounceRepositoryDialog({
|
||||
setCloneUrls([]);
|
||||
setRelays(['wss://relay.nostr.band']);
|
||||
setEarliestCommit('');
|
||||
setCreatedNaddr(null);
|
||||
setError(null);
|
||||
setNewWebUrl('');
|
||||
setNewCloneUrl('');
|
||||
@@ -393,294 +285,284 @@ export function AnnounceRepositoryDialog({
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
<Settings className="h-5 w-5" />
|
||||
{editNaddr ? 'Edit' : ''} Nostr Repository Settings
|
||||
<Megaphone className="h-5 w-5" />
|
||||
Announce Repository on Nostr
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{editNaddr
|
||||
? 'Update your repository announcement (NIP-34) for Nostr git clients'
|
||||
: 'Configure your repository announcement (NIP-34) for Nostr git clients'
|
||||
}
|
||||
Publish a repository announcement (NIP-34) to make it discoverable on Nostr git
|
||||
clients
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<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"
|
||||
value={repoId}
|
||||
onChange={(e) => handleRepoIdChange(e.target.value)}
|
||||
disabled={isCreating}
|
||||
className={repoIdError ? 'border-destructive' : ''}
|
||||
/>
|
||||
{repoIdError ? (
|
||||
<p className="text-xs text-destructive">{repoIdError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Kebab-case short name (e.g., "my-project", "awesome-app")
|
||||
</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}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Display name for your repository
|
||||
{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>
|
||||
|
||||
{/* 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>
|
||||
|
||||
{/* Advanced Settings */}
|
||||
<Collapsible open={showAdvanced} onOpenChange={setShowAdvanced}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<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="ghost"
|
||||
className="w-full justify-between p-0 hover:bg-transparent"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={copyNaddr}
|
||||
>
|
||||
<span className="text-sm font-medium">Advanced Settings</span>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${
|
||||
showAdvanced ? 'rotate-180' : ''
|
||||
}`}
|
||||
/>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-6 pt-4">
|
||||
{/* 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}
|
||||
onChange={(e) => {
|
||||
const newUrls = [...webUrls];
|
||||
newUrls[index] = e.target.value;
|
||||
setWebUrls(newUrls);
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<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>Git Server Clone URLs</Label>
|
||||
<div className="space-y-2">
|
||||
{cloneUrls.map((url, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
const newUrls = [...cloneUrls];
|
||||
newUrls[index] = e.target.value;
|
||||
setCloneUrls(newUrls);
|
||||
}}
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<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="https://gitnostr.com/..."
|
||||
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">
|
||||
HTTPS URLs for cloning the repository (nostr:// URLs not allowed)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Relays */}
|
||||
<div className="space-y-2">
|
||||
<Label>Git Nostr Relays</Label>
|
||||
<div className="space-y-2">
|
||||
{relays.map((relay, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={relay}
|
||||
onChange={(e) => {
|
||||
const newRelays = [...relays];
|
||||
newRelays[index] = e.target.value;
|
||||
setRelays(newRelays);
|
||||
}}
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<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">
|
||||
Nostr relays where patches and issues 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)
|
||||
</p>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Share this address with others to let them find your repository
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
) : (
|
||||
// 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>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
{/* 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 || !!repoIdError || !repoId.trim()}
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{editNaddr ? 'Updating...' : 'Publishing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
{editNaddr ? 'Update on Nostr' : 'Publish to Nostr'}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</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>
|
||||
);
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
ArrowUpRight,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -60,9 +59,8 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
|
||||
const [switchingToBranch, setSwitchingToBranch] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
const loadBranches = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
@@ -213,7 +211,6 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
force: true,
|
||||
});
|
||||
|
||||
toast({
|
||||
|
||||
@@ -10,7 +10,6 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { GitCompare, Loader2, GitCommit, FileIcon } from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { DiffViewer } from './DiffViewer';
|
||||
|
||||
@@ -39,9 +38,8 @@ export function CompareView({ projectId }: CompareViewProps) {
|
||||
} | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
const loadReferences = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
Check,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -58,10 +57,9 @@ export function DiffViewer({ projectId, compareFrom = 'HEAD', compareTo, filepat
|
||||
const [copiedHunk, setCopiedHunk] = useState<number | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise<string[]> => {
|
||||
// Get list of files from both refs and find differences
|
||||
|
||||
@@ -20,9 +20,8 @@ import { DiffViewer } from './DiffViewer';
|
||||
import { PullRequestForm } from './PullRequestForm';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
|
||||
interface GitManagementDialogProps{
|
||||
interface GitManagementDialogProps {
|
||||
projectId: string;
|
||||
children?: React.ReactNode;
|
||||
open?: boolean;
|
||||
@@ -40,8 +39,7 @@ export function GitManagementDialog({
|
||||
const [activeTab, setActiveTab] = useState(defaultTab);
|
||||
const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
@@ -78,10 +77,9 @@ export function MergeDialog({
|
||||
const [mergeComplete, setMergeComplete] = useState(false);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
|
||||
@@ -32,14 +32,12 @@ import {
|
||||
GitFork,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
|
||||
@@ -86,13 +84,12 @@ export function PullRequestDialog({
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { config } = useAppContext();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
@@ -704,46 +701,92 @@ export function PullRequestDialog({
|
||||
'#d': [info.repo],
|
||||
limit: 1,
|
||||
}
|
||||
], { signal: AbortSignal.timeout(3000) });
|
||||
]);
|
||||
|
||||
console.log(`Repository announcement query returned ${repoEvents.length} events`);
|
||||
|
||||
let earliestUniqueCommit: string | null = null;
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
let publishRelays = writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']; // Use write relays
|
||||
let publishRelays = [config.relayUrl]; // Use configured relay
|
||||
|
||||
if (repoEvents.length > 0) {
|
||||
const repoEvent = repoEvents[0];
|
||||
console.log('Found repository announcement event:', repoEvent);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get earliest unique commit from repository announcement
|
||||
if (repoAnn.earliestCommit) {
|
||||
earliestUniqueCommit = repoAnn.earliestCommit;
|
||||
const eucTag = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc');
|
||||
if (eucTag) {
|
||||
earliestUniqueCommit = eucTag[1];
|
||||
console.log('Found earliest unique commit:', earliestUniqueCommit);
|
||||
} else {
|
||||
console.warn('No euc tag found in repository announcement');
|
||||
}
|
||||
|
||||
// Get relay hints from repository announcement
|
||||
if (repoAnn.relays.length > 0) {
|
||||
publishRelays = repoAnn.relays;
|
||||
const relayTags = repoEvent.tags.filter((t: string[]) => t[0] === 'relays');
|
||||
if (relayTags.length > 0) {
|
||||
publishRelays = relayTags.map((t: string[]) => t[1]);
|
||||
console.log('Publishing to repository relays:', publishRelays);
|
||||
} else {
|
||||
console.log('No relay hints in repository announcement, using configured relay');
|
||||
}
|
||||
} else {
|
||||
console.error('Repository announcement not found');
|
||||
throw new Error(
|
||||
'Repository announcement not found.\n\n' +
|
||||
`The repository owner has not published a repository announcement (kind 30617) for ${info.owner}/${info.repo}.\n\n` +
|
||||
'Patches can only be submitted to repositories that have been announced on Nostr. ' +
|
||||
'Please contact the repository owner to announce their repository first.'
|
||||
);
|
||||
console.log('Repository announcement not found - creating one automatically');
|
||||
|
||||
// Auto-announce repository
|
||||
try {
|
||||
// Get earliest commit for euc tag
|
||||
const commits = await git.log({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
let euc: string | null = null;
|
||||
if (commits.length > 0) {
|
||||
euc = commits[commits.length - 1].oid;
|
||||
}
|
||||
|
||||
// Build repository announcement event
|
||||
const repoTags: string[][] = [
|
||||
['d', info.repo],
|
||||
['name', info.repo.split('/').pop() || info.repo],
|
||||
['clone', remoteUrl || ''],
|
||||
['relays', config.relayUrl],
|
||||
];
|
||||
|
||||
if (euc) {
|
||||
repoTags.push(['r', euc, 'euc']);
|
||||
earliestUniqueCommit = euc;
|
||||
}
|
||||
|
||||
const repoAnnouncement = {
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags: repoTags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
console.log('Auto-creating repository announcement:', repoAnnouncement);
|
||||
|
||||
const signedRepoEvent = await user.signer.signEvent(repoAnnouncement);
|
||||
|
||||
console.log('Signed repository announcement:', signedRepoEvent);
|
||||
|
||||
await nostr.event(signedRepoEvent);
|
||||
|
||||
console.log('Successfully auto-announced repository');
|
||||
|
||||
toast({
|
||||
title: 'Repository announced',
|
||||
description: 'Automatically created repository announcement for patch submission',
|
||||
});
|
||||
} catch (announceError) {
|
||||
console.error('Failed to auto-announce repository:', announceError);
|
||||
throw new Error(
|
||||
'Repository announcement not found and failed to create one automatically.\n\n' +
|
||||
`Error: ${announceError instanceof Error ? announceError.message : 'Unknown error'}\n\n` +
|
||||
'Please try using the "Announce Repository" button manually.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate git format-patch style content
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
GitFork,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
@@ -60,10 +59,9 @@ export function PullRequestForm({ projectId, currentBranch, remoteUrl }: PullReq
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// All the helper functions from PullRequestDialog can be reused here
|
||||
// (parseRemoteUrl, checkPushPermissions, ensureFork, etc.)
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface FileUploadAreaProps {
|
||||
selectedFile: File | null;
|
||||
isDragOver: boolean;
|
||||
isValid: boolean;
|
||||
onFileSelect: (file: File) => void;
|
||||
onFileRemove: () => void;
|
||||
onDragOver: (e: React.DragEvent) => void;
|
||||
onDragLeave: (e: React.DragEvent) => void;
|
||||
onDrop: (e: React.DragEvent) => void;
|
||||
disabled?: boolean;
|
||||
accept?: string;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function FileUploadArea({
|
||||
selectedFile,
|
||||
isDragOver,
|
||||
isValid,
|
||||
onFileSelect,
|
||||
onFileRemove,
|
||||
onDragOver,
|
||||
onDragLeave,
|
||||
onDrop,
|
||||
disabled = false,
|
||||
accept = '.zip',
|
||||
className,
|
||||
children
|
||||
}: FileUploadAreaProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
onFileSelect(files[0]);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50",
|
||||
selectedFile && isValid && "border-green-500/50 bg-green-500/5",
|
||||
selectedFile && !isValid && "border-destructive/50 bg-destructive/5",
|
||||
disabled && "opacity-50 cursor-not-allowed",
|
||||
className
|
||||
)}
|
||||
onClick={!disabled ? handleClickUpload : undefined}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={handleFileChange}
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
{children || (
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
isValid ? (
|
||||
<div className="h-8 w-8 rounded-full bg-green-100 flex items-center justify-center">
|
||||
<svg className="h-4 w-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-8 w-8 rounded-full bg-red-100 flex items-center justify-center">
|
||||
<svg className="h-4 w-4 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center">
|
||||
<svg className="h-4 w-4 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">{selectedFile.name}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
disabled={disabled}
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{accept === '.zip' ? 'ZIP files only' : `Accepted files: ${accept}`}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,26 +2,17 @@ import { createContext } from "react";
|
||||
|
||||
export type Theme = "dark" | "light" | "system";
|
||||
|
||||
export interface RelayMetadata {
|
||||
/** List of relays with read/write permissions */
|
||||
relays: { url: string; read: boolean; write: boolean }[];
|
||||
/** Unix timestamp of when the relay list was last updated */
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
/** Current theme */
|
||||
theme: Theme;
|
||||
/** NIP-65 relay list metadata */
|
||||
relayMetadata: RelayMetadata;
|
||||
/** Selected relay URL */
|
||||
relayUrl: string;
|
||||
/** Git repository URL to use as project template */
|
||||
projectTemplate: string;
|
||||
/** ESM CDN URL for package imports */
|
||||
esmUrl: string;
|
||||
/** HTTP proxy used to bypass CORS for AI and Git operations */
|
||||
corsProxy: string;
|
||||
/** Favicon URL template (e.g., "https://external-content.duckduckgo.com/ip3/{hostname}.ico") */
|
||||
faviconUrl: string;
|
||||
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
|
||||
previewDomain: string;
|
||||
/** Selected language */
|
||||
@@ -32,18 +23,6 @@ export interface AppConfig {
|
||||
showcaseModerator: string;
|
||||
/** Nostr Git Servers (hostnames) */
|
||||
ngitServers: string[];
|
||||
/** VFS path for projects directory */
|
||||
fsPathProjects: string;
|
||||
/** VFS path for config directory */
|
||||
fsPathConfig: string;
|
||||
/** VFS path for temporary files directory */
|
||||
fsPathTmp: string;
|
||||
/** VFS path for plugins directory */
|
||||
fsPathPlugins: string;
|
||||
/** Sentry DSN for error reporting (empty string = disabled) */
|
||||
sentryDsn: string;
|
||||
/** Whether the user has enabled Sentry error reporting */
|
||||
sentryEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
@@ -51,6 +30,8 @@ export interface AppContextType {
|
||||
config: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
||||
@@ -41,24 +41,14 @@ describe('useAIProjectId', () => {
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config: {
|
||||
theme: 'dark',
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
relayUrl: 'wss://relay.damus.io',
|
||||
projectTemplate: 'https://github.com/example/template',
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
},
|
||||
updateConfig: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -52,7 +52,7 @@ export function useAppSubmissions() {
|
||||
authors: [addrData.pubkey],
|
||||
'#d': [addrData.identifier],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(1000) });
|
||||
}]);
|
||||
|
||||
if (teamEvents.length > 0) {
|
||||
const teamEvent = teamEvents[0];
|
||||
@@ -72,27 +72,39 @@ export function useAppSubmissions() {
|
||||
const submissionEvents = await nostr.query([{
|
||||
kinds: [APP_SUBMISSION_KIND],
|
||||
'#t': ['soapbox-app-submission'],
|
||||
limit: 100,
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
limit: 1000
|
||||
}]);
|
||||
|
||||
// Get list events from moderators (NIP-51 kind 30267)
|
||||
const moderatorListEvents = await nostr.query([{
|
||||
// Get featured app lists from moderators (NIP-51 kind 30267)
|
||||
const featuredLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': [
|
||||
'soapbox-featured-apps',
|
||||
'soapbox-approved-apps',
|
||||
'soapbox-homepage-apps',
|
||||
],
|
||||
limit: 3,
|
||||
}], { signal: AbortSignal.timeout(1000) });
|
||||
'#d': ['soapbox-featured-apps'],
|
||||
limit: 10
|
||||
}]);
|
||||
|
||||
// Get approved app lists from moderators (NIP-51 kind 30267)
|
||||
const approvedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 10
|
||||
}]);
|
||||
|
||||
// Get homepage app lists from moderators (NIP-51 kind 30267)
|
||||
const homepageLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-homepage-apps'],
|
||||
limit: 10
|
||||
}]);
|
||||
|
||||
// Get reporting events for hidden apps (NIP-56 kind 1984)
|
||||
const reportEvents = await nostr.query([{
|
||||
kinds: [1984],
|
||||
authors: [MODERATOR_HEX],
|
||||
limit: 1000
|
||||
}], { signal: AbortSignal.timeout(1000) });
|
||||
}]);
|
||||
|
||||
// Process submissions and apply moderation
|
||||
const submissions: AppSubmission[] = [];
|
||||
@@ -110,30 +122,43 @@ export function useAppSubmissions() {
|
||||
}
|
||||
|
||||
// Get the latest featured list
|
||||
const featuredList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-featured-apps'));
|
||||
const approvedList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-approved-apps'));
|
||||
const homepageList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-homepage-apps'));
|
||||
const latestFeaturedList = featuredLists.reduce((latest, current) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get the latest approved list
|
||||
const latestApprovedList = approvedLists.reduce((latest, current) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get the latest homepage list
|
||||
const latestHomepageList = homepageLists.reduce((latest, current) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Extract featured app coordinates from the list
|
||||
const featuredAppCoords = new Set<string>();
|
||||
if (featuredList) {
|
||||
featuredList.tags
|
||||
if (latestFeaturedList) {
|
||||
latestFeaturedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => featuredAppCoords.add(tag[1]));
|
||||
}
|
||||
|
||||
// Extract approved app coordinates from the list
|
||||
const approvedAppCoords = new Set<string>();
|
||||
if (approvedList) {
|
||||
approvedList.tags
|
||||
if (latestApprovedList) {
|
||||
latestApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => approvedAppCoords.add(tag[1]));
|
||||
}
|
||||
|
||||
// Extract homepage app coordinates from the list
|
||||
const homepageAppCoords = new Set<string>();
|
||||
if (homepageList) {
|
||||
homepageList.tags
|
||||
if (latestHomepageList) {
|
||||
latestHomepageList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => homepageAppCoords.add(tag[1]));
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import { useEffect, useRef, useCallback } from 'react';
|
||||
import { BuildDebouncer } from '@/lib/BuildDebouncer';
|
||||
import { useBuildProject } from './useBuildProject';
|
||||
import { useSessionSubscription } from './useSessionSubscription';
|
||||
|
||||
interface UseAutoBuildOptions {
|
||||
projectId: string;
|
||||
enabled?: boolean;
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook that automatically builds a project when files are changed by the AI.
|
||||
* Uses a debouncer to avoid excessive builds.
|
||||
*/
|
||||
export function useAutoBuild({
|
||||
projectId,
|
||||
enabled = true,
|
||||
debounceMs = 2000
|
||||
}: UseAutoBuildOptions) {
|
||||
const { mutate: buildProject, isPending: isBuildPending } = useBuildProject(projectId);
|
||||
|
||||
const debouncerRef = useRef<BuildDebouncer | null>(null);
|
||||
|
||||
// Initialize debouncer
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleBuild = (buildProjectId: string, changedFiles: string[]) => {
|
||||
console.log(`Auto-building project ${buildProjectId} after changes to:`, changedFiles);
|
||||
buildProject();
|
||||
};
|
||||
|
||||
debouncerRef.current = new BuildDebouncer(debounceMs, handleBuild);
|
||||
|
||||
return () => {
|
||||
debouncerRef.current?.cleanup();
|
||||
debouncerRef.current = null;
|
||||
};
|
||||
}, [enabled, debounceMs, buildProject]);
|
||||
|
||||
// Listen for file changes from the session manager
|
||||
useSessionSubscription('fileChanged', (changedProjectId: string, filePath: string) => {
|
||||
if (changedProjectId === projectId && enabled && debouncerRef.current) {
|
||||
console.log(`File changed in project ${projectId}:`, filePath);
|
||||
debouncerRef.current.registerFileChange(projectId, filePath);
|
||||
}
|
||||
}, [projectId, enabled]);
|
||||
|
||||
// Cancel pending builds when AI stops loading
|
||||
useSessionSubscription('loadingChanged', (changedProjectId: string, isLoading: boolean) => {
|
||||
if (changedProjectId === projectId && !isLoading && enabled && debouncerRef.current) {
|
||||
// When AI stops, trigger any pending build immediately
|
||||
if (debouncerRef.current.hasPendingChanges(projectId)) {
|
||||
console.log(`AI stopped, triggering pending build for ${projectId}`);
|
||||
debouncerRef.current.triggerBuild(projectId);
|
||||
}
|
||||
}
|
||||
}, [projectId, enabled]);
|
||||
|
||||
const triggerBuild = useCallback(() => {
|
||||
debouncerRef.current?.triggerBuild(projectId);
|
||||
}, [projectId]);
|
||||
|
||||
const cancelBuild = useCallback(() => {
|
||||
debouncerRef.current?.cancel(projectId);
|
||||
}, [projectId]);
|
||||
|
||||
const hasPendingChanges = useCallback(() => {
|
||||
return debouncerRef.current?.hasPendingChanges(projectId) || false;
|
||||
}, [projectId]);
|
||||
|
||||
return {
|
||||
triggerBuild,
|
||||
cancelBuild,
|
||||
hasPendingChanges,
|
||||
isBuildPending,
|
||||
};
|
||||
}
|
||||
@@ -1,19 +1,17 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { buildProject } from "@/lib/build";
|
||||
import { useFS } from "./useFS";
|
||||
import { useFSPaths } from "./useFSPaths";
|
||||
import { useAppContext } from "./useAppContext";
|
||||
|
||||
export function useBuildProject(projectId: string) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return await buildProject({
|
||||
fs,
|
||||
projectPath: `${projectsPath}/${projectId}`,
|
||||
projectPath: `/projects/${projectId}`,
|
||||
domParser: new DOMParser(),
|
||||
esmUrl: config.esmUrl,
|
||||
});
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
/**
|
||||
* Hook to access configured virtual filesystem paths
|
||||
*
|
||||
* @returns Object containing VFS path configurations
|
||||
*/
|
||||
export function useFSPaths() {
|
||||
const { config } = useAppContext();
|
||||
|
||||
return {
|
||||
/** Projects directory path (default: /projects) */
|
||||
projectsPath: config.fsPathProjects,
|
||||
/** Config directory path (default: /config) */
|
||||
configPath: config.fsPathConfig,
|
||||
/** Temporary files directory path (default: /tmp) */
|
||||
tmpPath: config.fsPathTmp,
|
||||
/** Plugins directory path (default: /plugins) */
|
||||
pluginsPath: config.fsPathPlugins,
|
||||
};
|
||||
}
|
||||
@@ -33,24 +33,14 @@ function createWrapper(corsProxy: string) {
|
||||
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: 'light',
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
relayUrl: 'wss://relay.test',
|
||||
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy,
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-test.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
|
||||
return createElement(
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGitFetch } from './useGitFetch';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the git operations
|
||||
vi.mock('./useGit', () => ({
|
||||
useGit: () => ({
|
||||
git: {
|
||||
findRoot: vi.fn().mockResolvedValue('/projects/test-project'),
|
||||
listRemotes: vi.fn().mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]),
|
||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
||||
getRemoteInfo: vi.fn().mockResolvedValue({
|
||||
refs: {
|
||||
HEAD: {
|
||||
type: 'symref',
|
||||
target: 'refs/heads/main',
|
||||
},
|
||||
},
|
||||
}),
|
||||
resolveRef: vi.fn()
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'), // after current
|
||||
fetch: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useGitSettings', () => ({
|
||||
useGitSettings: () => ({
|
||||
settings: {
|
||||
credentials: [],
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useFSPaths', () => ({
|
||||
useFSPaths: () => ({
|
||||
projectsPath: '/projects',
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('useGitFetch', () => {
|
||||
it('returns null state when projectId is null', async () => {
|
||||
const { result } = renderHook(() => useGitFetch(null), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
// When projectId is null, the query is disabled and won't fetch
|
||||
// So we just check the initial state
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully', async () => {
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('can be manually refetched', async () => {
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
const firstFetchTime = result.current.data?.fetchedAt;
|
||||
|
||||
// Manually trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,335 +0,0 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useToast } from './useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
interface FetchResult {
|
||||
defaultBranch: string | null;
|
||||
defaultBranchOid: string | null;
|
||||
currentBranch: string | null;
|
||||
currentBranchOid: string | null;
|
||||
fetchedAt: number;
|
||||
hasChanges: boolean;
|
||||
remoteUrl: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch updates from remote repository and detect changes.
|
||||
* Polls every 60 seconds and shows toast notifications when changes are detected.
|
||||
*
|
||||
* @param projectId - The project ID to fetch for
|
||||
* @returns Query result with manual refetch capability
|
||||
*/
|
||||
export function useGitFetch(projectId: string | null) {
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Track previous state to detect changes
|
||||
const previousStateRef = useRef<{
|
||||
defaultBranchOid: string | null;
|
||||
currentBranchOid: string | null;
|
||||
} | null>(null);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['git-fetch', projectId],
|
||||
queryFn: async (): Promise<FetchResult> => {
|
||||
console.log('=== GIT FETCH STARTING ===');
|
||||
console.log('Project ID:', projectId);
|
||||
|
||||
if (!projectId) {
|
||||
console.log('No project ID, returning empty result');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
console.log('Working directory:', cwd);
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await git.findRoot({ filepath: cwd });
|
||||
console.log('Git repository found');
|
||||
} catch {
|
||||
console.log('Not a git repository');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get remotes
|
||||
const remotes = await git.listRemotes({ dir: cwd });
|
||||
console.log('Remotes found:', remotes);
|
||||
|
||||
if (remotes.length === 0) {
|
||||
console.log('No remotes configured');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
const remoteUrl = remote.url || null;
|
||||
console.log('Using remote:', remote.remote, 'URL:', remoteUrl);
|
||||
|
||||
if (!remoteUrl) {
|
||||
console.log('No remote URL found');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get credentials for authentication
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
console.log('Credentials found:', !!credentials);
|
||||
|
||||
// Get current branch before fetch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
const branch = await git.currentBranch({
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
currentBranch = (branch && branch.trim() !== '') ? branch : null;
|
||||
console.log('Current branch:', currentBranch);
|
||||
} catch (error) {
|
||||
console.warn('Could not get current branch:', error);
|
||||
}
|
||||
|
||||
// Store OIDs before fetch
|
||||
let beforeDefaultOid: string | null = null;
|
||||
let beforeCurrentOid: string | null = null;
|
||||
|
||||
// Get remote info to find default branch
|
||||
let defaultBranch: string | null = null;
|
||||
try {
|
||||
console.log('Fetching remote info...');
|
||||
const remoteInfo = await git.getRemoteInfo({
|
||||
url: remoteUrl,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
// Extract default branch from symbolic ref
|
||||
if (remoteInfo.refs?.HEAD?.type === 'symref') {
|
||||
const symref = remoteInfo.refs.HEAD.target;
|
||||
defaultBranch = symref?.replace('refs/heads/', '') || null;
|
||||
console.log('Default branch from remote:', defaultBranch);
|
||||
}
|
||||
|
||||
// If we have a default branch, try to get its OID before fetch
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
beforeDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID before fetch:', beforeDefaultOid);
|
||||
} catch {
|
||||
console.log('Remote default branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not get remote info:', error);
|
||||
}
|
||||
|
||||
// Get current branch OID before fetch
|
||||
if (currentBranch) {
|
||||
try {
|
||||
beforeCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID before fetch:', beforeCurrentOid);
|
||||
} catch {
|
||||
console.log('Remote current branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
|
||||
// Perform fetch
|
||||
try {
|
||||
console.log('Fetching from remote...');
|
||||
await git.fetch({
|
||||
dir: cwd,
|
||||
remote: remote.remote,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
console.log('Fetch completed successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Get OIDs after fetch
|
||||
let afterDefaultOid: string | null = null;
|
||||
let afterCurrentOid: string | null = null;
|
||||
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
afterDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID after fetch:', afterDefaultOid);
|
||||
} catch {
|
||||
console.log('Could not resolve default branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (currentBranch) {
|
||||
try {
|
||||
afterCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID after fetch:', afterCurrentOid);
|
||||
} catch {
|
||||
console.log('Could not resolve current branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
// Detect changes
|
||||
const defaultBranchChanged = beforeDefaultOid !== null &&
|
||||
afterDefaultOid !== null &&
|
||||
beforeDefaultOid !== afterDefaultOid;
|
||||
|
||||
const currentBranchChanged = beforeCurrentOid !== null &&
|
||||
afterCurrentOid !== null &&
|
||||
beforeCurrentOid !== afterCurrentOid &&
|
||||
currentBranch !== defaultBranch; // Don't double-report if they're the same
|
||||
|
||||
const hasChanges = defaultBranchChanged || currentBranchChanged;
|
||||
|
||||
console.log('Changes detected:', {
|
||||
defaultBranchChanged,
|
||||
currentBranchChanged,
|
||||
hasChanges,
|
||||
});
|
||||
|
||||
const result = {
|
||||
defaultBranch,
|
||||
defaultBranchOid: afterDefaultOid,
|
||||
currentBranch,
|
||||
currentBranchOid: afterCurrentOid,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges,
|
||||
remoteUrl,
|
||||
};
|
||||
|
||||
console.log('=== GIT FETCH COMPLETE ===');
|
||||
console.log('Result:', result);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Error fetching from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
enabled: !!projectId,
|
||||
refetchInterval: 60000, // Fetch every 60 seconds
|
||||
staleTime: 30000, // Consider data stale after 30 seconds
|
||||
retry: 1, // Only retry once on failure
|
||||
});
|
||||
|
||||
// Show toast notifications when changes are detected
|
||||
useEffect(() => {
|
||||
if (!query.data || !query.isSuccess) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentState = {
|
||||
defaultBranchOid: query.data.defaultBranchOid,
|
||||
currentBranchOid: query.data.currentBranchOid,
|
||||
};
|
||||
|
||||
// Skip on first load
|
||||
if (previousStateRef.current === null) {
|
||||
previousStateRef.current = currentState;
|
||||
return;
|
||||
}
|
||||
|
||||
const prevState = previousStateRef.current;
|
||||
|
||||
// Detect default branch changes
|
||||
const defaultBranchChanged =
|
||||
prevState.defaultBranchOid !== null &&
|
||||
currentState.defaultBranchOid !== null &&
|
||||
prevState.defaultBranchOid !== currentState.defaultBranchOid;
|
||||
|
||||
// Detect current branch changes
|
||||
const currentBranchChanged =
|
||||
prevState.currentBranchOid !== null &&
|
||||
currentState.currentBranchOid !== null &&
|
||||
prevState.currentBranchOid !== currentState.currentBranchOid &&
|
||||
query.data.currentBranch !== query.data.defaultBranch;
|
||||
|
||||
// Show toast for default branch changes
|
||||
if (defaultBranchChanged && query.data.defaultBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.defaultBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Show toast for current branch changes (if different from default)
|
||||
if (currentBranchChanged && query.data.currentBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.currentBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Update previous state
|
||||
previousStateRef.current = currentState;
|
||||
}, [query.data, query.isSuccess, toast, queryClient, projectId]);
|
||||
|
||||
return query;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
|
||||
interface GitFileChange {
|
||||
filepath: string;
|
||||
@@ -42,7 +41,6 @@ interface GitStatus {
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['git-status', projectId],
|
||||
@@ -63,7 +61,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
const cwd = `/projects/${projectId}`;
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
@@ -90,8 +88,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
// Ensure we have a valid branch name (not empty string or undefined)
|
||||
currentBranch = (branch && branch.trim() !== '') ? branch : null;
|
||||
currentBranch = branch || null;
|
||||
} catch (error) {
|
||||
console.warn('Could not get current branch:', error);
|
||||
}
|
||||
@@ -151,11 +148,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
});
|
||||
|
||||
for (const remote of remoteNames) {
|
||||
// Skip remotes with empty names
|
||||
if (!remote.remote || !remote.url) {
|
||||
console.warn('Skipping remote with empty name or URL:', remote);
|
||||
continue;
|
||||
}
|
||||
remotes.push({
|
||||
name: remote.remote,
|
||||
url: remote.url,
|
||||
@@ -203,13 +195,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
try {
|
||||
if (currentBranch && remotes.length > 0) {
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Validate remote and branch names before constructing ref
|
||||
if (!remote.name || !currentBranch) {
|
||||
console.warn('Invalid remote or branch name for ahead/behind calculation');
|
||||
throw new Error('Invalid remote or branch name');
|
||||
}
|
||||
|
||||
const remoteBranchName = `${remote.name}/${currentBranch}`;
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Hook to detect offline status and provide cache management utilities
|
||||
*/
|
||||
export function useOffline() {
|
||||
const [isOnline, setIsOnline] = useState(navigator.onLine);
|
||||
const [serviceWorkerRegistration, setServiceWorkerRegistration] = useState<ServiceWorkerRegistration | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => setIsOnline(true);
|
||||
const handleOffline = () => setIsOnline(false);
|
||||
|
||||
window.addEventListener('online', handleOnline);
|
||||
window.addEventListener('offline', handleOffline);
|
||||
|
||||
// Get service worker registration
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
setServiceWorkerRegistration(registration);
|
||||
}).catch((error) => {
|
||||
console.error('[ServiceWorker] Failed to get registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('online', handleOnline);
|
||||
window.removeEventListener('offline', handleOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const clearCache = async () => {
|
||||
if ('caches' in window) {
|
||||
const cacheNames = await caches.keys();
|
||||
await Promise.all(
|
||||
cacheNames
|
||||
.filter(name => name.startsWith('workbox-') || name.includes('shakespeare'))
|
||||
.map(name => caches.delete(name))
|
||||
);
|
||||
console.log('[Cache] Cleared all caches');
|
||||
}
|
||||
};
|
||||
|
||||
const updateServiceWorker = async () => {
|
||||
if (serviceWorkerRegistration) {
|
||||
await serviceWorkerRegistration.update();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isOnline,
|
||||
isOffline: !isOnline,
|
||||
serviceWorkerRegistration,
|
||||
clearCache,
|
||||
updateServiceWorker,
|
||||
};
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { getPluginGitInfo } from '@/lib/plugins';
|
||||
|
||||
/**
|
||||
* Hook to get git info for a specific plugin
|
||||
*/
|
||||
export function usePluginGitInfo(pluginName: string) {
|
||||
const { fs } = useFS();
|
||||
const { pluginsPath } = useFSPaths();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['plugin-git-info', pluginsPath, pluginName],
|
||||
queryFn: async () => {
|
||||
return await getPluginGitInfo(fs, pluginsPath, pluginName);
|
||||
},
|
||||
enabled: !!pluginName,
|
||||
});
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { getPlugins, getAllSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
|
||||
import { useGit } from './useGit';
|
||||
import { join } from 'path-browserify';
|
||||
|
||||
/**
|
||||
* Hook to manage plugins and skills
|
||||
*/
|
||||
export function usePlugins() {
|
||||
const { fs } = useFS();
|
||||
const { pluginsPath } = useFSPaths();
|
||||
const queryClient = useQueryClient();
|
||||
const { git } = useGit();
|
||||
|
||||
// Query to get all plugins
|
||||
const pluginsQuery = useQuery({
|
||||
queryKey: ['plugins', pluginsPath],
|
||||
queryFn: async () => {
|
||||
return await getPlugins(fs, pluginsPath);
|
||||
},
|
||||
});
|
||||
|
||||
// Query to get all skills
|
||||
const skillsQuery = useQuery({
|
||||
queryKey: ['skills', pluginsPath],
|
||||
queryFn: async () => {
|
||||
return await getAllSkills(fs, pluginsPath);
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation to clone a plugin from a git URL
|
||||
const clonePlugin = useMutation({
|
||||
mutationFn: async ({ gitUrl, pluginName }: { gitUrl: string; pluginName?: string }) => {
|
||||
// Extract plugin name from git URL if not provided
|
||||
let name = pluginName;
|
||||
if (!name) {
|
||||
// Extract from URL: https://github.com/user/repo.git -> repo
|
||||
const match = gitUrl.match(/\/([^/]+?)(\.git)?$/);
|
||||
if (!match) {
|
||||
throw new Error('Invalid git URL');
|
||||
}
|
||||
name = match[1];
|
||||
}
|
||||
|
||||
const pluginDir = join(pluginsPath, name);
|
||||
|
||||
// Ensure plugins directory exists
|
||||
try {
|
||||
await fs.stat(pluginsPath);
|
||||
} catch {
|
||||
await fs.mkdir(pluginsPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Check if plugin already exists
|
||||
try {
|
||||
await fs.stat(pluginDir);
|
||||
throw new Error(`Plugin "${name}" already exists`);
|
||||
} catch (error) {
|
||||
// Plugin doesn't exist, continue
|
||||
if (error instanceof Error && error.message.includes('already exists')) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Clone the repository
|
||||
await git.clone({
|
||||
dir: pluginDir,
|
||||
url: gitUrl,
|
||||
depth: 1,
|
||||
singleBranch: true,
|
||||
});
|
||||
|
||||
return name;
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate queries to refresh the lists
|
||||
queryClient.invalidateQueries({ queryKey: ['plugins', pluginsPath] });
|
||||
queryClient.invalidateQueries({ queryKey: ['skills', pluginsPath] });
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation to sync (pull) a plugin
|
||||
const syncPlugin = useMutation({
|
||||
mutationFn: async (pluginName: string) => {
|
||||
const pluginDir = join(pluginsPath, pluginName);
|
||||
|
||||
// Pull latest changes
|
||||
await git.pull({
|
||||
dir: pluginDir,
|
||||
singleBranch: true,
|
||||
fastForward: true,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
return pluginName;
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate queries to refresh the lists
|
||||
queryClient.invalidateQueries({ queryKey: ['plugins', pluginsPath] });
|
||||
queryClient.invalidateQueries({ queryKey: ['skills', pluginsPath] });
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation to delete a plugin
|
||||
const deletePlugin = useMutation({
|
||||
mutationFn: async (pluginName: string) => {
|
||||
await deletePluginFn(fs, pluginsPath, pluginName);
|
||||
return pluginName;
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate queries to refresh the lists
|
||||
queryClient.invalidateQueries({ queryKey: ['plugins', pluginsPath] });
|
||||
queryClient.invalidateQueries({ queryKey: ['skills', pluginsPath] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
plugins: pluginsQuery.data || [],
|
||||
isLoadingPlugins: pluginsQuery.isLoading,
|
||||
skills: skillsQuery.data || [],
|
||||
isLoadingSkills: skillsQuery.isLoading,
|
||||
clonePlugin,
|
||||
syncPlugin,
|
||||
deletePlugin,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
|
||||
export interface ShakespeareProjectConfig {
|
||||
type: 'shakespeare';
|
||||
@@ -42,22 +41,14 @@ export interface ProjectDeploySettings {
|
||||
* Hook to manage project-specific deployment settings
|
||||
* Stores settings in .git/shakespeare/deploy.json
|
||||
*/
|
||||
export function useProjectDeploySettings(projectId: string | null) {
|
||||
export function useProjectDeploySettings(projectId: string) {
|
||||
const fs = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<ProjectDeploySettings>({ providers: {} });
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const settingsPath = `${projectsPath}/${projectId}/.git/shakespeare/deploy.json`;
|
||||
const settingsPath = `/projects/${projectId}/.git/shakespeare/deploy.json`;
|
||||
|
||||
const loadSettings = useCallback(async () => {
|
||||
// Don't try to load if projectId is falsy
|
||||
if (!projectId) {
|
||||
setSettings({ providers: {} });
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const content = await fs.fs.readFile(settingsPath, 'utf8');
|
||||
@@ -78,20 +69,16 @@ export function useProjectDeploySettings(projectId: string | null) {
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [fs.fs, settingsPath, projectId]);
|
||||
}, [fs.fs, settingsPath]);
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings();
|
||||
}, [loadSettings]);
|
||||
|
||||
const saveSettings = async (newSettings: ProjectDeploySettings) => {
|
||||
if (!projectId) {
|
||||
throw new Error('Cannot save settings: no project selected');
|
||||
}
|
||||
|
||||
try {
|
||||
// Ensure .git/shakespeare directory exists
|
||||
const shakespeareDir = `${projectsPath}/${projectId}/.git/shakespeare`;
|
||||
const shakespeareDir = `/projects/${projectId}/.git/shakespeare`;
|
||||
try {
|
||||
await fs.fs.stat(shakespeareDir);
|
||||
} catch {
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import { useMemo } from 'react';
|
||||
import { ProjectsManager } from '@/lib/ProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGit } from './useGit';
|
||||
|
||||
/**
|
||||
* Hook that provides a ProjectsManager instance.
|
||||
* The ProjectsManager is memoized based on the fs instance and configured paths.
|
||||
* The ProjectsManager is memoized based on the fs instance.
|
||||
*/
|
||||
export function useProjectsManager() {
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
const projectsManager = useMemo(() => {
|
||||
return new ProjectsManager({ fs, git, projectsPath });
|
||||
}, [fs, git, projectsPath]);
|
||||
return new ProjectsManager({ fs, git });
|
||||
}, [fs, git]);
|
||||
|
||||
return projectsManager;
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { useLocalStorage } from './useLocalStorage';
|
||||
import { useGitStatus } from './useGitStatus';
|
||||
|
||||
interface PushReminderState {
|
||||
/** Whether push reminders are enabled */
|
||||
enabled: boolean;
|
||||
/** Number of messages since last push */
|
||||
messagesSinceLastPush: number;
|
||||
/** Timestamp when user last pushed or dismissed a reminder */
|
||||
lastInteraction: number;
|
||||
/** Project ID being tracked */
|
||||
currentProjectId: string | null;
|
||||
}
|
||||
|
||||
const DEFAULT_STATE: PushReminderState = {
|
||||
enabled: true,
|
||||
messagesSinceLastPush: 0,
|
||||
lastInteraction: 0, // Start at 0 so reminders can show immediately
|
||||
currentProjectId: null,
|
||||
};
|
||||
|
||||
/** Number of messages before showing push reminder */
|
||||
const MESSAGE_THRESHOLD = 5;
|
||||
|
||||
/** Minimum time in ms between showing reminders (5 minutes) */
|
||||
const MIN_REMINDER_INTERVAL = 5 * 60 * 1000;
|
||||
|
||||
export function usePushReminder(projectId: string | null) {
|
||||
const [state, setState] = useLocalStorage<PushReminderState>(
|
||||
'push-reminder-state',
|
||||
DEFAULT_STATE
|
||||
);
|
||||
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Reset counter when switching projects
|
||||
useEffect(() => {
|
||||
if (projectId && state.currentProjectId !== projectId) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentProjectId: projectId,
|
||||
messagesSinceLastPush: 0,
|
||||
// Don't reset lastInteraction - keep the cooldown across project switches
|
||||
}));
|
||||
}
|
||||
}, [projectId, state.currentProjectId, setState]);
|
||||
|
||||
// Check if should show reminder
|
||||
const shouldShowReminder = useCallback(() => {
|
||||
if (!state.enabled || !projectId || !gitStatus?.isGitRepo) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't show if user recently interacted with push reminder
|
||||
const timeSinceLastInteraction = Date.now() - state.lastInteraction;
|
||||
if (timeSinceLastInteraction < MIN_REMINDER_INTERVAL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Show if:
|
||||
// 1. There are uncommitted changes OR commits ahead of remote OR no remote configured
|
||||
// 2. Enough messages have been sent since last interaction
|
||||
const hasUnpushedWork =
|
||||
gitStatus.hasUncommittedChanges ||
|
||||
gitStatus.ahead > 0 ||
|
||||
gitStatus.remotes.length === 0;
|
||||
const enoughMessages = state.messagesSinceLastPush >= MESSAGE_THRESHOLD;
|
||||
|
||||
return hasUnpushedWork && enoughMessages;
|
||||
}, [state, projectId, gitStatus]);
|
||||
|
||||
// Increment message counter
|
||||
const incrementMessages = useCallback(() => {
|
||||
if (!state.enabled || !projectId) return;
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
messagesSinceLastPush: prev.messagesSinceLastPush + 1,
|
||||
}));
|
||||
}, [state.enabled, projectId, setState]);
|
||||
|
||||
// Reset counter (called after push or dismiss)
|
||||
const resetReminder = useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
messagesSinceLastPush: 0,
|
||||
lastInteraction: Date.now(),
|
||||
}));
|
||||
}, [setState]);
|
||||
|
||||
// Enable/disable reminders
|
||||
const setEnabled = useCallback((enabled: boolean) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
enabled,
|
||||
messagesSinceLastPush: 0,
|
||||
lastInteraction: Date.now(),
|
||||
}));
|
||||
}, [setState]);
|
||||
|
||||
// Check if there's unpushed work that should trigger warning icon
|
||||
const hasUnpushedWork = gitStatus?.isGitRepo && (
|
||||
gitStatus.hasUncommittedChanges ||
|
||||
gitStatus.ahead > 0 ||
|
||||
gitStatus.remotes.length === 0
|
||||
);
|
||||
|
||||
return {
|
||||
shouldShowReminder: shouldShowReminder(),
|
||||
incrementMessages,
|
||||
resetReminder,
|
||||
enabled: state.enabled,
|
||||
setEnabled,
|
||||
hasUnpushedWork: hasUnpushedWork || false,
|
||||
gitStatus,
|
||||
};
|
||||
}
|
||||
@@ -194,13 +194,10 @@ export function useZaps(
|
||||
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
const zapRequest = nip57.makeZapRequest({
|
||||
event: actualTarget,
|
||||
amount: zapAmount,
|
||||
relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band'],
|
||||
relays: [config.relayUrl],
|
||||
comment
|
||||
});
|
||||
|
||||
@@ -258,7 +255,7 @@ export function useZaps(
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (webln) { // Try WebLN next
|
||||
try {
|
||||
await webln.sendPayment(newInvoice);
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
/**
|
||||
* BuildDebouncer manages automatic builds triggered by file changes.
|
||||
* It debounces build requests to avoid excessive builds while the AI is working.
|
||||
*/
|
||||
export class BuildDebouncer {
|
||||
private debounceTimers = new Map<string, NodeJS.Timeout>();
|
||||
private pendingBuilds = new Map<string, Set<string>>();
|
||||
private readonly debounceMs: number;
|
||||
private readonly onBuild: (projectId: string, changedFiles: string[]) => void;
|
||||
|
||||
constructor(
|
||||
debounceMs: number = 2000,
|
||||
onBuild: (projectId: string, changedFiles: string[]) => void
|
||||
) {
|
||||
this.debounceMs = debounceMs;
|
||||
this.onBuild = onBuild;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a file change for a project.
|
||||
* This will trigger a debounced build after the configured delay.
|
||||
*/
|
||||
registerFileChange(projectId: string, filePath: string): void {
|
||||
// Track the changed file
|
||||
if (!this.pendingBuilds.has(projectId)) {
|
||||
this.pendingBuilds.set(projectId, new Set());
|
||||
}
|
||||
this.pendingBuilds.get(projectId)!.add(filePath);
|
||||
|
||||
// Clear existing timer
|
||||
const existingTimer = this.debounceTimers.get(projectId);
|
||||
if (existingTimer) {
|
||||
clearTimeout(existingTimer);
|
||||
}
|
||||
|
||||
// Set new timer
|
||||
const timer = setTimeout(() => {
|
||||
this.triggerBuild(projectId);
|
||||
}, this.debounceMs);
|
||||
|
||||
this.debounceTimers.set(projectId, timer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger an immediate build for a project, bypassing the debounce.
|
||||
*/
|
||||
triggerBuild(projectId: string): void {
|
||||
const changedFiles = Array.from(this.pendingBuilds.get(projectId) || []);
|
||||
|
||||
if (changedFiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear the pending builds and timer
|
||||
this.pendingBuilds.delete(projectId);
|
||||
const timer = this.debounceTimers.get(projectId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.debounceTimers.delete(projectId);
|
||||
}
|
||||
|
||||
// Trigger the build
|
||||
this.onBuild(projectId, changedFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel any pending builds for a project.
|
||||
*/
|
||||
cancel(projectId: string): void {
|
||||
const timer = this.debounceTimers.get(projectId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.debounceTimers.delete(projectId);
|
||||
}
|
||||
this.pendingBuilds.delete(projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a project has pending file changes.
|
||||
*/
|
||||
hasPendingChanges(projectId: string): boolean {
|
||||
return (this.pendingBuilds.get(projectId)?.size || 0) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of pending changed files for a project.
|
||||
*/
|
||||
getPendingFiles(projectId: string): string[] {
|
||||
return Array.from(this.pendingBuilds.get(projectId) || []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup all timers (call on unmount/cleanup).
|
||||
*/
|
||||
cleanup(): void {
|
||||
for (const timer of this.debounceTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.debounceTimers.clear();
|
||||
this.pendingBuilds.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,397 +0,0 @@
|
||||
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
|
||||
/**
|
||||
* Electron filesystem adapter that implements JSRuntimeFS interface
|
||||
* This adapter communicates with Electron's main process via IPC to perform
|
||||
* filesystem operations on the actual OS filesystem.
|
||||
*
|
||||
* Note: This adapter should only be instantiated when running in Electron.
|
||||
*/
|
||||
export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Cache for stat results to avoid repeated IPC calls
|
||||
private statCache = new Map<string, { result: Awaited<ReturnType<typeof this.electron.fs.stat>>; timestamp: number }>();
|
||||
private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache
|
||||
|
||||
// Cache for ENOENT results to avoid repeated failed reads (especially for git objects)
|
||||
private enoentCache = new Set<string>();
|
||||
private readonly ENOENT_CACHE_MAX_SIZE = 5000;
|
||||
|
||||
private get electron() {
|
||||
if (!window.electron) {
|
||||
throw new Error('ElectronFSAdapter can only be used in Electron environment');
|
||||
}
|
||||
return window.electron;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwrap Electron IPC errors to preserve error codes.
|
||||
* Electron wraps errors in "Error invoking remote method..." messages,
|
||||
* but we need to preserve the original error code for isomorphic-git.
|
||||
*/
|
||||
private unwrapElectronError(error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return error as Error;
|
||||
}
|
||||
|
||||
// Extract error code from the error object if it exists
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
|
||||
// If there's already a code, preserve it
|
||||
if (code) {
|
||||
const err = new Error(error.message);
|
||||
(err as NodeJS.ErrnoException).code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
// If no code property, try to extract from the message
|
||||
// Messages look like: "Error invoking remote method 'fs:stat': Error: Failed to stat /path: ENOENT: no such file or directory"
|
||||
const match = error.message.match(/:\s*(E[A-Z]+):/);
|
||||
if (match) {
|
||||
const err = new Error(error.message);
|
||||
(err as NodeJS.ErrnoException).code = match[1];
|
||||
return err;
|
||||
}
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array<ArrayBufferLike>>;
|
||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, options: string): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>> {
|
||||
try {
|
||||
// Validate path is not empty (isomorphic-git sometimes passes empty strings during ref resolution)
|
||||
if (!path || path.trim() === '') {
|
||||
const err = new Error(`EINVAL: invalid path ''`);
|
||||
(err as NodeJS.ErrnoException).code = 'EINVAL';
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Check if we've already seen ENOENT for this path (common for git packed objects)
|
||||
if (this.enoentCache.has(path)) {
|
||||
const err = new Error(`ENOENT: no such file or directory, open '${path}'`);
|
||||
(err as NodeJS.ErrnoException).code = 'ENOENT';
|
||||
throw err;
|
||||
}
|
||||
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
const result = await this.electron.fs.readFile(path, encoding);
|
||||
|
||||
// If no encoding, convert array to Uint8Array
|
||||
if (!encoding && Array.isArray(result)) {
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
|
||||
return result as string;
|
||||
} catch (error) {
|
||||
const unwrapped = this.unwrapElectronError(error);
|
||||
|
||||
// Cache ENOENT errors to avoid repeated IPC calls for missing files
|
||||
// This is especially important for git packed objects that isomorphic-git tries to read
|
||||
if ((unwrapped as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
this.enoentCache.add(path);
|
||||
|
||||
// Limit cache size to prevent memory leaks
|
||||
if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) {
|
||||
// Clear oldest entries (first 1000)
|
||||
const entries = Array.from(this.enoentCache);
|
||||
entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry));
|
||||
}
|
||||
}
|
||||
|
||||
throw unwrapped;
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array<ArrayBufferLike>, options?: string | { encoding?: string }): Promise<void> {
|
||||
try {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
// Convert Uint8Array to regular array for IPC serialization
|
||||
const dataToWrite = data instanceof Uint8Array ? Array.from(data) : data;
|
||||
const result = await this.electron.fs.writeFile(path, dataToWrite, encoding);
|
||||
|
||||
// Invalidate caches for this path and its parent directory
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
this.enoentCache.delete(path); // File now exists
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]>;
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
try {
|
||||
// Fast path: check if this is a file first (common case causing errors)
|
||||
// Use cached stat if available to avoid extra IPC call
|
||||
const cached = this.statCache.get(path);
|
||||
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
|
||||
if (cached.result.isFile) {
|
||||
// This is a file, not a directory - throw ENOTDIR immediately
|
||||
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
|
||||
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.readdir(path, options?.withFileTypes);
|
||||
|
||||
if (options?.withFileTypes) {
|
||||
// Convert plain objects to DirectoryEntry format
|
||||
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.isDirectory,
|
||||
isFile: () => entry.isFile,
|
||||
}));
|
||||
}
|
||||
|
||||
return result as string[];
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
try {
|
||||
// Default to recursive: true for isomorphic-git compatibility
|
||||
// isomorphic-git expects mkdir to behave like 'mkdir -p'
|
||||
const recursive = options?.recursive !== false;
|
||||
const result = await this.electron.fs.mkdir(path, recursive);
|
||||
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isBlockDevice(): boolean;
|
||||
isCharacterDevice(): boolean;
|
||||
isSymbolicLink(): boolean;
|
||||
isFIFO(): boolean;
|
||||
isSocket(): boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
mtime: Date;
|
||||
ctime: Date;
|
||||
atime: Date;
|
||||
}> {
|
||||
try {
|
||||
// Check cache first
|
||||
const cached = this.statCache.get(path);
|
||||
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
|
||||
return cached.result;
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.stat(path);
|
||||
const now = Date.now();
|
||||
const statResult = {
|
||||
isDirectory: () => result.isDirectory,
|
||||
isFile: () => result.isFile,
|
||||
isBlockDevice: () => result.isBlockDevice,
|
||||
isCharacterDevice: () => result.isCharacterDevice,
|
||||
isSymbolicLink: () => result.isSymbolicLink,
|
||||
isFIFO: () => result.isFIFO,
|
||||
isSocket: () => result.isSocket,
|
||||
size: result.size ?? 0,
|
||||
mtimeMs: result.mtimeMs ?? now,
|
||||
ctimeMs: result.ctimeMs ?? now,
|
||||
atimeMs: result.atimeMs ?? now,
|
||||
// Convert timestamps back to Date objects
|
||||
mtime: new Date(result.mtime ?? now),
|
||||
ctime: new Date(result.ctime ?? now),
|
||||
atime: new Date(result.atime ?? now),
|
||||
};
|
||||
|
||||
// Cache the result
|
||||
this.statCache.set(path, { result: statResult, timestamp: Date.now() });
|
||||
|
||||
// Limit cache size to prevent memory leaks
|
||||
if (this.statCache.size > 10000) {
|
||||
// Remove oldest entries (first 1000)
|
||||
const entries = Array.from(this.statCache.entries());
|
||||
entries.slice(0, 1000).forEach(([key]) => this.statCache.delete(key));
|
||||
}
|
||||
|
||||
return statResult;
|
||||
} catch (error) {
|
||||
// Electron IPC wraps errors, extract the original error code
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isBlockDevice(): boolean;
|
||||
isCharacterDevice(): boolean;
|
||||
isSymbolicLink(): boolean;
|
||||
isFIFO(): boolean;
|
||||
isSocket(): boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
mtime: Date;
|
||||
ctime: Date;
|
||||
atime: Date;
|
||||
}> {
|
||||
try {
|
||||
// Check cache first (use separate cache key for lstat)
|
||||
const cacheKey = `lstat:${path}`;
|
||||
const cached = this.statCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
|
||||
return cached.result;
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.lstat(path);
|
||||
const now = Date.now();
|
||||
const statResult = {
|
||||
isDirectory: () => result.isDirectory,
|
||||
isFile: () => result.isFile,
|
||||
isBlockDevice: () => result.isBlockDevice,
|
||||
isCharacterDevice: () => result.isCharacterDevice,
|
||||
isSymbolicLink: () => result.isSymbolicLink,
|
||||
isFIFO: () => result.isFIFO,
|
||||
isSocket: () => result.isSocket,
|
||||
size: result.size ?? 0,
|
||||
mtimeMs: result.mtimeMs ?? now,
|
||||
ctimeMs: result.ctimeMs ?? now,
|
||||
atimeMs: result.atimeMs ?? now,
|
||||
// Convert timestamps back to Date objects
|
||||
mtime: new Date(result.mtime ?? now),
|
||||
ctime: new Date(result.ctime ?? now),
|
||||
atime: new Date(result.atime ?? now),
|
||||
};
|
||||
|
||||
// Cache the result
|
||||
this.statCache.set(cacheKey, { result: statResult, timestamp: Date.now() });
|
||||
|
||||
// Limit cache size to prevent memory leaks
|
||||
if (this.statCache.size > 10000) {
|
||||
// Remove oldest entries (first 1000)
|
||||
const entries = Array.from(this.statCache.entries());
|
||||
entries.slice(0, 1000).forEach(([key]) => this.statCache.delete(key));
|
||||
}
|
||||
|
||||
return statResult;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async unlink(path: string): Promise<void> {
|
||||
try {
|
||||
const result = await this.electron.fs.unlink(path);
|
||||
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async rmdir(path: string): Promise<void> {
|
||||
try {
|
||||
const result = await this.electron.fs.rmdir(path);
|
||||
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
try {
|
||||
const result = await this.electron.fs.rename(oldPath, newPath);
|
||||
|
||||
// Invalidate cache for both paths and their parents
|
||||
this.statCache.delete(oldPath);
|
||||
this.statCache.delete(`lstat:${oldPath}`);
|
||||
this.statCache.delete(newPath);
|
||||
this.statCache.delete(`lstat:${newPath}`);
|
||||
|
||||
const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/'));
|
||||
if (oldParent) {
|
||||
this.statCache.delete(oldParent);
|
||||
this.statCache.delete(`lstat:${oldParent}`);
|
||||
}
|
||||
|
||||
const newParent = newPath.substring(0, newPath.lastIndexOf('/'));
|
||||
if (newParent) {
|
||||
this.statCache.delete(newParent);
|
||||
this.statCache.delete(`lstat:${newParent}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async readlink(path: string): Promise<string> {
|
||||
try {
|
||||
return await this.electron.fs.readlink(path);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async symlink(target: string, path: string): Promise<void> {
|
||||
try {
|
||||
return await this.electron.fs.symlink(target, path);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all caches. Useful when switching projects or after major filesystem changes.
|
||||
*/
|
||||
clearCaches(): void {
|
||||
this.statCache.clear();
|
||||
this.enoentCache.clear();
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,14 @@
|
||||
*/
|
||||
export interface JSRuntimeFS {
|
||||
// Core file operations with proper overloads for type safety
|
||||
readFile(path: string): Promise<Uint8Array<ArrayBufferLike>>;
|
||||
readFile(path: string): Promise<Uint8Array<ArrayBuffer>>;
|
||||
readFile(path: string, options: 'utf8'): Promise<string>;
|
||||
readFile(path: string, options: string): Promise<string>;
|
||||
readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>>;
|
||||
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>>;
|
||||
|
||||
writeFile(path: string, data: string | Uint8Array<ArrayBufferLike>, options?: string | { encoding?: string }): Promise<void>;
|
||||
writeFile(path: string, data: string | Uint8Array<ArrayBuffer>, options?: string | { encoding?: string }): Promise<void>;
|
||||
|
||||
// readdir overloads for different return types
|
||||
readdir(path: string): Promise<string[]>;
|
||||
|
||||
@@ -8,18 +8,18 @@ import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
export class LightningFSAdapter implements JSRuntimeFS {
|
||||
constructor(private lightningFS: LightningFS.PromisifiedFS) {}
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array<ArrayBufferLike>>;
|
||||
async readFile(path: string): Promise<Uint8Array>;
|
||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, options: string): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBufferLike>> {
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
return this.lightningFS.readFile(path, encoding);
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array<ArrayBufferLike>, options?: string | { encoding?: string }): Promise<void> {
|
||||
async writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void> {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
return this.lightningFS.writeFile(path, data, encoding);
|
||||
}
|
||||
|
||||
@@ -19,8 +19,6 @@ export interface Project {
|
||||
export interface ProjectsManagerOptions {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
/** Projects directory path (default: /projects) */
|
||||
projectsPath?: string;
|
||||
}
|
||||
|
||||
export class ProjectsManager {
|
||||
@@ -31,7 +29,7 @@ export class ProjectsManager {
|
||||
constructor(options: ProjectsManagerOptions) {
|
||||
this.fs = options.fs;
|
||||
this.git = options.git;
|
||||
this.dir = options.projectsPath || '/projects';
|
||||
this.dir = '/projects';
|
||||
}
|
||||
|
||||
async init() {
|
||||
|
||||
@@ -47,7 +47,6 @@ export interface SessionManagerEvents {
|
||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||
costUpdated: (projectId: string, totalCost: number) => void;
|
||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||
fileChanged: (projectId: string, filePath: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,8 +61,6 @@ export class SessionManager {
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
|
||||
private corsProxy?: string;
|
||||
private projectsPath: string;
|
||||
private pluginsPath?: string;
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
@@ -71,15 +68,11 @@ export class SessionManager {
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
|
||||
corsProxy?: string,
|
||||
projectsPath = '/projects',
|
||||
pluginsPath?: string,
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
this.getProviderModels = getProviderModels;
|
||||
this.getCurrentUser = getCurrentUser;
|
||||
this.projectsPath = projectsPath;
|
||||
this.pluginsPath = pluginsPath;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
@@ -97,7 +90,7 @@ export class SessionManager {
|
||||
|
||||
// Try to load existing history
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
|
||||
const dotAI = new DotAI(this.fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
@@ -239,13 +232,12 @@ export class SessionManager {
|
||||
};
|
||||
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `${this.projectsPath}/${projectId}`,
|
||||
cwd: `/projects/${projectId}`,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(session.tools),
|
||||
pluginsPath: this.pluginsPath,
|
||||
user,
|
||||
metadata,
|
||||
});
|
||||
@@ -576,7 +568,7 @@ export class SessionManager {
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
|
||||
const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`);
|
||||
await dotAI.setHistory(session.sessionName, session.messages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save session history:', error);
|
||||
|
||||
@@ -18,6 +18,7 @@ describe('AI Provider Presets', () => {
|
||||
it('should include other major providers', () => {
|
||||
const providerIds = AI_PROVIDER_PRESETS.map(p => p.id);
|
||||
expect(providerIds).toContain('openai');
|
||||
expect(providerIds).toContain('anthropic');
|
||||
expect(providerIds).toContain('openrouter');
|
||||
});
|
||||
|
||||
|
||||
@@ -51,6 +51,13 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
apiKeysURL: "https://platform.openai.com/api-keys",
|
||||
tosURL: "https://openai.com/policies/",
|
||||
},
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
baseURL: "https://api.anthropic.com/v1",
|
||||
apiKeysURL: "https://console.anthropic.com/settings/keys",
|
||||
tosURL: "https://www.anthropic.com/legal/",
|
||||
},
|
||||
{
|
||||
id: "xai",
|
||||
name: "xAI",
|
||||
@@ -81,14 +88,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
tosURL: "https://ai.google.dev/gemini-api/terms",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: "vercel",
|
||||
name: "Vercel",
|
||||
baseURL: "https://api.v0.dev/v1",
|
||||
apiKeysURL: "https://v0.app/chat/settings/billing",
|
||||
tosURL: "https://vercel.com/legal/terms",
|
||||
proxy: true,
|
||||
},
|
||||
];
|
||||
|
||||
// Helper function to get a specific preset by ID
|
||||
|
||||
@@ -1,440 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseRepositoryAnnouncement } from './announceRepository';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
// Valid test npub for GRASP URL testing
|
||||
const TEST_NPUB = 'npub1cmzxsdtwlu5m42vmqrkkcx50pc7anr5754ncmn380gmf4gcjsgms7vk7pj';
|
||||
|
||||
|
||||
describe('parseRepositoryAnnouncement', () => {
|
||||
// Helper to create a mock repository announcement event
|
||||
const createMockEvent = (tags: string[][]): NostrEvent => ({
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
sig: 'test-sig',
|
||||
});
|
||||
|
||||
it('should throw error for non-30617 events', () => {
|
||||
const event = createMockEvent([]);
|
||||
event.kind = 1;
|
||||
|
||||
expect(() => parseRepositoryAnnouncement(event)).toThrow('Expected kind 30617, got 1');
|
||||
});
|
||||
|
||||
it('should parse basic repository fields', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'my-repo'],
|
||||
['name', 'My Repository'],
|
||||
['description', 'A test repository'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('my-repo');
|
||||
expect(result.name).toBe('My Repository');
|
||||
expect(result.description).toBe('A test repository');
|
||||
expect(result.httpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should handle missing optional fields', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'minimal-repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('minimal-repo');
|
||||
expect(result.name).toBeUndefined();
|
||||
expect(result.description).toBeUndefined();
|
||||
expect(result.earliestCommit).toBeUndefined();
|
||||
expect(result.maintainers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should parse multiple values in single tag (NIP-34 format)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['web', 'https://example.com', 'https://mirror.example.com'],
|
||||
['clone', 'https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://relay1.com', 'wss://relay2.com'],
|
||||
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.webUrls).toEqual(['https://example.com', 'https://mirror.example.com']);
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://github.com/user/repo.git',
|
||||
'https://gitlab.com/user/repo.git',
|
||||
]);
|
||||
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
|
||||
expect(result.maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
|
||||
});
|
||||
|
||||
it('should parse multiple separate tags (backward compatibility)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://relay1.com'],
|
||||
['relays', 'wss://relay2.com'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://github.com/user/repo.git',
|
||||
'https://gitlab.com/user/repo.git',
|
||||
]);
|
||||
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
|
||||
});
|
||||
|
||||
it('should extract earliest unique commit (euc)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['r', 'abc123def456', 'euc'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.earliestCommit).toBe('abc123def456');
|
||||
});
|
||||
|
||||
it('should ignore r tags without euc marker', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['r', 'abc123def456'],
|
||||
['r', 'other-value', 'other-marker'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.earliestCommit).toBeUndefined();
|
||||
});
|
||||
|
||||
describe('graspServers - GRASP server detection', () => {
|
||||
it('should identify GRASP servers from clone and relays tags (NIP-34 format)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
expect(parsed.graspServers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(parsed.graspServers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should identify GRASP servers from clone and relays tags (multiple tags format)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should require both clone and relays tags to identify GRASP server', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
// Missing relays tag for git.shakespeare.diy
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
// Missing clone tag for relay.ngit.dev
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`]);
|
||||
});
|
||||
|
||||
it('should validate npub pattern in clone URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://git.shakespeare.diy/invalid-npub/myrepo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://git.shakespeare.diy/invalid-npub/myrepo.git']);
|
||||
});
|
||||
|
||||
it('should require .git extension in clone URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo`]);
|
||||
});
|
||||
|
||||
it('should handle multiple clone URLs for same server', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo1.git`],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo2.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should reject http:// clone URLs and only accept https://', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `http://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
// Only https://relay.ngit.dev should be identified as GRASP server
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(servers).toHaveLength(1);
|
||||
// http:// URL should not be included in httpsCloneUrls at all
|
||||
expect(parsed.httpsCloneUrls).toEqual([`https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle ws and wss protocols', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'ws://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (separate tags)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (mixed in single tag)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should return empty array when no GRASP servers found', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['relays', 'wss://relay.nostr.band/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should handle invalid URLs gracefully', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'not-a-valid-url'],
|
||||
['relays', 'also-invalid'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle paths with subdirectories after npub', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/org/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle empty tags array', () => {
|
||||
const event = createMockEvent([]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle tags with empty values', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', ''],
|
||||
['relays', ''],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle clone URLs with trailing slashes', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle relay URLs without trailing slashes', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle mixed trailing slashes in clone and relay URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter out invalid URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://valid.com/repo.git', 'not-a-url', 'ftp://invalid.com/repo.git'],
|
||||
['relays', 'wss://valid.com', 'not-a-url', 'http://invalid.com'],
|
||||
['web', 'https://valid.com', 'not-a-url'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.httpsCloneUrls).toEqual(['https://valid.com/repo.git']);
|
||||
expect(result.relays).toEqual(['wss://valid.com']);
|
||||
expect(result.webUrls).toEqual(['https://valid.com', 'not-a-url']); // web URLs are not validated
|
||||
});
|
||||
|
||||
it('should preserve raw event', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.event).toBe(event);
|
||||
expect(result.event.id).toBe('test-id');
|
||||
expect(result.event.pubkey).toBe('test-pubkey');
|
||||
});
|
||||
|
||||
it('should handle empty identifier gracefully', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('');
|
||||
});
|
||||
|
||||
it('should handle empty arrays for missing multi-value tags', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.webUrls).toEqual([]);
|
||||
expect(result.relays).toEqual([]);
|
||||
expect(result.maintainers).toEqual([]);
|
||||
expect(result.graspServers).toEqual([]);
|
||||
expect(result.nonGraspRelays).toEqual([]);
|
||||
});
|
||||
|
||||
it('should accept both ws and wss protocols for relays', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['relays', 'ws://insecure.example.com', 'wss://secure.example.com'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.relays).toEqual([
|
||||
'ws://insecure.example.com',
|
||||
'wss://secure.example.com',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should only accept https:// protocol for clone URLs (reject http://)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'http://insecure.example.com/repo.git', 'https://secure.example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Only https:// URL should be included
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://secure.example.com/repo.git',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,361 +0,0 @@
|
||||
import type { EventTemplate } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export interface RepositoryAnnouncementData {
|
||||
/** Repository identifier (d tag) */
|
||||
repoId: string;
|
||||
/** Human-readable name */
|
||||
name?: string;
|
||||
/** Description of the repository */
|
||||
description?: string;
|
||||
/** Web URLs where repository can be browsed */
|
||||
webUrls?: string[];
|
||||
/** Clone URLs for the repository */
|
||||
cloneUrls: string[];
|
||||
/** Relays for patch submissions */
|
||||
relays?: string[];
|
||||
/** Earliest unique commit (root commit) */
|
||||
earliestCommit?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsed NIP-34 repository announcement with categorized data
|
||||
*/
|
||||
export interface RepositoryAnnouncement {
|
||||
/** Repository identifier (d tag) */
|
||||
identifier: string;
|
||||
/** Human-readable name */
|
||||
name?: string;
|
||||
/** Description of the repository */
|
||||
description?: string;
|
||||
/** Web URLs where repository can be browsed */
|
||||
webUrls: string[];
|
||||
/** All clone URLs (https) - to support http we would need to store graspServers with ws|wss:// prefix */
|
||||
httpsCloneUrls: string[];
|
||||
/** valid ws:// or wss:// Repository relay URLs*/
|
||||
relays: string[];
|
||||
/** Earliest unique commit (root commit SHA) */
|
||||
earliestCommit?: string;
|
||||
/** Maintainer public keys */
|
||||
maintainers: string[];
|
||||
/** GRASP servers (hostname only) - servers that appear in both clone and relays with valid pattern */
|
||||
graspServers: string[];
|
||||
/** Clone URLs that are NOT GRASP servers */
|
||||
nonGraspHttpsCloneUrls: string[];
|
||||
/** Relay URLs that are NOT GRASP servers */
|
||||
nonGraspRelays: string[];
|
||||
/** Raw event for advanced use */
|
||||
event: NostrEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a NIP-34 repository announcement event (kind 30617)
|
||||
*
|
||||
* @param data - Repository announcement data
|
||||
* @returns Event template ready to be signed
|
||||
*/
|
||||
export function createRepositoryAnnouncementEvent(
|
||||
data: RepositoryAnnouncementData
|
||||
): EventTemplate {
|
||||
// Build tags array per NIP-34
|
||||
const tags: string[][] = [
|
||||
['d', data.repoId.trim()], // Required: repository identifier
|
||||
];
|
||||
|
||||
if (data.name?.trim()) {
|
||||
tags.push(['name', data.name.trim()]);
|
||||
}
|
||||
|
||||
if (data.description?.trim()) {
|
||||
tags.push(['description', data.description.trim()]);
|
||||
}
|
||||
|
||||
// Add web URLs (all in a single tag per NIP-34)
|
||||
if (data.webUrls && data.webUrls.length > 0) {
|
||||
const trimmedUrls = data.webUrls.map(url => url.trim()).filter(url => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['web', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add clone URLs (required, all in a single tag per NIP-34)
|
||||
if (data.cloneUrls.length > 0) {
|
||||
const trimmedUrls = data.cloneUrls.map(url => url.trim()).filter(url => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['clone', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add relays for patch submissions (all in a single tag per NIP-34)
|
||||
if (data.relays && data.relays.length > 0) {
|
||||
const trimmedRelays = data.relays.map(relay => relay.trim()).filter(relay => relay);
|
||||
if (trimmedRelays.length > 0) {
|
||||
tags.push(['relays', ...trimmedRelays]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add earliest unique commit (euc) for repository identification
|
||||
if (data.earliestCommit?.trim()) {
|
||||
tags.push(['r', data.earliestCommit.trim(), 'euc']);
|
||||
}
|
||||
|
||||
// Create repository announcement event (kind 30617)
|
||||
return {
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a naddr (NIP-19 addressable event identifier) for a repository
|
||||
*
|
||||
* @param repoId - Repository identifier
|
||||
* @param pubkey - Repository owner's public key
|
||||
* @param relays - Optional relay hints
|
||||
* @returns naddr string
|
||||
*/
|
||||
export function createRepositoryNaddr(
|
||||
repoId: string,
|
||||
pubkey: string,
|
||||
relays?: string[]
|
||||
): string {
|
||||
return nip19.naddrEncode({
|
||||
identifier: repoId.trim(),
|
||||
pubkey,
|
||||
kind: 30617,
|
||||
relays: relays && relays.length > 0 ? relays : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates repository ID according to NIP-34 standards
|
||||
* Repository IDs should be kebab-case short names
|
||||
*
|
||||
* @param repoId - Repository ID to validate
|
||||
* @throws Error if validation fails
|
||||
*/
|
||||
export function validateRepositoryId(repoId: string): void {
|
||||
if (!repoId || !repoId.trim()) {
|
||||
throw new Error('Repository ID is required');
|
||||
}
|
||||
|
||||
const trimmedId = repoId.trim();
|
||||
|
||||
// Check for valid kebab-case format
|
||||
// Should only contain lowercase letters, numbers, and hyphens
|
||||
// Should not start or end with a hyphen
|
||||
// Should not have consecutive hyphens
|
||||
const kebabCaseRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
|
||||
if (!kebabCaseRegex.test(trimmedId)) {
|
||||
throw new Error(
|
||||
'Repository ID must be in kebab-case format (lowercase letters, numbers, and single hyphens only)'
|
||||
);
|
||||
}
|
||||
|
||||
// Additional length check (reasonable limits)
|
||||
if (trimmedId.length < 2) {
|
||||
throw new Error('Repository ID must be at least 2 characters long');
|
||||
}
|
||||
|
||||
if (trimmedId.length > 100) {
|
||||
throw new Error('Repository ID must be less than 100 characters');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates repository announcement data
|
||||
*
|
||||
* @param data - Repository announcement data to validate
|
||||
* @throws Error if validation fails
|
||||
*/
|
||||
export function validateRepositoryAnnouncementData(
|
||||
data: RepositoryAnnouncementData
|
||||
): void {
|
||||
validateRepositoryId(data.repoId);
|
||||
|
||||
if (data.cloneUrls.length === 0) {
|
||||
throw new Error('At least one clone URL is required');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a NIP-34 repository announcement event (kind 30617) into a structured format.
|
||||
*
|
||||
* This function extracts all relevant data from the event tags and categorizes servers
|
||||
* into GRASP and non-GRASP categories. GRASP servers are identified by matching:
|
||||
* - clone tag contains URL(s) matching: [http|https]://<hostname>/<valid-npub>/<repo>.git
|
||||
* - relays tag contains URL(s) matching: [ws|wss]://<hostname>
|
||||
*
|
||||
* @param event - A kind 30617 repository announcement event
|
||||
* @returns Parsed repository data with categorized servers
|
||||
* @throws Error if event is not kind 30617
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const repo = parseRepositoryAnnouncement(event);
|
||||
* console.log(repo.identifier); // "my-repo"
|
||||
* console.log(repo.graspServers); // ["git.example.com"]
|
||||
* console.log(repo.nonGraspCloneUrls); // ["https://github.com/user/repo.git"]
|
||||
* ```
|
||||
*/
|
||||
export function parseRepositoryAnnouncement(event: NostrEvent): RepositoryAnnouncement {
|
||||
if (event.kind !== 30617) {
|
||||
throw new Error(`Expected kind 30617, got ${event.kind}`);
|
||||
}
|
||||
|
||||
// Extract basic fields
|
||||
const identifier = event.tags.find(([name]) => name === 'd')?.[1] || '';
|
||||
const name = event.tags.find(([name]) => name === 'name')?.[1];
|
||||
const description = event.tags.find(([name]) => name === 'description')?.[1];
|
||||
|
||||
// Extract multi-value tags
|
||||
const webUrls: string[] = [];
|
||||
const httpsCloneUrls: string[] = [];
|
||||
const relays: string[] = [];
|
||||
const maintainers: string[] = [];
|
||||
let earliestCommit: string | undefined;
|
||||
|
||||
// Track servers for GRASP detection
|
||||
const validCloneServers = new Set<string>(); // Servers with valid GRASP clone URLs
|
||||
const relayServers = new Set<string>(); // Servers in relays tags
|
||||
const cloneUrlsByServer = new Map<string, string[]>(); // Map hostname -> clone URLs
|
||||
const relayUrlsByServer = new Map<string, string[]>(); // Map hostname -> relay URLs
|
||||
|
||||
for (const [name, ...values] of event.tags) {
|
||||
switch (name) {
|
||||
case 'web':
|
||||
// All values after tag name are web URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
webUrls.push(value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'clone':
|
||||
// All values after tag name are clone URLs
|
||||
// Also track which ones match GRASP pattern
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
|
||||
// Only accept https:// URLs (reject http://)
|
||||
if (url.protocol === 'https:') {
|
||||
httpsCloneUrls.push(value); // Use original value to preserve exact format
|
||||
|
||||
// Check if this matches GRASP pattern: https://<hostname>/<npub>/<repo>.git
|
||||
if ((value.endsWith('.git/') || value.endsWith('.git')) && value.includes('/npub1')) {
|
||||
// Extract and validate the npub using nip19.decode
|
||||
// Match npub1 followed by alphanumeric chars, ending at /
|
||||
const npubMatch = value.match(/\/npub1([a-z0-9]+)\//);
|
||||
if (npubMatch) {
|
||||
const npub = `npub1${npubMatch[1]}`;
|
||||
try {
|
||||
const decoded = nip19.decode(npub);
|
||||
if (decoded.type === 'npub') {
|
||||
// Valid GRASP clone URL
|
||||
validCloneServers.add(url.hostname);
|
||||
|
||||
if (!cloneUrlsByServer.has(url.hostname)) {
|
||||
cloneUrlsByServer.set(url.hostname, []);
|
||||
}
|
||||
cloneUrlsByServer.get(url.hostname)!.push(value);
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub, not a GRASP server
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'relays':
|
||||
// All values after tag name are relay URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol === 'ws:' || url.protocol === 'wss:') {
|
||||
relays.push(value); // Use original value to preserve exact format
|
||||
relayServers.add(url.hostname);
|
||||
|
||||
if (!relayUrlsByServer.has(url.hostname)) {
|
||||
relayUrlsByServer.set(url.hostname, []);
|
||||
}
|
||||
relayUrlsByServer.get(url.hostname)!.push(value);
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'maintainers':
|
||||
// All values after tag name are maintainer pubkeys
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
maintainers.push(value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
// Check for earliest unique commit marker
|
||||
if (values.length >= 2 && values[1] === 'euc') {
|
||||
earliestCommit = values[0];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Identify GRASP servers: must appear in BOTH clone (with valid pattern) and relays
|
||||
const graspServers = [...validCloneServers].filter(server =>
|
||||
relayServers.has(server)
|
||||
);
|
||||
|
||||
// Categorize clone URLs
|
||||
const nonGraspHttpsCloneUrls = httpsCloneUrls.filter(url => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return !graspServers.includes(hostname);
|
||||
} catch {
|
||||
return true; // Invalid URLs go to non-GRASP
|
||||
}
|
||||
});
|
||||
|
||||
// Categorize relay URLs
|
||||
const nonGraspRelays = relays.filter(url => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return !graspServers.includes(hostname);
|
||||
} catch {
|
||||
return true; // Invalid URLs go to non-GRASP
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
httpsCloneUrls,
|
||||
relays,
|
||||
earliestCommit,
|
||||
maintainers,
|
||||
graspServers,
|
||||
nonGraspHttpsCloneUrls,
|
||||
nonGraspRelays,
|
||||
event,
|
||||
};
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ansiToHtml, containsAnsiCodes, stripAnsiCodes } from './ansiToHtml';
|
||||
|
||||
describe('ansiToHtml', () => {
|
||||
it('should convert basic color codes to HTML', () => {
|
||||
const input = '\u001b[31mRed text\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('text-red-500');
|
||||
expect(output).toContain('Red text');
|
||||
});
|
||||
|
||||
it('should handle multiple color codes', () => {
|
||||
const input = '\u001b[31mRed\u001b[0m \u001b[32mGreen\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('text-red-500');
|
||||
expect(output).toContain('text-green-500');
|
||||
});
|
||||
|
||||
it('should return original text if no ANSI codes', () => {
|
||||
const input = 'Plain text';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
it('should handle bold text', () => {
|
||||
const input = '\u001b[1mBold text\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('font-bold');
|
||||
});
|
||||
|
||||
it('should handle background colors', () => {
|
||||
const input = '\u001b[41mRed background\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('bg-red-500');
|
||||
});
|
||||
});
|
||||
|
||||
describe('containsAnsiCodes', () => {
|
||||
it('should detect ANSI codes', () => {
|
||||
expect(containsAnsiCodes('\u001b[31mRed\u001b[0m')).toBe(true);
|
||||
expect(containsAnsiCodes('\u001b[1mBold\u001b[0m')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for plain text', () => {
|
||||
expect(containsAnsiCodes('Plain text')).toBe(false);
|
||||
expect(containsAnsiCodes('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripAnsiCodes', () => {
|
||||
it('should remove basic color codes', () => {
|
||||
const input = '\u001b[31mRed text\u001b[0m';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Red text');
|
||||
});
|
||||
|
||||
it('should remove multiple ANSI codes', () => {
|
||||
const input = '\u001b[31mRed\u001b[0m \u001b[32mGreen\u001b[0m \u001b[1mBold\u001b[0m';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Red Green Bold');
|
||||
});
|
||||
|
||||
it('should remove cursor movement codes', () => {
|
||||
const input = 'Text\u001b[2AMove up\u001b[1BMove down';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('TextMove upMove down');
|
||||
});
|
||||
|
||||
it('should remove clear screen codes', () => {
|
||||
const input = 'Before\u001b[2JAfter';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('BeforeAfter');
|
||||
});
|
||||
|
||||
it('should handle text without ANSI codes', () => {
|
||||
const input = 'Plain text';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
it('should handle empty string', () => {
|
||||
const output = stripAnsiCodes('');
|
||||
expect(output).toBe('');
|
||||
});
|
||||
|
||||
it('should handle npm output with ANSI codes', () => {
|
||||
const input = '\u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('added 142 packages in 3s');
|
||||
});
|
||||
|
||||
it('should handle git status output with ANSI codes', () => {
|
||||
const input = 'On branch \u001b[32mmain\u001b[m\nYour branch is up to date';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('On branch main\nYour branch is up to date');
|
||||
});
|
||||
|
||||
it('should preserve newlines and spaces', () => {
|
||||
const input = '\u001b[31mLine 1\u001b[0m\n\u001b[32mLine 2\u001b[0m\n Indented';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Line 1\nLine 2\n Indented');
|
||||
});
|
||||
});
|
||||
+11
-25
@@ -49,15 +49,15 @@ const styleMap: Record<string, string> = {
|
||||
export function ansiToHtml(text: string): string {
|
||||
// Regular expression to match ANSI escape sequences
|
||||
const ansiRegex = /\u001b\[((?:\d+;)*\d+)m/g;
|
||||
|
||||
|
||||
// Initialize result and current style classes
|
||||
let result = '';
|
||||
let currentClasses: string[] = [];
|
||||
|
||||
|
||||
// Find all matches and their positions
|
||||
const matches: Array<{index: number, length: number, codes: string}> = [];
|
||||
let match;
|
||||
|
||||
|
||||
while ((match = ansiRegex.exec(text)) !== null) {
|
||||
matches.push({
|
||||
index: match.index,
|
||||
@@ -65,15 +65,15 @@ export function ansiToHtml(text: string): string {
|
||||
codes: match[1]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// If no ANSI codes found, return the original text
|
||||
if (matches.length === 0) {
|
||||
return text;
|
||||
}
|
||||
|
||||
|
||||
// Process the text with ANSI codes
|
||||
let lastIndex = 0;
|
||||
|
||||
|
||||
for (const match of matches) {
|
||||
// Add text before this match with current styling
|
||||
if (match.index > lastIndex) {
|
||||
@@ -84,10 +84,10 @@ export function ansiToHtml(text: string): string {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update current classes based on ANSI codes
|
||||
const codes = match.codes.split(';');
|
||||
|
||||
|
||||
for (const code of codes) {
|
||||
if (code === '0') {
|
||||
// Reset all styles
|
||||
@@ -109,11 +109,11 @@ export function ansiToHtml(text: string): string {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update lastIndex to after this match
|
||||
lastIndex = match.index + match.length;
|
||||
}
|
||||
|
||||
|
||||
// Add any remaining text
|
||||
if (lastIndex < text.length) {
|
||||
const textSegment = text.substring(lastIndex);
|
||||
@@ -123,7 +123,7 @@ export function ansiToHtml(text: string): string {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -132,18 +132,4 @@ export function ansiToHtml(text: string): string {
|
||||
*/
|
||||
export function containsAnsiCodes(text: string): boolean {
|
||||
return /\u001b\[(?:\d+;)*\d+m/.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip all ANSI escape sequences from a string
|
||||
* This removes color codes, cursor movements, and other terminal control sequences
|
||||
*/
|
||||
export function stripAnsiCodes(text: string): string {
|
||||
// Remove all ANSI escape sequences
|
||||
// This regex matches:
|
||||
// - Color codes: \u001b[...m
|
||||
// - Cursor movement: \u001b[...H, \u001b[...A, etc.
|
||||
// - Clear screen: \u001b[...J, \u001b[...K
|
||||
// - Other escape sequences
|
||||
return text.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '');
|
||||
}
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user