mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
358
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c03858cc7 | ||
|
|
87c533666d | ||
|
|
f7ef7a2080 | ||
|
|
60fa8d2239 | ||
|
|
c7527b24df | ||
|
|
7755277877 | ||
|
|
72db1b21f4 | ||
|
|
fec198e7b3 | ||
|
|
2d0e7ae281 | ||
|
|
e8a889c247 | ||
|
|
68edc0b6dc | ||
|
|
a8a7e3ace9 | ||
|
|
8ea62f4b23 | ||
|
|
d7950924a8 | ||
|
|
dd5c7b22be | ||
|
|
5f1eaed12b | ||
|
|
b289983071 | ||
|
|
1f23fa6359 | ||
|
|
94d14a87aa | ||
|
|
4b1c3ee381 | ||
|
|
753c12bcac | ||
|
|
9d53f74782 | ||
|
|
d16515a5c4 | ||
|
|
015a6c8536 | ||
|
|
373f25db76 | ||
|
|
a09916fcb8 | ||
|
|
11522c8426 | ||
|
|
dedb9c7f55 | ||
|
|
ab9c269240 | ||
|
|
a22cc50990 | ||
|
|
b2eb443b43 | ||
|
|
94e1a6543c | ||
|
|
bc009d444e | ||
|
|
1ab895bd59 | ||
|
|
772a2f424b | ||
|
|
55120452c7 | ||
|
|
0dd5ae13a9 | ||
|
|
f56f88b1cb | ||
|
|
c225821a44 | ||
|
|
e8203dd69f | ||
|
|
ffb9c3d95e | ||
|
|
feaa767632 | ||
|
|
425976bb82 | ||
|
|
76fa9940db | ||
|
|
80ed3d606d | ||
|
|
a106a6e10b | ||
|
|
be8309b503 | ||
|
|
f23b92c79f | ||
|
|
21f9511a1e | ||
|
|
82d2aed921 | ||
|
|
7c7275cfdb | ||
|
|
7c500d1047 | ||
|
|
7ad72f6ff8 | ||
|
|
1938c145db | ||
|
|
04f81a3375 | ||
|
|
fa34cade7a | ||
|
|
cab91f692e | ||
|
|
731e74ad06 | ||
|
|
5331a56d36 | ||
|
|
9b85c11803 | ||
|
|
c9069cfebd | ||
|
|
492542df91 | ||
|
|
6935b343ae | ||
|
|
ef6642181e | ||
|
|
ebc4c2d997 | ||
|
|
383fa9b0ae | ||
|
|
787b0bb777 | ||
|
|
0edef42bf2 | ||
|
|
022efa74c3 | ||
|
|
ba62a139e2 | ||
|
|
b72baaeb48 | ||
|
|
bdcc030de6 | ||
|
|
b9568896d6 | ||
|
|
dc55626832 | ||
|
|
2c7fd7d79b | ||
|
|
bb47f36a35 | ||
|
|
a87df5d0aa | ||
|
|
e6864cf8f3 | ||
|
|
0119972cc9 | ||
|
|
874bca5d61 | ||
|
|
81b0571b3e | ||
|
|
ddf09c6684 | ||
|
|
227b0fab76 | ||
|
|
a84ebb16e0 | ||
|
|
9538c72c99 | ||
|
|
8e727b0b63 | ||
|
|
d33fa36591 | ||
|
|
e8e2b28504 | ||
|
|
3f52efe4b8 | ||
|
|
266774fc61 | ||
|
|
e92b3b9cd4 | ||
|
|
5b828f0c83 | ||
|
|
5debca98d6 | ||
|
|
069cda512e | ||
|
|
ff37b3d758 | ||
|
|
4039e1e355 | ||
|
|
943a4e592b | ||
|
|
24b8b5bd05 | ||
|
|
8db727ed14 | ||
|
|
6085713885 | ||
|
|
60eca98d86 | ||
|
|
0b02edfe32 | ||
|
|
79605c7ed1 | ||
|
|
8383384af7 | ||
|
|
bd0ed0a10f | ||
|
|
d7807f3911 | ||
|
|
5f619c769a | ||
|
|
154adfd83f | ||
|
|
9cba46d33f | ||
|
|
0f67f64936 | ||
|
|
ba2cfe7b68 | ||
|
|
251959c18e | ||
|
|
d7fc8f62e8 | ||
|
|
11b9aa9e20 | ||
|
|
6f923251d4 | ||
|
|
9b7b79dacc | ||
|
|
af6942c04f | ||
|
|
d3550b0fca | ||
|
|
795639a8f4 | ||
|
|
0f1126174a | ||
|
|
2433a7daff | ||
|
|
a8b46e04ef | ||
|
|
e899a93358 | ||
|
|
2005acc343 | ||
|
|
716bd42c7d | ||
|
|
c74edebc1b | ||
|
|
6c37b11b59 | ||
|
|
1042bdcf56 | ||
|
|
facbeff722 | ||
|
|
6e9e04a65f | ||
|
|
ddba6c3cea | ||
|
|
695f500ab0 | ||
|
|
9d5f575765 | ||
|
|
9afa747cd4 | ||
|
|
7cbcd03c10 | ||
|
|
a8c021411b | ||
|
|
aaa2dc1100 | ||
|
|
774280dc90 | ||
|
|
85f71fd00a | ||
|
|
0732fc5efd | ||
|
|
d49c52a8d8 | ||
|
|
26635a4b6a | ||
|
|
fd9aa5b683 | ||
|
|
c32fa627e4 | ||
|
|
423828705a | ||
|
|
c8e78f8a19 | ||
|
|
ba273282db | ||
|
|
0e1ccfe469 | ||
|
|
a177c81314 | ||
|
|
6583e29d08 | ||
|
|
a3d491f1a5 | ||
|
|
beeffd820d | ||
|
|
e622c09251 | ||
|
|
8475ca7c1a | ||
|
|
da1d221e1d | ||
|
|
fe5fd75487 | ||
|
|
2e0d97a8bf | ||
|
|
e7f56aaa78 | ||
|
|
a5de673ad9 | ||
|
|
2728be2aa6 | ||
|
|
6fc0bb96be | ||
|
|
5867e1313c | ||
|
|
a9400df4b9 | ||
|
|
11deafd5cc | ||
|
|
6f1e01fe8b | ||
|
|
2e7c185f3b | ||
|
|
35b2e8c53f | ||
|
|
7fe8236611 | ||
|
|
2b95959361 | ||
|
|
0fcea2a61b | ||
|
|
09e4ae7c59 | ||
|
|
f8adf59780 | ||
|
|
e1ca6d7bbc | ||
|
|
1b04be3c46 | ||
|
|
027c4f4fd2 | ||
|
|
3fe2c8e9db | ||
|
|
75c01dafd5 | ||
|
|
6260ce630d | ||
|
|
3841b68d7a | ||
|
|
f789434f1b | ||
|
|
4302b7c2fb | ||
|
|
84a6c1b38c | ||
|
|
d1110445e6 | ||
|
|
365ce0757e | ||
|
|
029edb4758 | ||
|
|
637b6ff0aa | ||
|
|
8a0071563f | ||
|
|
cdc18303b4 | ||
|
|
5e45c86a0f | ||
|
|
b5d8e1764a | ||
|
|
36a4782383 | ||
|
|
f280b0c183 | ||
|
|
3a3cfb51c5 | ||
|
|
1415008d67 | ||
|
|
fd485ac1e9 | ||
|
|
b9d9ab8526 | ||
|
|
5eb18965ff | ||
|
|
53e07d1f26 | ||
|
|
857bea336a | ||
|
|
eb54b1eb9d | ||
|
|
cd378f537e | ||
|
|
4675f1126d | ||
|
|
60bb66d0ac | ||
|
|
02e6d6d1d5 | ||
|
|
5e6208eebb | ||
|
|
7f68a664a7 | ||
|
|
49866709c0 | ||
|
|
a70399b780 | ||
|
|
4555565753 | ||
|
|
4253f57ed8 | ||
|
|
cb2859f60c | ||
|
|
9818b99812 | ||
|
|
d0d85f26b2 | ||
|
|
6c0bab27c0 | ||
|
|
61cdc763f8 | ||
|
|
be73d63bf2 | ||
|
|
6c540fc099 | ||
|
|
7b19cbcd52 | ||
|
|
5350506a89 | ||
|
|
479df7cdad | ||
|
|
570f594dc7 | ||
|
|
b813dbe8c4 | ||
|
|
558044db25 | ||
|
|
5d11f51e05 | ||
|
|
1264384402 | ||
|
|
65309f25c2 | ||
|
|
c565decbe3 | ||
|
|
4bc1ae96c9 | ||
|
|
d3390fdbba | ||
|
|
d90f2cc83d | ||
|
|
e07f55e5ed | ||
|
|
4df17bc17e | ||
|
|
9a4c2a8cb5 | ||
|
|
cd6b797481 | ||
|
|
7ceb99ec79 | ||
|
|
79f11383f1 | ||
|
|
cc62c116a8 | ||
|
|
a9f6a04e83 | ||
|
|
69453350a2 | ||
|
|
a0c3bf02ec | ||
|
|
ba1b08eab8 | ||
|
|
d90d203ac3 | ||
|
|
678d898d48 | ||
|
|
351d13e1c3 | ||
|
|
c9214b5535 | ||
|
|
cfdd412546 | ||
|
|
c649698806 | ||
|
|
3accc0e158 | ||
|
|
352bb2c059 | ||
|
|
4a9bf570f8 | ||
|
|
4f608d2dd2 | ||
|
|
7eaa3f583f | ||
|
|
0cb6096019 | ||
|
|
82daf4044b | ||
|
|
4f31588cec | ||
|
|
5fe4a8fa97 | ||
|
|
6d6e928854 | ||
|
|
54cb053dfe | ||
|
|
d564da3872 | ||
|
|
cd3be1ae27 | ||
|
|
ca8e4616b4 | ||
|
|
8dfefdc7fd | ||
|
|
d89555723b | ||
|
|
28ec6f98cf | ||
|
|
6009ee7360 | ||
|
|
b9677ca557 | ||
|
|
2e2ba2be58 | ||
|
|
1dacc1371b | ||
|
|
1890a22efe | ||
|
|
202b61ec2e | ||
|
|
aba494e6b9 | ||
|
|
56863d5672 | ||
|
|
2ff99b7116 | ||
|
|
a267a2644c | ||
|
|
bb1287e02e | ||
|
|
00a24f13b6 | ||
|
|
213eda9797 | ||
|
|
47e3bf8fe5 | ||
|
|
95f3ebc1e0 | ||
|
|
2f8439d6ac | ||
|
|
f13c99de80 | ||
|
|
ed21b3db8d | ||
|
|
bb19f05f8f | ||
|
|
c5cd14afb5 | ||
|
|
6cfa34c341 | ||
|
|
4bdb25b687 | ||
|
|
477d59d271 | ||
|
|
7b43eed28d | ||
|
|
fc296b44d8 | ||
|
|
05cfecd073 | ||
|
|
6ee7472b65 | ||
|
|
cbcab47db3 | ||
|
|
93f6ab8b61 | ||
|
|
0881ef6524 | ||
|
|
15014a7bb1 | ||
|
|
af911d8592 | ||
|
|
c63caaf040 | ||
|
|
66f1d9140f | ||
|
|
d8b0584915 | ||
|
|
4e0dfd9883 | ||
|
|
8fd42b9a94 | ||
|
|
6fb8e9dbc6 | ||
|
|
4d9a4bf9e2 | ||
|
|
15ce829190 | ||
|
|
faf4b669bb | ||
|
|
9bdfe64ced | ||
|
|
ae6c83dc70 | ||
|
|
52ce8e5d0b | ||
|
|
2f1d7c7302 | ||
|
|
2aa0e0c320 | ||
|
|
c28461942c | ||
|
|
a114de32a9 | ||
|
|
d73206c237 | ||
|
|
f58bc266d6 | ||
|
|
03109e63b5 | ||
|
|
37c16f54ef | ||
|
|
b6275fc33e | ||
|
|
68d852b5b8 | ||
|
|
a7d44e7ec5 | ||
|
|
87f5d6a117 | ||
|
|
3bf924ef3a | ||
|
|
79676891a0 | ||
|
|
0fbd5f0b84 | ||
|
|
0b0696e624 | ||
|
|
43a272b50f | ||
|
|
1ab9763302 | ||
|
|
e0053af20a | ||
|
|
ddedf9d11f | ||
|
|
27c541a6be | ||
|
|
ba4b8d040f | ||
|
|
29ce881e63 | ||
|
|
9c3812c405 | ||
|
|
6b28a01413 | ||
|
|
d1f7063d48 | ||
|
|
6b99d31fdc | ||
|
|
5b2f6e1938 | ||
|
|
245e424c3a | ||
|
|
f09236d61d | ||
|
|
295854af48 | ||
|
|
d0190cacf9 | ||
|
|
9b35a16d7b | ||
|
|
75e2830057 | ||
|
|
c68f76adbc | ||
|
|
5ac349f1eb | ||
|
|
df45d927db | ||
|
|
0fa7093461 | ||
|
|
514fb9c2b0 | ||
|
|
b55a378396 | ||
|
|
3d8ccdca45 | ||
|
|
157ddfdac9 | ||
|
|
bcfb9d54ef | ||
|
|
0ae7a45dd8 | ||
|
|
475b998c1a | ||
|
|
cdbcbfa3ee | ||
|
|
96b7d31475 | ||
|
|
08024d2269 | ||
|
|
f7f76fe14f | ||
|
|
ec5d8de6c2 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
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';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
-978
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
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';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,16 +0,0 @@
|
||||
# jsr registry should not be edited or removed
|
||||
.npmrc
|
||||
|
||||
# vite client types are needed
|
||||
src/vite-env.d.ts
|
||||
|
||||
# tsconfig is stable and working correctly, so should not be edited
|
||||
tsconfig.json
|
||||
tsconfig.app.json
|
||||
tsconfig.node.json
|
||||
|
||||
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
|
||||
postcss.config.js
|
||||
|
||||
# vite config is stable and usually should not need to be edited
|
||||
vite.config.ts
|
||||
+294
-22
@@ -1,3 +1,150 @@
|
||||
# Shakespeare - AI-Powered Nostr Website Builder
|
||||
|
||||
Shakespeare is a browser-based AI chat application that allows users to build custom Nostr websites through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
|
||||
|
||||
### Virtual Filesystem Layout
|
||||
|
||||
Shakespeare uses LightningFS to provide a browser-based virtual filesystem (VFS) that persists project files in IndexedDB. This is the VFS within the browser that Shakespeare agents act upon. Each project is stored in its own isolated directory structure within the virtual filesystem.
|
||||
|
||||
#### Virtual Filesystem Architecture
|
||||
|
||||
```
|
||||
/
|
||||
├── projects/
|
||||
│ └── {projectId}/ # Individual project directory
|
||||
│ └── ... # Project files (package.json, src/, public/, etc.)
|
||||
├── config/ # Configuration files
|
||||
│ ├── ai.json # AI provider settings and API keys
|
||||
│ └── git.json # Git credentials and repository settings
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
```
|
||||
|
||||
#### Key Features
|
||||
|
||||
- **IndexedDB Backend**: All project files are stored in the browser's IndexedDB for persistence across sessions
|
||||
- **Project Isolation**: Each project has its own directory namespace to prevent conflicts
|
||||
- **File Operations**: Full POSIX-like filesystem operations (read, write, mkdir, rm, etc.)
|
||||
- **Git Integration**: Projects can be initialized as Git repositories for template cloning
|
||||
|
||||
This architecture allows Shakespeare to provide a full development environment entirely within the browser, with no server-side storage requirements.
|
||||
|
||||
#### AI Tools Available in Shakespeare
|
||||
|
||||
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 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
|
||||
- **BuildProjectTool**: Build and compile projects
|
||||
- **TypecheckTool**: Run TypeScript type checking
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
- **DeployProjectTool**: Deploy projects to hosting platforms
|
||||
- **ReadWebpageTool**: Fetch and read web pages
|
||||
- **NostrReadNipTool**: Read Nostr protocol NIP documents
|
||||
- **NostrReadKindTool**: Read Nostr event kind documentation
|
||||
- **NostrReadTagTool**: Read Nostr tag documentation
|
||||
- **NostrReadProtocolTool**: Read Nostr protocol basics
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
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:**
|
||||
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
|
||||
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
|
||||
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
|
||||
|
||||
#### Security
|
||||
|
||||
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
|
||||
|
||||
- **Read operations**: Can access any file in the VFS, including absolute paths
|
||||
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
|
||||
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
|
||||
|
||||
### Git Integration with isomorphic-git
|
||||
|
||||
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
||||
|
||||
#### Key Components
|
||||
|
||||
- **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)
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
|
||||
**Project Creation:**
|
||||
1. Clone template from GitLab repository (shallow clone, depth: 1)
|
||||
2. Remove original Git history
|
||||
3. Initialize fresh repository with `main` branch
|
||||
4. Stage all files and create initial commit
|
||||
|
||||
**Version Control:**
|
||||
- Automatic staging of all changed files before commits
|
||||
- Real-time status tracking (modified, added, deleted, untracked, staged files)
|
||||
- Full commit history with author info and SHA hashes
|
||||
- Branch management and remote repository support
|
||||
|
||||
**AI Integration:**
|
||||
- GitCommitTool allows AI assistants to commit changes automatically
|
||||
- Validates repository status and handles edge cases
|
||||
- Generates descriptive commit messages with file change statistics
|
||||
|
||||
**Browser Compatibility:**
|
||||
- CORS proxy for GitHub/GitLab repositories (`https://cors.isomorphic-git.org`)
|
||||
- IndexedDB persistence across browser sessions
|
||||
- Gitignore support using the `ignore` library
|
||||
|
||||
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
|
||||
|
||||
## AI Message Format
|
||||
|
||||
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
|
||||
|
||||
### User Messages
|
||||
|
||||
**String Content**: When the user message `content` is a string, it represents the actual user's message directly.
|
||||
|
||||
```json
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Please help me build a todo app"
|
||||
}
|
||||
```
|
||||
|
||||
**Array Content**: When the user message `content` is an array of parts, the structure follows this pattern:
|
||||
|
||||
- **First text part**: Represents the user's actual message
|
||||
- **Subsequent text parts**: Represent user actions, such as adding files to the VFS
|
||||
|
||||
```json
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Can you add this logo to my site?"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Added file: /tmp/logo.svg"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
This format allows the Shakespeare UI to parse and display user actions appropriately while maintaining compatibility with OpenAI's message format standard.
|
||||
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
@@ -18,6 +165,10 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
||||
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
||||
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
@@ -25,15 +176,44 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useFS`: Access virtual filesystem for project file operations
|
||||
- `useAISettings`: Manage AI provider configurations and API keys
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building)
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `useZaps`: Lightning zap functionality with payment processing
|
||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
||||
- `useNWC`: Nostr Wallet Connect connection management
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin)
|
||||
- `/src/lib/commands/`: Shell command implementations for virtual filesystem
|
||||
- `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.)
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
- `/src/lib/tools/`: AI tool implementations for project development
|
||||
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
|
||||
- Project tools: `BuildProjectTool`, `TypecheckTool`, `DeployProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
- Web access: `ReadWebpageTool`
|
||||
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
|
||||
- `/src/contexts/`: React context providers
|
||||
- `AppContext`: Global app configuration and theme
|
||||
- `FSContext`: Virtual filesystem access
|
||||
- `AISettingsContext`: AI provider settings and API key management
|
||||
- `GitSettingsContext`: Git credentials and repository configuration
|
||||
- `SessionManagerContext`: AI chat session management
|
||||
- `NWCContext`: Nostr Wallet Connect integration
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
@@ -81,7 +261,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
@@ -95,9 +274,9 @@ These components follow a consistent pattern using React's `forwardRef` and use
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
1. Edit AGENTS.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
@@ -110,9 +289,9 @@ This project comes with custom hooks for querying and publishing events on the N
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
@@ -120,7 +299,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
@@ -138,7 +317,7 @@ When implementing features that could use existing NIPs, follow this decision fr
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
@@ -299,6 +478,70 @@ function usePosts() {
|
||||
}
|
||||
```
|
||||
|
||||
### Infinite Scroll for Feeds
|
||||
|
||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useGlobalFeed() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['global-feed'],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const filter = { kinds: [1], limit: 20 };
|
||||
if (pageParam) filter.until = pageParam;
|
||||
|
||||
const events = await nostr.query([filter], {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
||||
});
|
||||
|
||||
return events;
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length === 0) return undefined;
|
||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example usage with intersection observer for automatic loading:
|
||||
|
||||
```tsx
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
|
||||
function GlobalFeed() {
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||
const { ref, inView } = useInView();
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [inView, hasNextPage, fetchNextPage]);
|
||||
|
||||
const posts = data?.pages.flat() || [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="py-4">
|
||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
@@ -494,12 +737,14 @@ The `LoginArea` component handles all the login-related UI and interactions, inc
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
@@ -553,7 +798,7 @@ This project includes a boilerplate `NIP19Page` component that provides the foun
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
@@ -868,14 +1113,14 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
1. **Install a font package** using npm:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
- For Inter Variable: `@fontsource-variable/inter`
|
||||
- For Roboto: `@fontsource/roboto`
|
||||
- For Outfit Variable: `@fontsource-variable/outfit`
|
||||
- For Poppins: `@fontsource/poppins`
|
||||
- For Open Sans: `@fontsource/open-sans`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
@@ -928,8 +1173,11 @@ When users specify color schemes:
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
## Writing Tests vs Running Tests
|
||||
|
||||
There is an important distinction between **writing new tests** and **running existing tests**:
|
||||
|
||||
### Writing Tests (Creating New Test Files)
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
@@ -942,6 +1190,14 @@ When users specify color schemes:
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Running Tests (Executing the Test Suite)
|
||||
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
|
||||
|
||||
- **You must run the test script** to validate your changes
|
||||
- **Your task is not complete** until the test script passes without errors
|
||||
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
|
||||
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
@@ -971,8 +1227,24 @@ describe('MyComponent', () => {
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
## Validating Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
|
||||
|
||||
### Validation Priority Order
|
||||
|
||||
Run available tools in this priority order:
|
||||
|
||||
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
|
||||
2. **Building/Compilation** (Required): Verify the project builds successfully
|
||||
3. **Linting** (Recommended): Check code style and catch potential issues
|
||||
4. **Tests** (If Available): Run existing test suite
|
||||
|
||||
**Minimum Requirements:**
|
||||
- Code must type-check without errors
|
||||
- Code must build/compile successfully
|
||||
- Fix any critical linting errors that would break functionality
|
||||
|
||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
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';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
-978
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
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';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
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';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -5,7 +5,8 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
|
||||
## Features
|
||||
|
||||
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
|
||||
- **Project Management**: Create and manage multiple projects in a Google Drive-like interface
|
||||
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
|
||||
- **Project Management**: Create and manage multiple projects with sidebar navigation
|
||||
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
|
||||
- **File Explorer**: Browse and manage your project files
|
||||
- **Project Preview**: Preview your website as you build it
|
||||
@@ -15,8 +16,9 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
|
||||
|
||||
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
|
||||
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
|
||||
3. **Edit Code**: Switch to the code view to manually edit files if needed
|
||||
4. **Preview**: View your website in the preview pane
|
||||
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
|
||||
4. **Edit Code**: Switch to the code view to manually edit files if needed
|
||||
5. **Preview**: View your website in the preview pane
|
||||
|
||||
## Project Structure
|
||||
|
||||
@@ -41,11 +43,36 @@ The AI assistant can:
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Homepage**: Create new projects and view existing ones
|
||||
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
|
||||
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
|
||||
3. **File Explorer**: Navigate your project files in the code view
|
||||
4. **File Editor**: Edit files with syntax highlighting and save changes
|
||||
|
||||
## Git Integration
|
||||
|
||||
Shakespeare includes full Git functionality with credential management:
|
||||
|
||||
### Features
|
||||
- **Version Control**: Full Git repository support with commit history and branch management
|
||||
- **Global Credentials**: Configure Git credentials once and use them across all projects
|
||||
- **Automatic Matching**: Credentials are automatically matched to repository origins
|
||||
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
|
||||
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
|
||||
|
||||
### Setting Up Git Credentials
|
||||
|
||||
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
|
||||
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
|
||||
3. **Enter Token**: Use your username and personal access token for authentication
|
||||
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
|
||||
|
||||
### Repository Operations
|
||||
|
||||
- **Push/Pull**: Sync changes with remote repositories using configured credentials
|
||||
- **Status Monitoring**: Real-time Git status with file changes and sync information
|
||||
- **Commit History**: View commit history and repository information
|
||||
- **Branch Management**: Work with different branches and track remote changes
|
||||
|
||||
## Development
|
||||
|
||||
Built with:
|
||||
@@ -54,6 +81,5 @@ Built with:
|
||||
- Vite
|
||||
- TailwindCSS
|
||||
- shadcn/ui
|
||||
- Vercel AI SDK
|
||||
- LightningFS for filesystem
|
||||
- isomorphic-git for template cloning
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
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';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -41,7 +41,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
@@ -54,6 +54,23 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"id": 123
|
||||
}
|
||||
|
||||
// POST Request with JSON body
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/api/data",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30}
|
||||
}
|
||||
},
|
||||
"id": 124
|
||||
}
|
||||
|
||||
// Success Response
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
@@ -64,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"Content-Type": "application/javascript",
|
||||
"Cache-Control": "no-cache"
|
||||
},
|
||||
"body": "console.log('hello');"
|
||||
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7"
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
@@ -94,14 +111,14 @@ full request body support
|
||||
- `url` (string): Full URL of the request
|
||||
- `method` (string): HTTP method (GET, POST, etc.)
|
||||
- `headers` (object): Request headers as key-value pairs
|
||||
- `body` (string|null): Request body as string, or null if no body
|
||||
- `body` (string|null): Request body as base64 encoded string, or null if no body
|
||||
|
||||
**Result:**
|
||||
|
||||
- `status` (number): HTTP status code (200, 404, etc.)
|
||||
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
|
||||
- `headers` (object): Response headers as key-value pairs
|
||||
- `body` (string|null): Response body content (null if status is 204)
|
||||
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
|
||||
|
||||
**Error Codes:**
|
||||
|
||||
@@ -117,8 +134,8 @@ full request body support
|
||||
- File uploads (as base64 strings)
|
||||
- Any HTTP method with body content
|
||||
|
||||
Request bodies are serialized as strings, so binary data should be
|
||||
base64-encoded.
|
||||
Request bodies must be base64-encoded strings when not null. This ensures
|
||||
consistent handling of both text and binary data across the messaging protocol.
|
||||
|
||||
## Implementation
|
||||
|
||||
@@ -153,6 +170,9 @@ class FetchClientParent {
|
||||
const url = new URL(fetchRequest.url);
|
||||
const path = url.pathname;
|
||||
|
||||
// Decode request body if present
|
||||
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
|
||||
|
||||
const file = this.files.get(path);
|
||||
|
||||
if (file) {
|
||||
@@ -166,7 +186,7 @@ class FetchClientParent {
|
||||
"Content-Type": file.contentType,
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
body: file.content,
|
||||
body: btoa(file.content), // base64 encode the response body
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -180,7 +200,7 @@ class FetchClientParent {
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: `File not found: ${path}`,
|
||||
body: btoa(`File not found: ${path}`), // base64 encode the error message
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -264,6 +284,23 @@ class JSONRPCClient {
|
||||
}
|
||||
```
|
||||
|
||||
## Base64 Encoding
|
||||
|
||||
All request and response bodies must be base64 encoded when not null. This ensures:
|
||||
|
||||
- **Consistent Data Handling:** Both text and binary data are handled uniformly
|
||||
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
|
||||
- **Binary Data Support:** Enables transmission of images, files, and other binary content
|
||||
|
||||
**Encoding/Decoding:**
|
||||
```javascript
|
||||
// Encoding (before sending)
|
||||
const encodedBody = btoa(originalBody);
|
||||
|
||||
// Decoding (after receiving)
|
||||
const decodedBody = atob(encodedBody);
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- **Origin Validation:** Always verify message origin
|
||||
|
||||
@@ -180,8 +180,18 @@ class FetchClient {
|
||||
|
||||
const response = await this.rpcClient.fetch(serializedRequest);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
if (response.headers["Content-Type"] !== "text/html") {
|
||||
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
// Replace current document with the site index content
|
||||
this.replaceDocument(response.body);
|
||||
this.replaceDocument(text);
|
||||
} catch (error) {
|
||||
this.showError("Failed to load site index", error);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,14 @@ function handleJSONRPCResponse(message) {
|
||||
|
||||
// Create response from serialized response
|
||||
const { status, statusText, headers, body } = result;
|
||||
const response = new Response(body, {
|
||||
|
||||
// Decode base64 body if present
|
||||
let decoded = null;
|
||||
if (typeof body === "string") {
|
||||
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
|
||||
}
|
||||
|
||||
const response = new Response(decoded, {
|
||||
status: status || 200,
|
||||
statusText: statusText || "OK",
|
||||
headers: headers || {},
|
||||
@@ -65,8 +72,9 @@ async function requestViaJSONRPC(request) {
|
||||
let body = null;
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to string (JSON-serializable)
|
||||
body = await request.text();
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
|
||||
Generated
+430
-52
@@ -9,11 +9,12 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@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",
|
||||
@@ -42,25 +43,27 @@
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@soapbox.pub/streamdown": "^1.0.11",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@std/path": "npm:@jsr/std__path@^1.1.1",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webcontainer/api": "^1.6.1",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"ignore": "^7.0.5",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -71,13 +74,13 @@
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"recharts": "^2.12.7",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"sonner": "^1.5.0",
|
||||
"streamdown": "^1.0.12",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.1",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -887,6 +890,16 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/eslintrc/node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/js": {
|
||||
"version": "9.31.0",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.31.0.tgz",
|
||||
@@ -971,6 +984,36 @@
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@getalby/lightning-tools": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@getalby/lightning-tools/-/lightning-tools-5.2.1.tgz",
|
||||
"integrity": "sha512-dxOmJLJAh6qJ8rsbA5/Bwj7MSI9X3RkxxqmCedl5rfP+yKwNSdfu8i4EiCZN/tk2hNBJb8GHSCcPRNZfwfmEHg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"type": "lightning",
|
||||
"url": "lightning:[email protected]"
|
||||
}
|
||||
},
|
||||
"node_modules/@getalby/sdk": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@getalby/sdk/-/sdk-6.0.1.tgz",
|
||||
"integrity": "sha512-iFEKT0VI2p7sGNmpLD65rZwIqD+rRHV8OdclKJtqZ7AMlw/ND7M8caJAZt6iU9TY/4O/AiiRenTALGxzckttQw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@getalby/lightning-tools": "^5.2.0",
|
||||
"nostr-tools": "2.16.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"type": "lightning",
|
||||
"url": "lightning:[email protected]"
|
||||
}
|
||||
},
|
||||
"node_modules/@hookform/resolvers": {
|
||||
"version": "3.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
|
||||
@@ -1180,9 +1223,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jsr/nostrify__nostrify": {
|
||||
"version": "0.46.4",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.4.tgz",
|
||||
"integrity": "sha512-bYuYkw9+jnHIDEJD6i+w0p8xV1oBLr1RF5rS3qF2yTz1b8i50dXKMO2cLObjalAAO3RYbnib3l85t1ZgWLCzAA==",
|
||||
"version": "0.46.5",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.5.tgz",
|
||||
"integrity": "sha512-l81N0o1A4WKAnOhq600ASDLxZbwzFZzUjhAkARPNFbWkXmEssVvXEQXyyoy1s7lboK45iZCijW0Bia7NHXmSug==",
|
||||
"dependencies": {
|
||||
"@jsr/nostrify__types": "^0.36.0",
|
||||
"@jsr/scure__base": "^1.2.4",
|
||||
@@ -1310,9 +1353,9 @@
|
||||
},
|
||||
"node_modules/@nostrify/nostrify": {
|
||||
"name": "@jsr/nostrify__nostrify",
|
||||
"version": "0.46.4",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.4.tgz",
|
||||
"integrity": "sha512-bYuYkw9+jnHIDEJD6i+w0p8xV1oBLr1RF5rS3qF2yTz1b8i50dXKMO2cLObjalAAO3RYbnib3l85t1ZgWLCzAA==",
|
||||
"version": "0.46.5",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.5.tgz",
|
||||
"integrity": "sha512-l81N0o1A4WKAnOhq600ASDLxZbwzFZzUjhAkARPNFbWkXmEssVvXEQXyyoy1s7lboK45iZCijW0Bia7NHXmSug==",
|
||||
"dependencies": {
|
||||
"@jsr/nostrify__types": "^0.36.0",
|
||||
"@jsr/scure__base": "^1.2.4",
|
||||
@@ -1325,11 +1368,11 @@
|
||||
},
|
||||
"node_modules/@nostrify/react": {
|
||||
"name": "@jsr/nostrify__react",
|
||||
"version": "0.2.8",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__react/0.2.8.tgz",
|
||||
"integrity": "sha512-9sCsMm1uwuGWU+NhgFf6LS/4JzeRXnGOz+ocA5X3/ncvxZhidPOEAU39QyygRLFo/JYG8OC5wlyH8w0Uejq+VQ==",
|
||||
"version": "0.2.9",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__react/0.2.9.tgz",
|
||||
"integrity": "sha512-S19YP9adasszJbxgdIeC/4KXtZsAs9nf8I/2ptjr7pipyZWx8HykjjFE5pahj2TNMFc0/pEErcYpxGBg5t2n6Q==",
|
||||
"dependencies": {
|
||||
"@jsr/nostrify__nostrify": "^0.46.4",
|
||||
"@jsr/nostrify__nostrify": "^0.46.5",
|
||||
"nostr-tools": "^2.13.0",
|
||||
"react": "^18.0.0"
|
||||
}
|
||||
@@ -3204,6 +3247,12 @@
|
||||
"url": "https://github.com/sponsors/dcastil"
|
||||
}
|
||||
},
|
||||
"node_modules/@std/encoding": {
|
||||
"name": "@jsr/std__encoding",
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/1.0.10.tgz",
|
||||
"integrity": "sha512-WK2njnDTyKefroRNk2Ooq7GStp6Y0ccAvr4To+Z/zecRAGe7+OSvH9DbiaHpAKwEi2KQbmpWMOYsdNt+TsdmSw=="
|
||||
},
|
||||
"node_modules/@std/path": {
|
||||
"name": "@jsr/std__path",
|
||||
"version": "1.1.1",
|
||||
@@ -3594,6 +3643,15 @@
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@types/chrome": {
|
||||
"version": "0.0.74",
|
||||
"resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.74.tgz",
|
||||
"integrity": "sha512-hzosS5CkQcIKCgxcsV2AzbJ36KNxG/Db2YEN/erEu7Boprg+KpMDLBQqKFmSo+JkQMGqRcicUyqCowJpuT+C6A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/filesystem": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-array": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz",
|
||||
@@ -3681,6 +3739,21 @@
|
||||
"@types/estree": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/filesystem": {
|
||||
"version": "0.0.36",
|
||||
"resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz",
|
||||
"integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/filewriter": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/filewriter": {
|
||||
"version": "0.0.33",
|
||||
"resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz",
|
||||
"integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/hast": {
|
||||
"version": "2.3.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/hast/-/hast-2.3.10.tgz",
|
||||
@@ -3824,6 +3897,16 @@
|
||||
"typescript": ">=4.8.4 <5.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/parser": {
|
||||
"version": "8.31.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.31.1.tgz",
|
||||
@@ -4165,12 +4248,6 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@webcontainer/api": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@webcontainer/api/-/api-1.6.1.tgz",
|
||||
"integrity": "sha512-2RS2KiIw32BY1Icf6M1DvqSmcon9XICZCDgS29QJb2NmF12ZY2V5Ia+949hMKB3Wno+P/Y8W+sPP59PZeXSELg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.15.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
@@ -4581,6 +4658,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase-css": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
|
||||
@@ -4759,6 +4845,72 @@
|
||||
"integrity": "sha512-bLSptAy2P0s6hU4PzuIMKmMJJSE6gLXGH1cntDu7bWJUksvuM+7ReOK61mozULErYvP6a15rnYl0zFDef+pyPw==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
|
||||
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.0",
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui/node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui/node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cliui/node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui/node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui/node_modules/wrap-ansi": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/clsx": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
|
||||
@@ -5068,11 +5220,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decamelize": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
|
||||
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.5.0.tgz",
|
||||
"integrity": "sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw==",
|
||||
"dev": true,
|
||||
"version": "10.6.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
|
||||
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/decimal.js-light": {
|
||||
@@ -5193,6 +5353,12 @@
|
||||
"integrity": "sha512-iSq8ngPOt0K53A6eVr4d5Kn6GNrM2nQZtC740pzIriHtn4pOQ2lyzEXQMBeVcWERN0ye7fhBsk9PbLLQOnUx/g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dijkstrajs": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dlv": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
|
||||
@@ -5524,6 +5690,16 @@
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint/node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/espree": {
|
||||
"version": "10.4.0",
|
||||
"resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
|
||||
@@ -5854,6 +6030,15 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
@@ -6648,9 +6833,9 @@
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
|
||||
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
@@ -6924,6 +7109,15 @@
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/isomorphic-git/node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/isomorphic-git/node_modules/pify": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",
|
||||
@@ -8534,16 +8728,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/next-themes": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.3.0.tgz",
|
||||
"integrity": "sha512-/QHIrsYpd6Kfk7xakK4svpDI5mmXP0gfvCoJdGpZQ2TOrQZmsW0QxjaiLn8wbIKjtm4BTSqLoix4lxYYOnLJ/w==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8 || ^17 || ^18",
|
||||
"react-dom": "^16.8 || ^17 || ^18"
|
||||
}
|
||||
},
|
||||
"node_modules/node-releases": {
|
||||
"version": "2.0.19",
|
||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz",
|
||||
@@ -8571,9 +8755,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nostr-tools": {
|
||||
"version": "2.15.2",
|
||||
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.15.2.tgz",
|
||||
"integrity": "sha512-utmqVVS4HMDiwhIgI6Cr+KqA4aUhF3Sb755iO/qCiqxc5H9JW/9Z3N1RO/jKWpjP6q/Vx0lru7IYuiPvk+2/ng==",
|
||||
"version": "2.16.2",
|
||||
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.16.2.tgz",
|
||||
"integrity": "sha512-ZxH9EbSt5ypURZj2TGNJxZd0Omb5ag5KZSu8IyJMCdLyg2KKz+2GA0sP/cSawCQEkyviIN4eRT4G2gB/t9lMRw==",
|
||||
"license": "Unlicense",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^0.5.1",
|
||||
@@ -8721,6 +8905,15 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-try": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/package-json-from-dist": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
|
||||
@@ -8786,7 +8979,6 @@
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -8886,6 +9078,15 @@
|
||||
"pathe": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/possible-typed-array-names": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||
@@ -9166,6 +9367,23 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
|
||||
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dijkstrajs": "^1.0.1",
|
||||
"pngjs": "^5.0.0",
|
||||
"yargs": "^15.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"qrcode": "bin/qrcode"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/queue-microtask": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||
@@ -9690,6 +9908,21 @@
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/resolve": {
|
||||
"version": "1.22.10",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
|
||||
@@ -9862,6 +10095,12 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/set-function-length": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
|
||||
@@ -10015,16 +10254,6 @@
|
||||
"simple-concat": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sonner": {
|
||||
"version": "1.7.4",
|
||||
"resolved": "https://registry.npmjs.org/sonner/-/sonner-1.7.4.tgz",
|
||||
"integrity": "sha512-DIS8z4PfJRbIyfVFDVnK9rO3eYDtse4Omcm6bt0oEr5/jtLgysmjuBl1frJ9E/EQZrFmKx2A8m/s5s9CRXIzhw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc",
|
||||
"react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc"
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -11366,6 +11595,15 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/webln": {
|
||||
"version": "0.3.2",
|
||||
"resolved": "https://registry.npmjs.org/webln/-/webln-0.3.2.tgz",
|
||||
"integrity": "sha512-YYT83aOCLup2AmqvJdKtdeBTaZpjC6/JDMe8o6x1kbTYWwiwrtWHyO//PAsPixF3jwFsAkj5DmiceB6w/QSe7Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/chrome": "^0.0.74"
|
||||
}
|
||||
},
|
||||
"node_modules/webpack-virtual-modules": {
|
||||
"version": "0.6.2",
|
||||
"resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
|
||||
@@ -11430,6 +11668,12 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/which-module": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
||||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/which-typed-array": {
|
||||
"version": "1.1.19",
|
||||
"resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz",
|
||||
@@ -11620,6 +11864,12 @@
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "2.7.1",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.1.tgz",
|
||||
@@ -11632,6 +11882,134 @@
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
|
||||
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^6.0.0",
|
||||
"decamelize": "^1.2.0",
|
||||
"find-up": "^4.1.0",
|
||||
"get-caller-file": "^2.0.1",
|
||||
"require-directory": "^2.1.1",
|
||||
"require-main-filename": "^2.0.0",
|
||||
"set-blocking": "^2.0.0",
|
||||
"string-width": "^4.2.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^4.0.0",
|
||||
"yargs-parser": "^18.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "18.1.3",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"camelcase": "^5.0.0",
|
||||
"decamelize": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/yargs/node_modules/find-up": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
|
||||
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^5.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/locate-path": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
||||
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-try": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/p-locate": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
|
||||
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs/node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
|
||||
+11
-8
@@ -4,18 +4,19 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npm i && vite",
|
||||
"build": "npm i && vite build && cp dist/index.html dist/404.html",
|
||||
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
|
||||
"dev": "npm i --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@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",
|
||||
@@ -44,25 +45,27 @@
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@soapbox.pub/streamdown": "^1.0.11",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@std/path": "npm:@jsr/std__path@^1.1.1",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webcontainer/api": "^1.6.1",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"ignore": "^7.0.5",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -73,13 +76,13 @@
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"recharts": "^2.12.7",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"sonner": "^1.5.0",
|
||||
"streamdown": "^1.0.12",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.1",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"src": "/favicon.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"src": "/favicon.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
|
||||
+38
-28
@@ -4,21 +4,21 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createHead, UnheadProvider } from '@unhead/react/client';
|
||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||
import { Suspense } from 'react';
|
||||
import { Suspense, useEffect } from 'react';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { Toaster as Sonner } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { WebContainerAdapter } from '@/lib/WebContainerAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
const head = createHead({
|
||||
@@ -40,6 +40,7 @@ const queryClient = new QueryClient({
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
@@ -53,35 +54,44 @@ const presetRelays = [
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
|
||||
// Initialize JSRuntime with WebContainer adapter
|
||||
const jsRuntime = new WebContainerAdapter();
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from /tmp directory
|
||||
function FSCleanupHandler() {
|
||||
useEffect(() => {
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs).catch(console.error);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<JSRuntimeProvider runtime={jsRuntime}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</QueryClientProvider>
|
||||
</JSRuntimeProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,14 @@ import { SessionMonitor } from "./components/SessionMonitor";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Settings from "./pages/Settings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
return (
|
||||
@@ -16,6 +21,12 @@ export function AppRouter() {
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus } from 'lucide-react';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
interface AIMessageItemProps {
|
||||
@@ -52,6 +53,11 @@ export const AIMessageItem = memo(({
|
||||
|
||||
// Generate icons and titles based on tool name and arguments
|
||||
switch (toolName) {
|
||||
case 'shell':
|
||||
return {
|
||||
icon: Terminal,
|
||||
title: args.command ? args.command : 'Shell Command'
|
||||
};
|
||||
case 'text_editor_view': {
|
||||
const title = args.path
|
||||
? (args.start_line || args.end_line
|
||||
@@ -126,6 +132,16 @@ export const AIMessageItem = memo(({
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
|
||||
};
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project'
|
||||
};
|
||||
case 'typecheck':
|
||||
return {
|
||||
icon: CheckCircle,
|
||||
title: 'TypeScript'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
@@ -160,6 +176,7 @@ export const AIMessageItem = memo(({
|
||||
const toolInfo = getToolInfo();
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Regular tool message rendering
|
||||
return (
|
||||
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
|
||||
<button
|
||||
@@ -189,11 +206,17 @@ export const AIMessageItem = memo(({
|
||||
// Regular rendering for non-tool messages
|
||||
if (message.role === 'user') {
|
||||
// User messages: right-aligned bubble without avatar/name
|
||||
const userContent = typeof message.content === 'string'
|
||||
? message.content
|
||||
: Array.isArray(message.content)
|
||||
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm whitespace-pre-wrap break-words">
|
||||
{getContent()}
|
||||
<div className="text-sm break-words">
|
||||
<UserMessage content={userContent} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -205,7 +228,7 @@ export const AIMessageItem = memo(({
|
||||
<div className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<div className="break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { AISettingsProvider } from './AISettingsProvider';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
@@ -16,31 +17,42 @@ Object.defineProperty(window, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
});
|
||||
|
||||
// Mock the config utils
|
||||
vi.mock('@/lib/configUtils', () => ({
|
||||
readAISettings: vi.fn(),
|
||||
writeAISettings: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('AISettingsProvider', () => {
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
localStorageMock.getItem.mockReturnValue(null);
|
||||
|
||||
// Mock the read function to return default settings
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: {},
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should initialize with empty recentlyUsedModels array', () => {
|
||||
it('should initialize with empty recentlyUsedModels array', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<AISettingsProvider>{children}</AISettingsProvider>
|
||||
</TestApp>
|
||||
),
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should add recently used models correctly', () => {
|
||||
it('should add recently used models correctly', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<AISettingsProvider>{children}</AISettingsProvider>
|
||||
</TestApp>
|
||||
),
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
@@ -52,13 +64,13 @@ describe('AISettingsProvider', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('should move existing model to front when used again', () => {
|
||||
it('should move existing model to front when used again', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<AISettingsProvider>{children}</AISettingsProvider>
|
||||
</TestApp>
|
||||
),
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
// Add multiple models
|
||||
@@ -86,13 +98,13 @@ describe('AISettingsProvider', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('should limit recently used models to 10 items', () => {
|
||||
it('should limit recently used models to 10 items', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<AISettingsProvider>{children}</AISettingsProvider>
|
||||
</TestApp>
|
||||
),
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
// Add 12 models
|
||||
@@ -108,27 +120,96 @@ describe('AISettingsProvider', () => {
|
||||
expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3');
|
||||
});
|
||||
|
||||
it('should migrate old settings without recentlyUsedModels', () => {
|
||||
it('should migrate old settings without recentlyUsedModels', async () => {
|
||||
const oldSettings = {
|
||||
providers: {
|
||||
openrouter: {
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
};
|
||||
|
||||
localStorageMock.getItem.mockReturnValue(JSON.stringify(oldSettings));
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue(oldSettings);
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
expect(result.current.settings.providers).toEqual(oldSettings.providers);
|
||||
});
|
||||
});
|
||||
|
||||
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Create a custom TestApp that mocks the query client
|
||||
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = useQueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<AISettingsProvider>{children}</AISettingsProvider>
|
||||
<MockedTestApp>{children}</MockedTestApp>
|
||||
</TestApp>
|
||||
),
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
expect(result.current.settings.providers).toEqual(oldSettings.providers);
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
providers: {
|
||||
'test-provider': {
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
|
||||
});
|
||||
|
||||
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Create a custom TestApp that mocks the query client
|
||||
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = useQueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<MockedTestApp>{children}</MockedTestApp>
|
||||
</TestApp>
|
||||
),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
recentlyUsedModels: ['test-model']
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
|
||||
interface AISettingsProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -10,54 +13,51 @@ const DEFAULT_SETTINGS: AISettings = {
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'ai-settings';
|
||||
|
||||
function migrateOldSettings(stored: unknown): AISettings {
|
||||
// Handle migration from old single-provider format
|
||||
if (stored && typeof stored === 'object' && 'apiKey' in stored && 'baseUrl' in stored) {
|
||||
const oldSettings = stored as { apiKey?: string; baseUrl?: string };
|
||||
return {
|
||||
providers: {
|
||||
openrouter: {
|
||||
baseURL: oldSettings.baseUrl || 'https://openrouter.ai/api/v1',
|
||||
apiKey: oldSettings.apiKey || '',
|
||||
},
|
||||
},
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
}
|
||||
// If it's already the new format or invalid, return as AISettings or default
|
||||
if (stored && typeof stored === 'object' && 'providers' in stored) {
|
||||
const settings = stored as Partial<AISettings>;
|
||||
return {
|
||||
providers: settings.providers || {},
|
||||
recentlyUsedModels: settings.recentlyUsedModels || [],
|
||||
};
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const [settings, setSettings] = useState<AISettings>(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
const migrated = migrateOldSettings(parsed);
|
||||
return { ...DEFAULT_SETTINGS, ...migrated };
|
||||
} catch {
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
const { fs } = useFS();
|
||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
}, [settings]);
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readAISettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize AI settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeAISettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save AI settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<AISettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
// If providers are being updated, invalidate the provider-models query
|
||||
if ('providers' in newSettings) {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
}
|
||||
};
|
||||
|
||||
const addProvider = (name: string, connection: AIConnection) => {
|
||||
@@ -68,6 +68,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
[name]: connection,
|
||||
},
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const removeProvider = (name: string) => {
|
||||
@@ -78,6 +79,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
providers: rest,
|
||||
};
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const updateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
@@ -91,6 +93,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
},
|
||||
},
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const addRecentlyUsedModel = (modelId: string) => {
|
||||
|
||||
@@ -27,14 +27,18 @@ import {
|
||||
GitBranch,
|
||||
Download,
|
||||
Trash2,
|
||||
Settings,
|
||||
GitMerge,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { AppSettingsDialog } from '@/components/AppSettingsDialog';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import JSZip from 'jszip';
|
||||
import git from 'isomorphic-git';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
@@ -64,12 +68,14 @@ export function ActionsMenu({
|
||||
onProjectDeleted
|
||||
}: ActionsMenuProps) {
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const git = useGit();
|
||||
const { fs } = useFS();
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
|
||||
@@ -151,7 +157,6 @@ export function ActionsMenu({
|
||||
try {
|
||||
// Get the current commit hash
|
||||
const commits = await git.log({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
depth: 1,
|
||||
});
|
||||
@@ -211,6 +216,15 @@ export function ActionsMenu({
|
||||
New Chat
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitMerge className="h-4 w-4" />
|
||||
Git Status
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitHistoryOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
@@ -220,6 +234,17 @@ export function ActionsMenu({
|
||||
Git History
|
||||
</DropdownMenuItem>
|
||||
|
||||
<AppSettingsDialog>
|
||||
<DropdownMenuItem
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
onSelect={(e) => e.preventDefault()}
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
</AppSettingsDialog>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={handleExportProject}
|
||||
disabled={isAnyLoading}
|
||||
@@ -307,6 +332,12 @@ export function ActionsMenu({
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Dialogs */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
|
||||
<GitHistoryDialog
|
||||
projectId={projectId}
|
||||
open={gitHistoryOpen}
|
||||
|
||||
@@ -27,14 +27,7 @@ export function AppLayout({
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(() => {
|
||||
// On mobile, always start hidden
|
||||
if (typeof window !== 'undefined' && window.innerWidth < 768) {
|
||||
return false;
|
||||
}
|
||||
// On desktop, we'll set the initial state after projects load
|
||||
return false; // Default to closed initially
|
||||
});
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
// Track if we've set the initial state based on projects
|
||||
const [hasSetInitialState, setHasSetInitialState] = useState(false);
|
||||
@@ -136,6 +129,8 @@ export function AppLayout({
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-screen sticky top-0"
|
||||
showCollapseButton={true}
|
||||
onCollapse={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -143,16 +138,16 @@ export function AppLayout({
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col bg-background">
|
||||
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
|
||||
{/* Toggle Button - positioned absolutely in top-left corner */}
|
||||
{showSidebar && (
|
||||
{/* Toggle Button - only show when sidebar is collapsed */}
|
||||
{showSidebar && !isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
|
||||
<Columns2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ interface AppProviderProps {
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
deployServer: z.string().min(1),
|
||||
});
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
@@ -88,11 +89,11 @@ function useApplyTheme(theme: Theme) {
|
||||
if (theme !== 'system') return;
|
||||
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
|
||||
const handleChange = () => {
|
||||
const root = window.document.documentElement;
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
|
||||
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
|
||||
root.classList.add(systemTheme);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings, Save } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface AppSettingsDialogProps {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [deployServer, setDeployServer] = useState(config.deployServer);
|
||||
|
||||
const handleSave = () => {
|
||||
// Validate deploy server
|
||||
if (!deployServer.trim()) {
|
||||
toast({
|
||||
title: "Invalid deploy server",
|
||||
description: "Deploy server cannot be empty.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove protocol if present
|
||||
const cleanDeployServer = deployServer.replace(/^https?:\/\//, '');
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
deployServer: cleanDeployServer,
|
||||
}));
|
||||
|
||||
toast({
|
||||
title: "Settings saved",
|
||||
description: "Your deployment settings have been updated.",
|
||||
});
|
||||
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
// Reset to current config
|
||||
setDeployServer(config.deployServer);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
Settings
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>App Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your application preferences and deployment settings.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Deployment</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deployServer">Deploy Server</Label>
|
||||
<Input
|
||||
id="deployServer"
|
||||
value={deployServer}
|
||||
onChange={(e) => setDeployServer(e.target.value)}
|
||||
placeholder="shakespeare.wtf"
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your projects will be deployed to subdomains of this server.
|
||||
Example: yourproject.{deployServer || 'shakespeare.wtf'}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitDialog } from './GitDialog';
|
||||
|
||||
// Mock the hooks
|
||||
const mockRefetch = vi.fn();
|
||||
const mockUseGitStatus = vi.fn();
|
||||
|
||||
const baseGitStatus = {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
totalCommits: 5,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
latestCommit: {
|
||||
oid: 'abc123def456',
|
||||
message: 'Initial commit',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: Date.now() / 1000,
|
||||
},
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: () => mockUseGitStatus(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: vi.fn(() => ({
|
||||
fs: {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: vi.fn(() => ({
|
||||
toast: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useGitSettings', () => ({
|
||||
useGitSettings: vi.fn(() => ({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('GitDialog', () => {
|
||||
beforeEach(() => {
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: baseGitStatus,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
});
|
||||
|
||||
it('renders git repository information', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Git Repository Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Repository Information')).toBeInTheDocument();
|
||||
expect(screen.getByText('main')).toBeInTheDocument();
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections
|
||||
});
|
||||
|
||||
it('shows sync status', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Up to date')).toBeInTheDocument();
|
||||
expect(screen.getByText('Pull')).toBeInTheDocument();
|
||||
expect(screen.getByText('Push')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows clean working directory when no changes', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Working directory is clean')).toBeInTheDocument();
|
||||
expect(screen.getByText('No uncommitted changes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('enables push button when there are commits ahead', () => {
|
||||
// Mock git status with commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 2,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows configured credentials status', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Authentication')).toBeInTheDocument();
|
||||
expect(screen.getByText('github.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('Configured')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,554 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import {
|
||||
GitBranch,
|
||||
Upload,
|
||||
Download,
|
||||
Loader2,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
Clock,
|
||||
FileIcon,
|
||||
Plus,
|
||||
Minus,
|
||||
Edit,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials';
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
children?: React.ReactNode;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) {
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [isPulling, setIsPulling] = useState(false);
|
||||
const [pushResult, setPushResult] = useState<string | null>(null);
|
||||
const [pullResult, setPullResult] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
const git = useGit();
|
||||
const { toast } = useToast();
|
||||
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Get credentials for the current repository
|
||||
const getCredentialsForCurrentRepo = () => {
|
||||
if (!gitStatus?.remotes.length) return null;
|
||||
const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin')
|
||||
return findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
};
|
||||
|
||||
const currentCredentials = getCredentialsForCurrentRepo();
|
||||
|
||||
const handlePush = async () => {
|
||||
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
|
||||
toast({
|
||||
title: "Cannot push",
|
||||
description: "Not a git repository or no current branch",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.remotes.length === 0) {
|
||||
toast({
|
||||
title: "Cannot push",
|
||||
description: "No remote repositories configured",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.ahead === 0) {
|
||||
toast({
|
||||
title: "Nothing to push",
|
||||
description: "No commits ahead of remote. Commit your changes first.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPushing(true);
|
||||
setPushResult(null);
|
||||
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Prepare authentication if credentials are available
|
||||
const authOptions = currentCredentials ? {
|
||||
onAuth: () => ({
|
||||
username: currentCredentials.username,
|
||||
password: currentCredentials.password
|
||||
}),
|
||||
} : {};
|
||||
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: remote.name,
|
||||
ref: gitStatus.currentBranch,
|
||||
...authOptions,
|
||||
});
|
||||
|
||||
setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`);
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPushResult(`❌ Push failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Push failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePull = async () => {
|
||||
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
|
||||
toast({
|
||||
title: "Cannot pull",
|
||||
description: "Not a git repository or no current branch",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.remotes.length === 0) {
|
||||
toast({
|
||||
title: "Cannot pull",
|
||||
description: "No remote repositories configured",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPulling(true);
|
||||
setPullResult(null);
|
||||
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Prepare authentication if credentials are available
|
||||
const authOptions = currentCredentials ? {
|
||||
onAuth: () => ({
|
||||
username: currentCredentials.username,
|
||||
password: currentCredentials.password
|
||||
}),
|
||||
} : {};
|
||||
|
||||
await git.pull({
|
||||
dir: projectPath,
|
||||
ref: gitStatus.currentBranch,
|
||||
singleBranch: true,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
...authOptions,
|
||||
});
|
||||
|
||||
setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`);
|
||||
toast({
|
||||
title: "Pull successful",
|
||||
description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after pull
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPullResult(`❌ Pull failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Pull failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsPulling(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRefresh = async () => {
|
||||
await refetchGitStatus();
|
||||
setPushResult(null);
|
||||
setPullResult(null);
|
||||
};
|
||||
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
return <Plus className="h-3 w-3 text-green-500" />;
|
||||
case 'deleted':
|
||||
return <Minus className="h-3 w-3 text-red-500" />;
|
||||
case 'modified':
|
||||
return <Edit className="h-3 w-3 text-blue-500" />;
|
||||
case 'staged':
|
||||
return <CheckCircle className="h-3 w-3 text-green-600" />;
|
||||
case 'untracked':
|
||||
return <FileIcon className="h-3 w-3 text-gray-500" />;
|
||||
default:
|
||||
return <FileIcon className="h-3 w-3" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getFileStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
return 'bg-green-100 text-green-800 border-green-200';
|
||||
case 'deleted':
|
||||
return 'bg-red-100 text-red-800 border-red-200';
|
||||
case 'modified':
|
||||
return 'bg-blue-100 text-blue-800 border-blue-200';
|
||||
case 'staged':
|
||||
return 'bg-green-100 text-green-800 border-green-200';
|
||||
case 'untracked':
|
||||
return 'bg-gray-100 text-gray-800 border-gray-200';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-800 border-gray-200';
|
||||
}
|
||||
};
|
||||
|
||||
const getSyncStatus = () => {
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return { status: 'not-repo', text: 'Not a Git repository', icon: AlertCircle, color: 'text-gray-500' };
|
||||
}
|
||||
|
||||
if (gitStatus.remotes.length === 0) {
|
||||
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
|
||||
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0) {
|
||||
return { status: 'ahead', text: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead`, icon: Upload, color: 'text-blue-600' };
|
||||
}
|
||||
|
||||
// Show uncommitted changes but with different styling since they can't be pushed directly
|
||||
if (gitStatus.hasUncommittedChanges) {
|
||||
return { status: 'uncommitted', text: `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`, icon: Clock, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.behind > 0) {
|
||||
return { status: 'behind', text: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind`, icon: Download, color: 'text-orange-600' };
|
||||
}
|
||||
|
||||
return { status: 'synced', text: 'Up to date', icon: CheckCircle, color: 'text-green-600' };
|
||||
};
|
||||
|
||||
const syncStatus = getSyncStatus();
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-2xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Git Repository Status
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
View repository status and sync with remote repositories
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-4">
|
||||
{/* Repository Info */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm flex items-center justify-between">
|
||||
Repository Information
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleRefresh}
|
||||
className="h-7 w-7 p-0"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{gitStatus?.isGitRepo ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Current Branch:</span>
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{gitStatus.currentBranch || 'unknown'}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total Commits:</span>
|
||||
<Badge variant="secondary">{gitStatus.totalCommits}</Badge>
|
||||
</div>
|
||||
|
||||
{gitStatus.latestCommit && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm text-muted-foreground">Latest Commit:</span>
|
||||
<div className="bg-muted/50 rounded-md p-2 space-y-1">
|
||||
<div className="font-mono text-xs text-muted-foreground">
|
||||
{gitStatus.latestCommit.oid.substring(0, 7)}
|
||||
</div>
|
||||
<div className="text-sm">{gitStatus.latestCommit.message}</div>
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm text-muted-foreground">Remotes:</span>
|
||||
{gitStatus.remotes.map((remote) => (
|
||||
<div key={remote.name} className="bg-muted/50 rounded-md p-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Badge variant="outline">{remote.name}</Badge>
|
||||
<span className="font-mono text-xs text-muted-foreground truncate ml-2">
|
||||
{remote.url}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-4 text-muted-foreground">
|
||||
<AlertCircle className="h-8 w-8 mx-auto mb-2" />
|
||||
<p>Not a Git repository</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Credentials Status */}
|
||||
{gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm flex items-center justify-between">
|
||||
Authentication
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="h-7 gap-1 text-xs"
|
||||
>
|
||||
<Settings className="h-3 w-3" />
|
||||
Settings
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Credentials for push/pull operations
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{gitStatus.remotes.map((remote) => {
|
||||
const credentials = findCredentialsForRepo(remote.url, settings.credentials);
|
||||
const originDisplayName = getOriginDisplayName(remote.url);
|
||||
|
||||
return (
|
||||
<div key={remote.name} className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">{remote.name}</Badge>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{originDisplayName}
|
||||
</span>
|
||||
</div>
|
||||
{credentials ? (
|
||||
<div className="flex items-center gap-1 text-green-600">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
<span className="text-xs">Configured</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1 text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs">No credentials</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!credentials && (
|
||||
<Alert className="border-amber-200 bg-amber-50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
No credentials configured for {originDisplayName}.
|
||||
Push/pull operations may fail for private repositories.{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="underline hover:no-underline font-medium"
|
||||
>
|
||||
Configure credentials
|
||||
</button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Sync Status */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Sync Status</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPulling ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPulling ? 'Pulling...' : 'Pull'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || gitStatus.ahead === 0}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushing ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Operation Results */}
|
||||
{(pushResult || pullResult) && (
|
||||
<div className="mt-3 space-y-2">
|
||||
{pushResult && (
|
||||
<div className="text-xs font-mono bg-muted/50 rounded p-2">
|
||||
{pushResult}
|
||||
</div>
|
||||
)}
|
||||
{pullResult && (
|
||||
<div className="text-xs font-mono bg-muted/50 rounded p-2">
|
||||
{pullResult}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Working Directory Changes */}
|
||||
{gitStatus?.isGitRepo && gitStatus.changedFiles.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Working Directory Changes</CardTitle>
|
||||
<CardDescription>
|
||||
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{gitStatus.changedFiles.map((file, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="font-mono text-sm flex-1 truncate">
|
||||
{file.filepath}
|
||||
</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn("text-xs", getFileStatusColor(file.status))}
|
||||
>
|
||||
{file.status}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Clean Working Directory */}
|
||||
{gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-6">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
|
||||
<p>Working directory is clean</p>
|
||||
<p className="text-xs">No uncommitted changes</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { GitSettingsProvider } from './GitSettingsProvider';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the config utils
|
||||
vi.mock('@/lib/configUtils', () => ({
|
||||
readGitSettings: vi.fn(),
|
||||
writeGitSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
// Test component that uses the hook
|
||||
function TestComponent() {
|
||||
const { settings, updateSettings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
|
||||
|
||||
const handleAdd = () => {
|
||||
const credential: GitCredential = {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
};
|
||||
addCredential('https://github.com', credential);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
updateCredential('https://github.com', { password: 'updated-token' });
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
removeCredential('https://github.com');
|
||||
};
|
||||
|
||||
const handleUpdateCorsProxy = () => {
|
||||
updateSettings({ corsProxy: 'https://custom-cors.example.com' });
|
||||
};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
|
||||
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
|
||||
<div data-testid="cors-proxy">{settings.corsProxy}</div>
|
||||
<button onClick={handleAdd}>Add GitHub</button>
|
||||
<button onClick={handleUpdate}>Update GitHub</button>
|
||||
<button onClick={handleRemove}>Remove GitHub</button>
|
||||
<button onClick={handleUpdateCorsProxy}>Update CORS Proxy</button>
|
||||
{settings.credentials['https://github.com'] && (
|
||||
<div data-testid="github-creds">
|
||||
{settings.credentials['https://github.com'].username}:
|
||||
{settings.credentials['https://github.com'].password}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TestWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<TestApp>
|
||||
<GitSettingsProvider>
|
||||
{children}
|
||||
</GitSettingsProvider>
|
||||
</TestApp>
|
||||
);
|
||||
}
|
||||
|
||||
describe('GitSettingsProvider', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
|
||||
// Mock the read function to return default settings
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
});
|
||||
});
|
||||
|
||||
it('provides initial empty state', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0');
|
||||
});
|
||||
});
|
||||
|
||||
it('can add credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
|
||||
});
|
||||
|
||||
it('can update credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
// First add a credential
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
|
||||
|
||||
// Then update it
|
||||
fireEvent.click(screen.getByText('Update GitHub'));
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:updated-token');
|
||||
});
|
||||
|
||||
it('can remove credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
// First add a credential
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
|
||||
// Then remove it
|
||||
fireEvent.click(screen.getByText('Remove GitHub'));
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0');
|
||||
});
|
||||
|
||||
it('persists settings to VFS', async () => {
|
||||
const { writeGitSettings } = await import('@/lib/configUtils');
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
|
||||
// Check that settings were saved to VFS
|
||||
await waitFor(() => {
|
||||
expect(writeGitSettings).toHaveBeenCalledWith(
|
||||
expect.anything(), // fs instance
|
||||
expect.objectContaining({
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
}
|
||||
},
|
||||
corsProxy: 'https://cors.isomorphic-git.org'
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('loads settings from VFS', async () => {
|
||||
const settings = {
|
||||
credentials: {
|
||||
'https://gitlab.com': {
|
||||
username: 'git',
|
||||
password: 'gitlab-token',
|
||||
},
|
||||
},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
};
|
||||
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue(settings);
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
|
||||
});
|
||||
});
|
||||
|
||||
it('provides default CORS proxy', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
|
||||
});
|
||||
});
|
||||
|
||||
it('can update CORS proxy', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Update CORS Proxy'));
|
||||
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
|
||||
interface GitSettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const [settings, setSettings] = useState<GitSettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readGitSettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Git settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeGitSettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save Git settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<GitSettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
};
|
||||
|
||||
const addCredential = (origin: string, credential: GitCredential) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: credential,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeCredential = (origin: string) => {
|
||||
setSettings(prev => {
|
||||
const { [origin]: removed, ...rest } = prev.credentials;
|
||||
return {
|
||||
...prev,
|
||||
credentials: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: {
|
||||
...prev.credentials[origin],
|
||||
...credential,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.credentials).length > 0;
|
||||
|
||||
const contextValue: GitSettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addCredential,
|
||||
removeCredential,
|
||||
updateCredential,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
return (
|
||||
<GitSettingsContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</GitSettingsContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
|
||||
import type { JSRuntime } from '@/lib/JSRuntime';
|
||||
|
||||
interface JSRuntimeProviderProps {
|
||||
children: ReactNode;
|
||||
runtime: JSRuntime;
|
||||
}
|
||||
|
||||
export function JSRuntimeProvider({ children, runtime }: JSRuntimeProviderProps) {
|
||||
const contextValue: JSRuntimeContextType = { runtime };
|
||||
|
||||
return (
|
||||
<JSRuntimeContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</JSRuntimeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -8,7 +9,6 @@ import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { AISettingsDialog } from '@/components/ai/AISettingsDialog';
|
||||
|
||||
interface ModelSelectorProps {
|
||||
value: string;
|
||||
@@ -28,9 +28,9 @@ export function ModelSelector({
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isCustomInput, setIsCustomInput] = useState(false);
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
|
||||
const { models, isLoading, error, refetch } = useProviderModels();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
|
||||
|
||||
@@ -58,7 +58,7 @@ export function ModelSelector({
|
||||
}
|
||||
|
||||
if (selectedValue === '__manage_providers__') {
|
||||
setSettingsOpen(true);
|
||||
navigate('/settings/ai');
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
@@ -112,19 +112,14 @@ export function ModelSelector({
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AISettingsDialog
|
||||
open={settingsOpen}
|
||||
onOpenChange={setSettingsOpen}
|
||||
/>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
|
||||
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
|
||||
className
|
||||
)}
|
||||
disabled={disabled}
|
||||
@@ -132,10 +127,10 @@ export function ModelSelector({
|
||||
<span className="w-full truncate">
|
||||
{value || placeholder}
|
||||
</span>
|
||||
<ChevronDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80 p-0" align="end">
|
||||
<PopoverContent className="w-96 p-0" align="end">
|
||||
<Command>
|
||||
{isConfigured && <CommandInput placeholder="Search models..." className="h-9" />}
|
||||
<CommandList className="max-h-[300px]">
|
||||
@@ -257,6 +252,5 @@ export function ModelSelector({
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +1,25 @@
|
||||
import React, { useState, memo } from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Folder, Download, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star, Columns2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
import { AISettingsDialog } from '@/components/ai/AISettingsDialog';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
isSelected: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
isFavorite?: boolean;
|
||||
}
|
||||
|
||||
const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) => {
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
|
||||
@@ -38,7 +35,7 @@ const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) =
|
||||
isSelected && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
|
||||
)}
|
||||
>
|
||||
<div className="w-full p-3 text-left text-sidebar-foreground">
|
||||
<div className="w-full px-3 py-2 text-left text-sidebar-foreground">
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="absolute inset-0"
|
||||
@@ -51,28 +48,27 @@ const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) =
|
||||
<Folder className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="font-medium text-sm truncate mb-1">
|
||||
<div className="flex justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1 flex items-center">
|
||||
<h3 className="font-medium text-sm truncate">
|
||||
{project.name}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Star Button */}
|
||||
<div className="flex-shrink-0 -mt-1 -mr-1 relative">
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
showToast={false}
|
||||
className="h-6 w-6 hover:bg-primary/20"
|
||||
/>
|
||||
</div>
|
||||
{/* Star indicator - only shown when favorited */}
|
||||
{isFavorite && (
|
||||
<div className="flex-shrink-0 relative -mr-1 pointer-events-none">
|
||||
<div className="flex items-center justify-center">
|
||||
<Star className="h-4 w-4 text-yellow-500 fill-current" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
ProjectItem.displayName = 'ProjectItem';
|
||||
|
||||
@@ -80,133 +76,35 @@ interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
onSelectProject: (project: Project | null) => void;
|
||||
className?: string;
|
||||
showCollapseButton?: boolean;
|
||||
onCollapse?: () => void;
|
||||
}
|
||||
|
||||
export function ProjectSidebar({
|
||||
selectedProject,
|
||||
onSelectProject,
|
||||
className
|
||||
className,
|
||||
showCollapseButton = false,
|
||||
onCollapse
|
||||
}: ProjectSidebarProps) {
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [aiSettingsOpen, setAISettingsOpen] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
|
||||
// Load projects on mount
|
||||
React.useEffect(() => {
|
||||
const loadProjects = async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
setProjects(projectList);
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadProjects();
|
||||
}, [projectsManager]);
|
||||
|
||||
const handleNewProject = () => {
|
||||
onSelectProject(null);
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
const isFavorite = (projectId: string) => favorites.includes(projectId);
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
}, [favorites, queryClient]);
|
||||
|
||||
const exportFilesAsZip = async (projectName: string) => {
|
||||
const zip = new JSZip();
|
||||
|
||||
// Recursive function to add files and directories to zip
|
||||
const addToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = dirPath === '/' ? `/${entry.name}` : `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zipFolder.folder(entry.name);
|
||||
if (folder) {
|
||||
await addToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await fs.readFile(fullPath);
|
||||
zipFolder.file(entry.name, fileContent);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read file ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read directory ${dirPath}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start from root directory
|
||||
await addToZip('/', zip);
|
||||
|
||||
// Generate zip file
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create download link
|
||||
const url = URL.createObjectURL(content);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
|
||||
// Generate filename with date
|
||||
const now = new Date();
|
||||
const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD format
|
||||
link.download = `${projectName}-${dateStr}.zip`;
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const handleExportFiles = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const projectName = selectedProject?.name || 'shakespeare';
|
||||
await exportFilesAsZip(projectName);
|
||||
|
||||
toast({
|
||||
title: "Files exported successfully",
|
||||
description: "Your project files have been downloaded as a zip file.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export files:', error);
|
||||
toast({
|
||||
title: "Failed to export files",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Sort projects: favorites first, then by lastModified (newest first)
|
||||
const sortedProjects = projects.sort((a, b) => {
|
||||
const aIsFavorite = isFavorite(a.id);
|
||||
const bIsFavorite = isFavorite(b.id);
|
||||
|
||||
if (aIsFavorite && !bIsFavorite) return -1;
|
||||
if (!aIsFavorite && bIsFavorite) return 1;
|
||||
|
||||
return b.lastModified.getTime() - a.lastModified.getTime();
|
||||
});
|
||||
if (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
|
||||
@@ -223,38 +121,26 @@ export function ProjectSidebar({
|
||||
</h1>
|
||||
</button>
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 hover:bg-primary/10">
|
||||
<MoreVertical className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
{/* Collapse button - shown when showCollapseButton is true */}
|
||||
{showCollapseButton && onCollapse && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10"
|
||||
onClick={onCollapse}
|
||||
aria-label="Collapse sidebar"
|
||||
>
|
||||
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate('/clone')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Import Repository
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={handleExportFiles}
|
||||
disabled={isExporting}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{isExporting ? 'Exporting...' : 'Export Files'}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setAISettingsOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
AI Settings
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={() => navigate('/settings')}
|
||||
>
|
||||
<Settings className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -262,14 +148,34 @@ export function ProjectSidebar({
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="p-2">
|
||||
<div className="mb-2">
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90"
|
||||
onClick={handleNewProject}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Project
|
||||
</Button>
|
||||
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
|
||||
<div className="flex">
|
||||
<button
|
||||
onClick={handleNewProject}
|
||||
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Project
|
||||
</button>
|
||||
<div className="w-px bg-white/20" />
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate('/clone')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Import Repository
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
@@ -291,14 +197,15 @@ export function ProjectSidebar({
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{sortedProjects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
/>
|
||||
))}
|
||||
{projects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -308,12 +215,6 @@ export function ProjectSidebar({
|
||||
<div className="p-4 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
|
||||
<LoginArea className="w-full" />
|
||||
</div>
|
||||
|
||||
{/* AI Settings Dialog */}
|
||||
<AISettingsDialog
|
||||
open={aiSettingsOpen}
|
||||
onOpenChange={setAISettingsOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -14,10 +16,14 @@ interface SessionManagerProviderProps {
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
return new SessionManager(fs, settings);
|
||||
}, [fs, settings]);
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => user;
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
|
||||
}, [fs, settings, models, user]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -15,13 +15,13 @@ export function SessionMonitor() {
|
||||
const previousLoadingStates = useRef<Map<string, boolean>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
const handleLoadingChanged = (sessionId: string, isLoading: boolean) => {
|
||||
const wasLoading = previousLoadingStates.current.get(sessionId);
|
||||
previousLoadingStates.current.set(sessionId, isLoading);
|
||||
const handleLoadingChanged = (projectId: string, isLoading: boolean) => {
|
||||
const wasLoading = previousLoadingStates.current.get(projectId);
|
||||
previousLoadingStates.current.set(projectId, isLoading);
|
||||
|
||||
// If session just finished loading (was loading, now not loading)
|
||||
if (wasLoading && !isLoading) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
const session = sessionManager.getSession(projectId);
|
||||
if (!session) return;
|
||||
|
||||
// Check if user is currently viewing this project
|
||||
@@ -32,7 +32,7 @@ export function SessionMonitor() {
|
||||
if (!isCurrentProject) {
|
||||
toast({
|
||||
title: "AI Session Complete",
|
||||
description: `Finished working on ${session.projectName}`,
|
||||
description: `Finished working on ${session.projectId}`,
|
||||
action: (
|
||||
<button
|
||||
onClick={() => navigate(`/project/${session.projectId}`)}
|
||||
@@ -46,20 +46,20 @@ export function SessionMonitor() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleSessionCreated = (sessionId: string) => {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
const handleSessionCreated = (projectId: string) => {
|
||||
const session = sessionManager.getSession(projectId);
|
||||
if (session) {
|
||||
previousLoadingStates.current.set(sessionId, session.isLoading);
|
||||
previousLoadingStates.current.set(projectId, session.isLoading);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSessionDeleted = (sessionId: string) => {
|
||||
previousLoadingStates.current.delete(sessionId);
|
||||
const handleSessionDeleted = (projectId: string) => {
|
||||
previousLoadingStates.current.delete(projectId);
|
||||
};
|
||||
|
||||
// Initialize with current sessions
|
||||
sessionManager.getAllSessions().forEach(session => {
|
||||
previousLoadingStates.current.set(session.id, session.isLoading);
|
||||
previousLoadingStates.current.set(session.projectId, session.isLoading);
|
||||
});
|
||||
|
||||
// Subscribe to events
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Columns2, Bot, GitBranch, Database } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useCallback } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsItem {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
href: string;
|
||||
}
|
||||
|
||||
const settingsItems: SettingsItem[] = [
|
||||
{
|
||||
id: 'ai',
|
||||
title: 'AI Settings',
|
||||
description: 'Configure AI providers and API keys',
|
||||
icon: Bot,
|
||||
href: '/settings/ai',
|
||||
},
|
||||
{
|
||||
id: 'git',
|
||||
title: 'Git Settings',
|
||||
description: 'Configure Git credentials for HTTP authentication',
|
||||
icon: GitBranch,
|
||||
href: '/settings/git',
|
||||
},
|
||||
{
|
||||
id: 'data',
|
||||
title: 'Data',
|
||||
description: 'Export files and manage local data',
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
];
|
||||
|
||||
export function SettingsLayout() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const [_projects, setProjects] = useState<Project[]>([]);
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
const [hasSetInitialState, setHasSetInitialState] = useState(false);
|
||||
|
||||
const loadProjects = useCallback(async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
setProjects(projectList);
|
||||
|
||||
// Set initial sidebar state based on projects and device type
|
||||
if (!hasSetInitialState && !isMobile) {
|
||||
// On desktop, show sidebar if there are projects
|
||||
setIsSidebarVisible(projectList.length > 0);
|
||||
setHasSetInitialState(true);
|
||||
} else if (!hasSetInitialState && isMobile) {
|
||||
// On mobile, always start hidden
|
||||
setIsSidebarVisible(false);
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
if (!hasSetInitialState) {
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
}
|
||||
}, [projectsManager, hasSetInitialState, isMobile]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects();
|
||||
}, [loadProjects]);
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
if (project) {
|
||||
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
|
||||
navigate(`/project/${project.id}`);
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
// Get current settings page
|
||||
const currentPath = location.pathname;
|
||||
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-white">
|
||||
{/* Mobile Header */}
|
||||
<header className="h-12 border-b bg-white px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-lg font-semibold">Settings</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Mobile Sidebar Overlay */}
|
||||
{isSidebarVisible && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={(project) => {
|
||||
setIsSidebarVisible(false);
|
||||
handleProjectSelect(project);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop 3-column layout
|
||||
return (
|
||||
<div className="h-screen flex bg-white overflow-hidden">
|
||||
{/* Left Column - Projects Sidebar (optionally hidden) */}
|
||||
{isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar flex-shrink-0">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Middle Column - Settings Navigation */}
|
||||
<div className="w-96 border-r bg-white flex flex-col flex-shrink-0">
|
||||
{/* Header with toggle button */}
|
||||
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
|
||||
</Button>
|
||||
<h1 className="text-xl font-bold flex items-center gap-2">
|
||||
Settings
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Settings Navigation - Scrollable */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-4">
|
||||
<div className="space-y-2">
|
||||
{settingsItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = currentSettingsId === item.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => navigate(item.href)}
|
||||
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
|
||||
'bg-primary/10 border border-primary/20': isActive,
|
||||
'hover:bg-muted/50': !isActive,
|
||||
})}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
|
||||
{item.title}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-0.5">
|
||||
{item.description}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Right Column - Settings Content - Scrollable */}
|
||||
<ScrollArea className="flex-1 bg-white">
|
||||
<div className="max-w-4xl">
|
||||
<Outlet />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { ChatPane } from './ChatPane';
|
||||
|
||||
// Mock the AI settings hook to return configured state
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
isConfigured: true,
|
||||
settings: {
|
||||
recentlyUsedModels: ['gpt-4'],
|
||||
},
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock other hooks
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: () => ({
|
||||
fs: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useCurrentUser', () => ({
|
||||
useCurrentUser: () => ({
|
||||
user: null,
|
||||
metadata: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useKeepAlive', () => ({
|
||||
useKeepAlive: () => ({
|
||||
updateMetadata: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useAIChat', () => ({
|
||||
useAIChat: () => ({
|
||||
messages: [],
|
||||
streamingMessage: null,
|
||||
isLoading: false,
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
sendMessage: vi.fn(),
|
||||
startGeneration: vi.fn(),
|
||||
stopGeneration: vi.fn(),
|
||||
startNewSession: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useProviderModels', () => ({
|
||||
useProviderModels: () => ({
|
||||
models: [
|
||||
{
|
||||
fullId: 'gpt-4',
|
||||
contextLength: 8192,
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('ChatPane', () => {
|
||||
it('handles image paste from clipboard', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
|
||||
expect(textarea).toBeInTheDocument();
|
||||
|
||||
// Create a mock image file
|
||||
const imageFile = new File(['fake-image-data'], 'test.png', {
|
||||
type: 'image/png',
|
||||
});
|
||||
|
||||
// Create mock clipboard data
|
||||
const mockClipboardItem = {
|
||||
type: 'image/png',
|
||||
getAsFile: () => imageFile,
|
||||
} as DataTransferItem;
|
||||
|
||||
const mockClipboardData = {
|
||||
items: [mockClipboardItem],
|
||||
length: 1,
|
||||
} as unknown as DataTransfer;
|
||||
|
||||
// Fire the paste event on the textarea using fireEvent
|
||||
fireEvent.paste(textarea, {
|
||||
clipboardData: mockClipboardData,
|
||||
});
|
||||
|
||||
// The file should be added to the attached files
|
||||
// We can't easily test the internal state, but we can verify the event was handled
|
||||
// without throwing an error
|
||||
expect(textarea).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders welcome message when no messages exist', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,20 @@
|
||||
import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo } from 'react';
|
||||
import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Send, Square, Loader2 } from 'lucide-react';
|
||||
import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
|
||||
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
@@ -22,6 +22,7 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
|
||||
import { DeployProjectTool } from '@/lib/tools/DeployProjectTool';
|
||||
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
|
||||
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
|
||||
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
|
||||
@@ -29,15 +30,18 @@ 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 { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { Git } from '@/lib/git';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { makeSystemPrompt } from '@/lib/system';
|
||||
import { assistantContentEmpty } from '@/lib/ai-messages';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
|
||||
interface ChatPaneProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onNewChat?: () => void;
|
||||
onBuild?: () => void;
|
||||
onDeploy?: () => void;
|
||||
@@ -54,7 +58,6 @@ export interface ChatPaneRef {
|
||||
|
||||
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
projectId,
|
||||
projectName,
|
||||
onNewChat: _onNewChat,
|
||||
onBuild: _onBuild,
|
||||
onDeploy: _onDeploy,
|
||||
@@ -66,6 +69,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}, ref) => {
|
||||
const [input, setInput] = useState('');
|
||||
const [systemPrompt, setSystemPrompt] = useState('');
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
@@ -77,27 +83,50 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
setProviderModel(settings.recentlyUsedModels[0]);
|
||||
}
|
||||
}, [providerModel, settings.recentlyUsedModels]);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs: browserFS } = useFS();
|
||||
const { fs } = useFS();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const customTools = useMemo(() => ({
|
||||
git_commit: new GitCommitTool(browserFS, cwd),
|
||||
text_editor_view: new TextEditorViewTool(browserFS, cwd),
|
||||
text_editor_write: new TextEditorWriteTool(browserFS, cwd),
|
||||
text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd),
|
||||
npm_add_package: new NpmAddPackageTool(browserFS, cwd),
|
||||
npm_remove_package: new NpmRemovePackageTool(browserFS, cwd),
|
||||
build_project: new BuildProjectTool(browserFS, cwd),
|
||||
nostr_read_nip: new NostrReadNipTool(),
|
||||
nostr_fetch_event: new NostrFetchEventTool(),
|
||||
nostr_read_kind: new NostrReadKindTool(),
|
||||
nostr_read_tag: new NostrReadTagTool(),
|
||||
nostr_read_protocol: new NostrReadProtocolTool(),
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
}), [browserFS, cwd]);
|
||||
const customTools = useMemo(() => {
|
||||
const git = new Git(fs);
|
||||
const baseTools = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
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),
|
||||
typecheck: new TypecheckTool(fs, cwd),
|
||||
nostr_read_nip: new NostrReadNipTool(),
|
||||
nostr_fetch_event: new NostrFetchEventTool(),
|
||||
nostr_read_kind: new NostrReadKindTool(),
|
||||
nostr_read_tag: new NostrReadTagTool(),
|
||||
nostr_read_protocol: new NostrReadProtocolTool(),
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
if (user && user.signer) {
|
||||
return {
|
||||
...baseTools,
|
||||
deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId),
|
||||
};
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, cwd, user, projectId]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
@@ -108,39 +137,70 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
return result;
|
||||
}, [customTools]);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: externalIsLoading || isBuildLoading || isDeployLoading,
|
||||
title: 'Shakespeare',
|
||||
artist: `Working on ${projectId}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// Memoize the metadata update callback to avoid unnecessary re-renders
|
||||
const onUpdateMetadata = useCallback((title: string, description: string) => {
|
||||
updateMetadata(title, description);
|
||||
}, [updateMetadata]);
|
||||
|
||||
useEffect(() => {
|
||||
makeSystemPrompt({
|
||||
cwd,
|
||||
fs: browserFS,
|
||||
fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(tools),
|
||||
user,
|
||||
metadata,
|
||||
}).then(setSystemPrompt)
|
||||
}, [browserFS, cwd, tools]);
|
||||
}, [fs, cwd, tools, user, metadata]);
|
||||
|
||||
const {
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
startNewSession: internalStartNewSession,
|
||||
} = useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
onUpdateMetadata: (title, description) => {
|
||||
updateMetadata(title, description);
|
||||
}
|
||||
onUpdateMetadata,
|
||||
});
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
// Calculate context usage percentage
|
||||
const currentModel = useMemo(() => {
|
||||
if (!providerModel.trim()) return null;
|
||||
return models.find(model => model.fullId === providerModel.trim());
|
||||
}, [models, providerModel]);
|
||||
|
||||
const contextUsagePercentage = useMemo(() => {
|
||||
if (!currentModel?.contextLength || !lastInputTokens) return 0;
|
||||
return Math.min((lastInputTokens / currentModel.contextLength) * 100, 100);
|
||||
}, [currentModel, lastInputTokens]);
|
||||
|
||||
// Notify parent of loading state changes
|
||||
useEffect(() => {
|
||||
if (onLoadingChange) {
|
||||
@@ -153,49 +213,59 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const autostart = searchParams.get('autostart');
|
||||
const urlModel = searchParams.get('model');
|
||||
|
||||
if (autostart === 'true' && isConfigured && messages.length > 0 && !isLoading) {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
if (autostart === 'true' && isConfigured) {
|
||||
// Use model from URL if available, otherwise use current selection
|
||||
const modelToUse = urlModel?.trim() || providerModel.trim();
|
||||
|
||||
// If the last message is from the user, auto-start the AI
|
||||
if (lastMessage.role === 'user') {
|
||||
// Use model from URL if available, otherwise use current selection
|
||||
const modelToUse = urlModel?.trim() || providerModel.trim();
|
||||
|
||||
if (modelToUse) {
|
||||
// Update provider model if it came from URL
|
||||
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
|
||||
setProviderModel(urlModel.trim());
|
||||
}
|
||||
|
||||
// Clear the autostart and model parameters so they don't trigger again
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('autostart');
|
||||
newSearchParams.delete('model');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
startGeneration(modelToUse);
|
||||
if (modelToUse) {
|
||||
// Update provider model if it came from URL
|
||||
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
|
||||
setProviderModel(urlModel.trim());
|
||||
}
|
||||
|
||||
// Clear the autostart and model parameters so they don't trigger again
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('autostart');
|
||||
newSearchParams.delete('model');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
startGeneration(modelToUse);
|
||||
}
|
||||
}
|
||||
}, [searchParams, setSearchParams, isConfigured, messages, isLoading, startGeneration, providerModel, setProviderModel, addRecentlyUsedModel]);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: isLoading || isBuildLoading || isDeployLoading,
|
||||
title: 'Shakespeare',
|
||||
artist: `Working on ${projectName}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
]
|
||||
});
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
|
||||
|
||||
|
||||
// Function to scroll to bottom
|
||||
const scrollToBottom = () => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
}
|
||||
};
|
||||
|
||||
// Simple scroll event listener
|
||||
useEffect(() => {
|
||||
const container = scrollAreaRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const handleScroll = () => {
|
||||
const threshold = 100;
|
||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||
const hasScrollableContent = container.scrollHeight > container.clientHeight;
|
||||
|
||||
setShowScrollToBottom(!isNearBottom && hasScrollableContent);
|
||||
};
|
||||
|
||||
container.addEventListener('scroll', handleScroll);
|
||||
|
||||
// Check immediately
|
||||
handleScroll();
|
||||
|
||||
return () => {
|
||||
container.removeEventListener('scroll', handleScroll);
|
||||
};
|
||||
}, [messages]); // Re-run when messages change to ensure proper setup
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
||||
@@ -208,20 +278,91 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
if (isNearBottom) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
|
||||
}
|
||||
}, [messages, streamingMessage, isLoading]);
|
||||
|
||||
// Scroll to bottom when first visiting a project (including page refresh)
|
||||
useEffect(() => {
|
||||
if (projectId && !scrolledProjects.has(projectId)) {
|
||||
// Small delay to ensure messages have loaded
|
||||
const timer = setTimeout(() => {
|
||||
scrollToBottom();
|
||||
scrolledProjects.add(projectId);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [projectId, scrolledProjects]);
|
||||
|
||||
// Also scroll on initial mount if we have a projectId
|
||||
useEffect(() => {
|
||||
if (projectId && !scrolledProjects.has(projectId)) {
|
||||
const timer = setTimeout(() => {
|
||||
scrollToBottom();
|
||||
scrolledProjects.add(projectId);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, []); // Empty dependency array = runs on mount
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
setAttachedFiles(prev => [...prev, file]);
|
||||
};
|
||||
|
||||
const handleFileRemove = (fileToRemove: File) => {
|
||||
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
|
||||
};
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim() || isLoading || !providerModel.trim()) return;
|
||||
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
|
||||
|
||||
const messageContent = input;
|
||||
const modelToUse = providerModel.trim();
|
||||
|
||||
// Build message content as text parts
|
||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
||||
|
||||
// Add user input as text part if present
|
||||
if (input.trim()) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: input.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files and add as separate text parts
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
const savedPath = await saveFileToTmp(fs, file);
|
||||
return `Added file: ${savedPath}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
return `Failed to save file: ${file.name}`;
|
||||
}
|
||||
});
|
||||
|
||||
const fileResults = await Promise.all(filePromises);
|
||||
|
||||
// Add each file as a separate text part
|
||||
fileResults.forEach(fileResult => {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: fileResult
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
setInput('');
|
||||
setAttachedFiles([]);
|
||||
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
try {
|
||||
// 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);
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
@@ -236,6 +377,35 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = async (e: React.ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
|
||||
// Check if the item is an image
|
||||
if (item.type.startsWith('image/')) {
|
||||
e.preventDefault(); // Prevent default paste behavior for images
|
||||
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
// Generate a filename with timestamp
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const extension = file.type.split('/')[1] || 'png';
|
||||
const filename = `pasted-image-${timestamp}.${extension}`;
|
||||
|
||||
// Create a new File object with the generated name
|
||||
const namedFile = new File([file], filename, { type: file.type });
|
||||
|
||||
// Add to attached files
|
||||
setAttachedFiles(prev => [...prev, namedFile]);
|
||||
}
|
||||
break; // Only handle the first image found
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle first user interaction to enable audio context
|
||||
const handleFirstInteraction = () => {
|
||||
// This will be handled automatically by the useKeepAlive hook
|
||||
@@ -276,10 +446,33 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="h-full flex flex-col relative">
|
||||
|
||||
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Empty state when no messages and not loading */}
|
||||
{messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="text-6xl mb-6">🎭</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Welcome to Shakespeare
|
||||
</h3>
|
||||
<p className="text-muted-foreground mb-6 leading-relaxed">
|
||||
Your AI-powered development assistant is ready to help you build, edit, and enhance your project.
|
||||
</p>
|
||||
<div className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>💡 Ask me to add new features</p>
|
||||
<p>📝 Request file edits and improvements</p>
|
||||
<p>🔧 Get help with debugging and optimization</p>
|
||||
<p>🚀 Build and deploy your project</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages.map((message, index) => {
|
||||
// Skip assistant messages with no content
|
||||
if (message.role === 'assistant' && assistantContentEmpty(message.content)) {
|
||||
@@ -311,18 +504,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
streamingMessage.content ? (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage as AIMessage}
|
||||
isCurrentlyLoading
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
/>
|
||||
) : (
|
||||
<div key="streaming-loading" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
|
||||
<div key="streaming-loading" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)
|
||||
)}
|
||||
{streamingMessage?.tool_calls?.[0]?.type === 'function' && (
|
||||
@@ -338,16 +532,31 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scroll to bottom button */}
|
||||
{showScrollToBottom && (
|
||||
<div className="absolute bottom-36 left-1/2 -translate-x-1/2 z-10">
|
||||
<Button
|
||||
onClick={scrollToBottom}
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-10 w-10 rounded-full shadow-lg border bg-background/80 backdrop-blur-sm hover:bg-background/90 transition-all duration-200"
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t p-4">
|
||||
{/* Chat Input Container */}
|
||||
<div className="relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all">
|
||||
<div className="flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all">
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={handleFirstInteraction}
|
||||
placeholder={providerModel.trim() ? "Ask me to add features, edit files, or build your project..." : "Please select a model to start chatting..."}
|
||||
className="min-h-[52px] max-h-32 resize-none border-0 bg-transparent px-4 py-3 pb-12 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isLoading || !providerModel.trim()}
|
||||
rows={1}
|
||||
style={{
|
||||
@@ -362,7 +571,52 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
/>
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="absolute bottom-2 left-2 right-2 flex items-center gap-2">
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
{/* File Attachment */}
|
||||
<FileAttachment
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
selectedFiles={attachedFiles}
|
||||
disabled={isLoading}
|
||||
multiple={true}
|
||||
/>
|
||||
|
||||
{/* Context Usage Wheel */}
|
||||
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="cursor-help">
|
||||
<CircularProgress
|
||||
value={contextUsagePercentage}
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Context usage: {lastInputTokens.toLocaleString()} / {currentModel.contextLength.toLocaleString()} tokens ({contextUsagePercentage.toFixed(1)}%)</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Cost Display */}
|
||||
{totalCost >= 0.01 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
|
||||
${totalCost.toFixed(2)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Total cost for this chat session</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Model Selector */}
|
||||
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
|
||||
<ModelSelector
|
||||
@@ -381,19 +635,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onClick={stopGeneration}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 rounded-lg p-0 hover:bg-muted"
|
||||
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
|
||||
>
|
||||
<Square className="h-4 w-4" />
|
||||
<Square />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={!input.trim() || !providerModel.trim()}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || !providerModel.trim()}
|
||||
size="sm"
|
||||
className="h-8 w-8 rounded-lg p-0"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
<ArrowUp />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,8 +2,10 @@ import { useState, useEffect, useCallback } from 'react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react';
|
||||
import { ChevronRight, ChevronDown, File, Folder, Search } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { createGitignoreFilter, normalizePathForGitignore } from '@/lib/gitignore';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
interface FileTreeProps {
|
||||
projectId: string;
|
||||
@@ -21,7 +23,14 @@ interface FileNode {
|
||||
|
||||
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
|
||||
const [tree, setTree] = useState<FileNode[]>([]);
|
||||
const [filteredTree, setFilteredTree] = useState<FileNode[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [gitignoreFilter, setGitignoreFilter] = useState<{
|
||||
isIgnored: (path: string) => boolean;
|
||||
shouldShow: (path: string) => boolean;
|
||||
} | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
@@ -115,14 +124,20 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
const loadFileTree = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Load gitignore filter
|
||||
const projectPath = `${projectsManager['dir']}/${projectId}`;
|
||||
const filter = await createGitignoreFilter(fs, projectPath);
|
||||
setGitignoreFilter(filter);
|
||||
|
||||
const structure = await buildFileTree(projectId, '');
|
||||
setTree(structure);
|
||||
setFilteredTree(structure);
|
||||
} catch (_error) {
|
||||
console.error('Failed to load file tree:', _error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId, buildFileTree]);
|
||||
}, [projectId, buildFileTree, fs, projectsManager]);
|
||||
|
||||
useEffect(() => {
|
||||
loadFileTree();
|
||||
@@ -141,7 +156,9 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
});
|
||||
};
|
||||
|
||||
// Update both the original tree and filtered tree
|
||||
setTree(prev => toggleNode(prev));
|
||||
setFilteredTree(prev => toggleNode(prev));
|
||||
};
|
||||
|
||||
const handleFileClick = (filePath: string, type: 'file' | 'directory') => {
|
||||
@@ -152,6 +169,58 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
}
|
||||
};
|
||||
|
||||
// Search functions
|
||||
const searchInFiles = useCallback(async (nodes: FileNode[], term: string): Promise<FileNode[]> => {
|
||||
if (!term.trim()) return nodes;
|
||||
|
||||
const results: FileNode[] = [];
|
||||
const searchTermLower = term.toLowerCase();
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.type === 'file') {
|
||||
const fileNameMatch = node.name.toLowerCase().includes(searchTermLower);
|
||||
|
||||
if (fileNameMatch) {
|
||||
results.push(node);
|
||||
}
|
||||
} else if (node.type === 'directory' && node.children) {
|
||||
const childResults = await searchInFiles(node.children, term);
|
||||
if (childResults.length > 0) {
|
||||
// Create a filtered directory node with matching children
|
||||
results.push({
|
||||
...node,
|
||||
children: childResults,
|
||||
isOpen: true, // Auto-expand directories with matches
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results }, []);
|
||||
|
||||
// Perform search when search term changes
|
||||
useEffect(() => {
|
||||
const performSearch = async () => {
|
||||
if (!searchTerm.trim()) {
|
||||
setFilteredTree(tree);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const results = await searchInFiles(tree, searchTerm);
|
||||
setFilteredTree(results);
|
||||
} catch (error) {
|
||||
console.error('Search failed:', error);
|
||||
setFilteredTree([]);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
performSearch();
|
||||
}, [searchTerm, tree, searchInFiles]);
|
||||
|
||||
const renderNode = (node: FileNode, depth: number = 0) => {
|
||||
const isSelected = selectedFile === node.path;
|
||||
|
||||
@@ -160,9 +229,16 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
const gitDirStatus = node.type === 'directory' ? getDirectoryGitStatus(node.path, node.children || []) : null;
|
||||
const gitStatus = gitFileStatus || gitDirStatus;
|
||||
|
||||
// Check if this file/directory is gitignored
|
||||
const normalizedPath = normalizePathForGitignore(node.path);
|
||||
const isGitignored = gitignoreFilter?.isIgnored(normalizedPath) ?? false;
|
||||
|
||||
// Get styling classes for git status
|
||||
const gitStatusClasses = getGitStatusClasses(gitStatus);
|
||||
|
||||
// Apply muted styling for gitignored files
|
||||
const gitignoreClasses = isGitignored ? 'text-muted-foreground' : '';
|
||||
|
||||
return (
|
||||
<div key={node.path}>
|
||||
<div
|
||||
@@ -177,19 +253,19 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
{node.type === 'directory' ? (
|
||||
<>
|
||||
{node.isOpen ? (
|
||||
<ChevronDown className="h-4 w-4 flex-shrink-0" />
|
||||
<ChevronDown className={cn("h-4 w-4 flex-shrink-0", gitignoreClasses)} />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 flex-shrink-0" />
|
||||
<ChevronRight className={cn("h-4 w-4 flex-shrink-0", gitignoreClasses)} />
|
||||
)}
|
||||
<Folder className="h-4 w-4 text-blue-500 flex-shrink-0" />
|
||||
<Folder className={cn("h-4 w-4 text-blue-500 flex-shrink-0", gitignoreClasses)} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-4" /> {/* Spacer for alignment */}
|
||||
<File className="h-4 w-4 text-gray-500 flex-shrink-0" />
|
||||
<File className={cn("h-4 w-4 text-gray-500 flex-shrink-0", gitignoreClasses)} />
|
||||
</>
|
||||
)}
|
||||
<span className={cn("text-sm truncate", gitStatusClasses)}>{node.name}</span>
|
||||
<span className={cn("text-sm whitespace-nowrap", gitStatusClasses, gitignoreClasses)}>{node.name}</span>
|
||||
</div>
|
||||
|
||||
{node.type === 'directory' && node.isOpen && node.children && (
|
||||
@@ -215,12 +291,32 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
{tree.length === 0 ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-8">
|
||||
No files found
|
||||
{/* Search Section */}
|
||||
<div className="mb-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search files..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Tree */}
|
||||
{isSearching ? (
|
||||
<div className="space-y-2">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div key={i} className="h-6 bg-muted rounded animate-pulse"></div>
|
||||
))}
|
||||
</div>
|
||||
) : filteredTree.length === 0 ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-4">
|
||||
{searchTerm ? 'No files found matching your search' : 'No files found'}
|
||||
</div>
|
||||
) : (
|
||||
tree.map(node => renderNode(node))
|
||||
filteredTree.map(node => renderNode(node))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { RefreshCw, FolderOpen, ArrowLeft } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
@@ -53,6 +55,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
|
||||
const isMobile = useIsMobile();
|
||||
const [hasBuiltProject, setHasBuiltProject] = useState(false);
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
@@ -120,6 +125,51 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const navigateToPath = useCallback((path: string) => {
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
setCurrentPath(path);
|
||||
|
||||
// Update navigation history
|
||||
const newHistory = navigationHistory.slice(0, historyIndex + 1);
|
||||
newHistory.push(path);
|
||||
setNavigationHistory(newHistory);
|
||||
setHistoryIndex(newHistory.length - 1);
|
||||
}
|
||||
}, [projectId, navigationHistory, historyIndex]);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
if (historyIndex > 0) {
|
||||
const newIndex = historyIndex - 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
|
||||
const goForward = useCallback(() => {
|
||||
if (historyIndex < navigationHistory.length - 1) {
|
||||
const newIndex = historyIndex + 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
console.log(`Sending response to iframe:`, message);
|
||||
@@ -165,8 +215,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const file = await projectsManager.readFile(projectId, 'dist' + filePath);
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
console.log(`Serving file: ${filePath}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -176,7 +227,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
'Content-Type': getContentType(filePath),
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: file,
|
||||
body: encodeBase64(bytes),
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -188,8 +239,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
// SPA fallback: serve index.html for non-file requests
|
||||
try {
|
||||
const indexFile = await projectsManager.readFile(projectId, 'dist/index.html');
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -199,13 +251,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
'Content-Type': 'text/html',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: indexFile,
|
||||
body: encodeBase64(bytes),
|
||||
},
|
||||
id
|
||||
});
|
||||
} catch {
|
||||
// Even index.html doesn't exist
|
||||
console.log(`No files found, returning 404 for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -214,7 +267,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
body: `File not found: ${path}`,
|
||||
body: encodeBase64(`File not found: ${path}`),
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -303,20 +356,18 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
<TabsContent value="preview" className="h-full mt-0">
|
||||
{hasBuiltProject ? (
|
||||
<div className="h-full w-full flex flex-col">
|
||||
<div className="flex items-center justify-between p-2 border-b bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<span className="text-sm font-medium bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">Project Preview</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={refreshIframe}
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={navigateToPath}
|
||||
onRefresh={refreshIframe}
|
||||
onBack={goBack}
|
||||
onForward={goForward}
|
||||
canGoBack={historyIndex > 0}
|
||||
canGoForward={historyIndex < navigationHistory.length - 1}
|
||||
/>
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.local-shakespeare.dev/`}
|
||||
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}
|
||||
className="w-full flex-1 border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
@@ -329,20 +380,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Build your project to see the preview here
|
||||
</p>
|
||||
<div className="bg-background border rounded-lg p-8 max-w-md">
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Run the build command to generate <code className="bg-muted px-1 rounded">dist/index.html</code>
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={checkForBuiltProject}
|
||||
className="gap-2"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Check for Build
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -360,11 +397,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</>
|
||||
) : (
|
||||
@@ -424,11 +464,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="h-[calc(100%-60px)]">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Star } from 'lucide-react';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface StarButtonProps {
|
||||
@@ -23,18 +24,22 @@ export function StarButton({
|
||||
}: StarButtonProps) {
|
||||
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const { toast } = useToast();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const isFavorite = favorites.includes(projectId);
|
||||
|
||||
const handleToggleFavorite = (e: React.MouseEvent) => {
|
||||
e.stopPropagation(); // Prevent triggering parent click events
|
||||
|
||||
|
||||
const newFavorites = isFavorite
|
||||
? favorites.filter(id => id !== projectId)
|
||||
: [...favorites, projectId];
|
||||
|
||||
setFavorites(newFavorites);
|
||||
|
||||
// Invalidate the projects query to trigger a refetch with new sorting
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
if (showToast) {
|
||||
toast({
|
||||
title: isFavorite ? "Project Unfavorited" : "Project Favorited",
|
||||
@@ -54,11 +59,11 @@ export function StarButton({
|
||||
)}
|
||||
aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
|
||||
>
|
||||
<Star
|
||||
<Star
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
|
||||
)}
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { UserMessage } from './UserMessage';
|
||||
|
||||
describe('UserMessage Integration', () => {
|
||||
it('renders text parts with file attachments correctly', () => {
|
||||
// Simulate the new text parts structure that ChatPane would create
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Please analyze this file:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/data.csv' },
|
||||
{ type: 'text' as const, text: 'Let me know what you find!' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
// Check that regular text is displayed
|
||||
expect(screen.getByText('Please analyze this file:')).toBeInTheDocument();
|
||||
expect(screen.getByText('Let me know what you find!')).toBeInTheDocument();
|
||||
|
||||
// Check that file attachment is rendered as a badge
|
||||
expect(screen.getByText('data.csv')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/data.csv')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles single text part with file attachment', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/script.js' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('script.js')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/script.js')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles multiple file attachments in separate parts', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Here are my files:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/config.json' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/styles.css' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/main.js' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Here are my files:')).toBeInTheDocument();
|
||||
expect(screen.getByText('config.json')).toBeInTheDocument();
|
||||
expect(screen.getByText('styles.css')).toBeInTheDocument();
|
||||
expect(screen.getByText('main.js')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles empty content gracefully', () => {
|
||||
const content: Array<{ type: 'text'; text: string }> = [];
|
||||
|
||||
const { container } = render(<UserMessage content={content} />);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { UserMessage } from './UserMessage';
|
||||
|
||||
describe('UserMessage', () => {
|
||||
it('renders regular text without file attachments', () => {
|
||||
const content = 'This is a regular message without any file attachments.';
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText(content)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles backward compatibility with string content containing file attachments', () => {
|
||||
const content = 'Here is my file: Added file: /tmp/test.txt';
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
// When using string content, it should still work but won't separate file attachments
|
||||
expect(screen.getByText(content)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders file attachment badges for single file with text parts', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Here is my file:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
|
||||
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders multiple file attachments with text parts', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Files uploaded:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/document.pdf' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/image.jpg' },
|
||||
{ type: 'text' as const, text: 'All done!' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Files uploaded:')).toBeInTheDocument();
|
||||
expect(screen.getByText('document.pdf')).toBeInTheDocument();
|
||||
expect(screen.getByText('image.jpg')).toBeInTheDocument();
|
||||
expect(screen.getByText('All done!')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders text files with FileText icon', () => {
|
||||
const content = [{ type: 'text' as const, text: 'Added file: /tmp/script.js' }];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('script.js')).toBeInTheDocument();
|
||||
// FileText icon should be rendered (we can't easily test the icon itself, but we can test the component renders)
|
||||
});
|
||||
|
||||
it('handles files without extensions', () => {
|
||||
const content = [{ type: 'text' as const, text: 'Added file: /tmp/README' }];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('README')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/README')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles complex filenames with underscores and numbers', () => {
|
||||
const content = [{ type: 'text' as const, text: 'Added file: /tmp/my_file_1.txt' }];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('my_file_1.txt')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/my_file_1.txt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('preserves whitespace in text content', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Line 1\n\nLine 3 with spaces \n\nFinal line' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
|
||||
];
|
||||
|
||||
const { container } = render(<UserMessage content={content} />);
|
||||
|
||||
// Check that the component renders and contains the expected text content
|
||||
expect(container.textContent).toContain('Line 1');
|
||||
expect(container.textContent).toContain('Line 3 with spaces');
|
||||
expect(container.textContent).toContain('Final line');
|
||||
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles mixed content with file attachments in the middle', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Starting text' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/middle.txt' },
|
||||
{ type: 'text' as const, text: 'ending text' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Starting text')).toBeInTheDocument();
|
||||
expect(screen.getByText('middle.txt')).toBeInTheDocument();
|
||||
expect(screen.getByText('ending text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { FileText, File } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
interface UserMessageProps {
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Component to render user messages nicely
|
||||
* Handles both string content and array content (text parts)
|
||||
* Detects "Added file: /tmp/<filename>" patterns and renders them as badges
|
||||
*/
|
||||
export function UserMessage({ content }: UserMessageProps) {
|
||||
// Convert content to array format for uniform processing
|
||||
const contentParts = typeof content === 'string'
|
||||
? [{ type: 'text' as const, text: content }]
|
||||
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
|
||||
|
||||
// Regular expression to match "Added file: /tmp/<filename>" patterns
|
||||
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
|
||||
|
||||
// Process each content part and categorize as text or file
|
||||
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
|
||||
|
||||
contentParts.forEach(part => {
|
||||
const text = part.text.trim();
|
||||
const match = text.match(filePattern);
|
||||
|
||||
if (match) {
|
||||
// This is a file attachment
|
||||
const filepath = match[1]; // "/tmp/filename.txt"
|
||||
processedParts.push({ type: 'file', content: text, filepath });
|
||||
} else if (text) {
|
||||
// This is regular text content
|
||||
processedParts.push({ type: 'text', content: text });
|
||||
}
|
||||
});
|
||||
|
||||
// If no content, return empty
|
||||
if (processedParts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getFileIcon = (filename: string) => {
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
|
||||
// Return FileText icon for text-like files, File icon for others
|
||||
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
|
||||
|
||||
if (extension && textExtensions.includes(extension)) {
|
||||
return <FileText className="h-3 w-3" />;
|
||||
}
|
||||
|
||||
return <File className="h-3 w-3" />;
|
||||
};
|
||||
|
||||
const getFileName = (filepath: string) => {
|
||||
return filepath.split('/').pop() || filepath;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{processedParts.map((part, index) => {
|
||||
if (part.type === 'text') {
|
||||
return (
|
||||
<div key={index} className="whitespace-pre-wrap">
|
||||
{part.content}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
const filename = getFileName(part.filepath!);
|
||||
return (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
|
||||
{getFileIcon(filename)}
|
||||
<span className="text-xs font-medium">{filename}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import { useState, forwardRef } from 'react';
|
||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||
|
||||
interface WalletModalProps {
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// Extracted AddWalletContent to prevent re-renders
|
||||
const AddWalletContent = forwardRef<HTMLDivElement, {
|
||||
alias: string;
|
||||
setAlias: (value: string) => void;
|
||||
connectionUri: string;
|
||||
setConnectionUri: (value: string) => void;
|
||||
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
|
||||
<div className="space-y-4 px-4" ref={ref}>
|
||||
<div>
|
||||
<Label htmlFor="alias">Wallet Name (optional)</Label>
|
||||
<Input
|
||||
id="alias"
|
||||
placeholder="My Lightning Wallet"
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="connection-uri">Connection URI</Label>
|
||||
<Textarea
|
||||
id="connection-uri"
|
||||
placeholder="nostr+walletconnect://..."
|
||||
value={connectionUri}
|
||||
onChange={(e) => setConnectionUri(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
AddWalletContent.displayName = 'AddWalletContent';
|
||||
|
||||
// Extracted WalletContent to prevent re-renders
|
||||
const WalletContent = forwardRef<HTMLDivElement, {
|
||||
hasWebLN: boolean;
|
||||
isDetecting: boolean;
|
||||
hasNWC: boolean;
|
||||
connections: NWCConnection[];
|
||||
connectionInfo: Record<string, NWCInfo>;
|
||||
activeConnection: string | null;
|
||||
handleSetActive: (cs: string) => void;
|
||||
handleRemoveConnection: (cs: string) => void;
|
||||
setAddDialogOpen: (open: boolean) => void;
|
||||
}>(({
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen
|
||||
}, ref) => (
|
||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Current Status</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">WebLN</p>
|
||||
<p className="text-xs text-muted-foreground">Browser extension</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{/* NWC */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Nostr Wallet Connect</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{connections.length > 0
|
||||
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
|
||||
: "Remote wallet connection"
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
|
||||
{hasNWC ? "Ready" : "None"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
{/* NWC Management */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">Nostr Wallet Connect</h3>
|
||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{/* Connected Wallets List */}
|
||||
{connections.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<p className="text-sm">No wallets connected</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{connections.map((connection) => {
|
||||
const info = connectionInfo[connection.connectionString];
|
||||
const isActive = activeConnection === connection.connectionString;
|
||||
return (
|
||||
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{connection.alias || info?.alias || 'Lightning Wallet'}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
NWC Connection
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
{!isActive && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleSetActive(connection.connectionString)}
|
||||
>
|
||||
<Zap className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Help */}
|
||||
{!hasWebLN && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install a WebLN extension or connect a NWC wallet for zaps.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
WalletContent.displayName = 'WalletContent';
|
||||
|
||||
export function WalletModal({ children, className }: WalletModalProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [connectionUri, setConnectionUri] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection
|
||||
} = useNWC();
|
||||
|
||||
const { hasWebLN, isDetecting } = useWallet();
|
||||
|
||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleAddConnection = async () => {
|
||||
if (!connectionUri.trim()) {
|
||||
toast({
|
||||
title: 'Connection URI required',
|
||||
description: 'Please enter a valid NWC connection URI.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
|
||||
if (success) {
|
||||
setConnectionUri('');
|
||||
setAlias('');
|
||||
setAddDialogOpen(false);
|
||||
}
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveConnection = (connectionString: string) => {
|
||||
removeConnection(connectionString);
|
||||
};
|
||||
|
||||
const handleSetActive = (connectionString: string) => {
|
||||
setActiveConnection(connectionString);
|
||||
toast({
|
||||
title: 'Active wallet changed',
|
||||
description: 'The selected wallet is now active for zaps.',
|
||||
});
|
||||
};
|
||||
|
||||
const walletContentProps = {
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen,
|
||||
};
|
||||
|
||||
const addWalletDialog = (
|
||||
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Connect NWC Wallet</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter your connection string from a compatible wallet.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<AddWalletContent
|
||||
alias={alias}
|
||||
setAlias={setAlias}
|
||||
connectionUri={connectionUri}
|
||||
setConnectionUri={setConnectionUri}
|
||||
/>
|
||||
<DialogFooter className="px-4">
|
||||
<Button
|
||||
onClick={handleAddConnection}
|
||||
disabled={isConnecting || !connectionUri.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isConnecting ? 'Connecting...' : 'Connect'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<>
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm" className={className}>
|
||||
<Wallet className="h-4 w-4 mr-2" />
|
||||
Wallet Settings
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
<DrawerContent className="h-full">
|
||||
<DrawerHeader className="text-center relative">
|
||||
<DrawerClose asChild>
|
||||
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DrawerClose>
|
||||
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
Lightning Wallet
|
||||
</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
Connect your lightning wallet to send zaps instantly.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="overflow-y-auto">
|
||||
<WalletContent {...walletContentProps} />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
{/* Render Add Wallet as a separate Drawer for mobile */}
|
||||
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DrawerContent>
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
Enter your connection string from a compatible wallet.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<AddWalletContent
|
||||
alias={alias}
|
||||
setAlias={setAlias}
|
||||
connectionUri={connectionUri}
|
||||
setConnectionUri={setConnectionUri}
|
||||
/>
|
||||
<div className="p-4">
|
||||
<Button
|
||||
onClick={handleAddConnection}
|
||||
disabled={isConnecting || !connectionUri.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isConnecting ? 'Connecting...' : 'Connect'}
|
||||
</Button>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm" className={className}>
|
||||
<Wallet className="h-4 w-4 mr-2" />
|
||||
Wallet Settings
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
Lightning Wallet
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Connect your lightning wallet to send zaps instantly.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<WalletContent {...walletContentProps} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{addWalletDialog}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
|
||||
interface ZapButtonProps {
|
||||
target: Event;
|
||||
className?: string;
|
||||
showCount?: boolean;
|
||||
zapData?: { count: number; totalSats: number; isLoading?: boolean };
|
||||
}
|
||||
|
||||
export function ZapButton({
|
||||
target,
|
||||
className = "text-xs ml-1",
|
||||
showCount = true,
|
||||
zapData: externalZapData
|
||||
}: ZapButtonProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target?.pubkey || '');
|
||||
const { webln, activeNWC } = useWallet();
|
||||
|
||||
// Only fetch data if not provided externally
|
||||
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
|
||||
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
|
||||
webln,
|
||||
activeNWC
|
||||
);
|
||||
|
||||
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
|
||||
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Use external data if provided, otherwise use fetched data
|
||||
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
||||
const showLoading = externalZapData?.isLoading || isLoading;
|
||||
|
||||
return (
|
||||
<ZapDialog target={target}>
|
||||
<div className={`flex items-center gap-1 ${className}`}>
|
||||
<Zap className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{showLoading ? (
|
||||
'...'
|
||||
) : showCount && totalSats > 0 ? (
|
||||
`${totalSats.toLocaleString()}`
|
||||
) : (
|
||||
'Zap'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</ZapDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
import { useState, useEffect, useRef, forwardRef } from 'react';
|
||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
interface ZapDialogProps {
|
||||
target: Event;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const presetAmounts = [
|
||||
{ amount: 1, icon: Sparkle },
|
||||
{ amount: 50, icon: Sparkles },
|
||||
{ amount: 100, icon: Zap },
|
||||
{ amount: 250, icon: Star },
|
||||
{ amount: 1000, icon: Rocket },
|
||||
];
|
||||
|
||||
interface ZapContentProps {
|
||||
invoice: string | null;
|
||||
amount: number | string;
|
||||
comment: string;
|
||||
isZapping: boolean;
|
||||
qrCodeUrl: string;
|
||||
copied: boolean;
|
||||
hasWebLN: boolean;
|
||||
handleZap: () => void;
|
||||
handleCopy: () => void;
|
||||
openInWallet: () => void;
|
||||
setAmount: (amount: number | string) => void;
|
||||
setComment: (comment: string) => void;
|
||||
inputRef: React.RefObject<HTMLInputElement>;
|
||||
zap: (amount: number, comment: string) => void;
|
||||
}
|
||||
|
||||
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
|
||||
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
invoice,
|
||||
amount,
|
||||
comment,
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
setAmount,
|
||||
setComment,
|
||||
inputRef,
|
||||
zap,
|
||||
}, ref) => (
|
||||
<div ref={ref}>
|
||||
{invoice ? (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
{/* Payment amount display */}
|
||||
<div className="text-center pt-4">
|
||||
<div className="text-2xl font-bold">{amount} sats</div>
|
||||
</div>
|
||||
|
||||
<Separator className="my-4" />
|
||||
|
||||
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
|
||||
{/* QR Code */}
|
||||
<div className="flex justify-center">
|
||||
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
|
||||
<CardContent className="p-0 flex justify-center">
|
||||
{qrCodeUrl ? (
|
||||
<img
|
||||
src={qrCodeUrl}
|
||||
alt="Lightning Invoice QR Code"
|
||||
className="w-full h-auto aspect-square max-w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Invoice input */}
|
||||
<div className="space-y-2 mt-4">
|
||||
<Label htmlFor="invoice">Lightning Invoice</Label>
|
||||
<div className="flex gap-2 min-w-0">
|
||||
<Input
|
||||
id="invoice"
|
||||
value={invoice}
|
||||
readOnly
|
||||
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
|
||||
onClick={(e) => e.currentTarget.select()}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleCopy}
|
||||
className="shrink-0"
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment buttons */}
|
||||
<div className="space-y-3 mt-4">
|
||||
{hasWebLN && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
}}
|
||||
disabled={isZapping}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : "Pay with WebLN"}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={openInWallet}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open in Lightning Wallet
|
||||
</Button>
|
||||
|
||||
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
||||
Scan the QR code or copy the invoice to pay with any Lightning wallet.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={String(amount)}
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
setAmount(parseInt(value, 10));
|
||||
}
|
||||
}}
|
||||
className="grid grid-cols-5 gap-1 w-full"
|
||||
>
|
||||
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
|
||||
<ToggleGroupItem
|
||||
key={presetAmount}
|
||||
value={String(presetAmount)}
|
||||
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
||||
>
|
||||
<Icon className="h-4 w-4 mb-1" />
|
||||
<span className="truncate">{presetAmount}</span>
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
<span className="text-xs text-muted-foreground">OR</span>
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
</div>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
id="custom-amount"
|
||||
type="number"
|
||||
placeholder="Custom amount"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
className="w-full text-sm"
|
||||
/>
|
||||
<Textarea
|
||||
id="custom-comment"
|
||||
placeholder="Add a comment (optional)"
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
className="w-full resize-none text-sm"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="px-4 pb-4">
|
||||
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
|
||||
{isZapping ? (
|
||||
'Creating invoice...'
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Zap {amount} sats
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
ZapContent.displayName = 'ZapContent';
|
||||
|
||||
|
||||
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target.pubkey);
|
||||
const { toast } = useToast();
|
||||
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
|
||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||
const [amount, setAmount] = useState<number | string>(100);
|
||||
const [comment, setComment] = useState<string>('');
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
// Detect WebLN when dialog opens
|
||||
useEffect(() => {
|
||||
if (open && !hasWebLN) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [open, hasWebLN, detectWebLN]);
|
||||
|
||||
// Generate QR code
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
|
||||
const generateQR = async () => {
|
||||
if (!invoice) {
|
||||
setQrCodeUrl('');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
|
||||
width: 512,
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#FFFFFF',
|
||||
},
|
||||
});
|
||||
|
||||
if (!isCancelled) {
|
||||
setQrCodeUrl(url);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isCancelled) {
|
||||
console.error('Failed to generate QR code:', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
generateQR();
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
};
|
||||
}, [invoice]);
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (invoice) {
|
||||
await navigator.clipboard.writeText(invoice);
|
||||
setCopied(true);
|
||||
toast({
|
||||
title: 'Invoice copied',
|
||||
description: 'Lightning invoice copied to clipboard',
|
||||
});
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const openInWallet = () => {
|
||||
if (invoice) {
|
||||
const lightningUrl = `lightning:${invoice}`;
|
||||
window.open(lightningUrl, '_blank');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
} else {
|
||||
// Clean up state when dialog closes
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
}
|
||||
}, [open, setInvoice]);
|
||||
|
||||
const handleZap = () => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
};
|
||||
|
||||
const contentProps = {
|
||||
invoice,
|
||||
amount,
|
||||
comment,
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
setAmount,
|
||||
setComment,
|
||||
inputRef,
|
||||
zap,
|
||||
};
|
||||
|
||||
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
// Use drawer for entire mobile flow, make it full-screen when showing invoice
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
onOpenChange={(newOpen) => {
|
||||
// Reset invoice when closing
|
||||
if (!newOpen) {
|
||||
setInvoice(null);
|
||||
setQrCodeUrl('');
|
||||
}
|
||||
setOpen(newOpen);
|
||||
}}
|
||||
dismissible={true} // Always allow dismissal via drag
|
||||
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
|
||||
activeSnapPoint={invoice ? 0.98 : 0.98}
|
||||
modal={true}
|
||||
shouldScaleBackground={false}
|
||||
fadeFromIndex={0}
|
||||
>
|
||||
<DrawerTrigger asChild>
|
||||
<div className={`cursor-pointer ${className || ''}`}>
|
||||
{children}
|
||||
</div>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent
|
||||
key={invoice ? 'payment' : 'form'}
|
||||
className={cn(
|
||||
"transition-all duration-300",
|
||||
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
|
||||
)}
|
||||
data-testid="zap-modal"
|
||||
>
|
||||
<DrawerHeader className="text-center relative">
|
||||
{/* Back button when showing invoice */}
|
||||
{invoice && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setInvoice(null);
|
||||
setQrCodeUrl('');
|
||||
}}
|
||||
className="absolute left-4 top-4 flex items-center gap-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Close button */}
|
||||
<DrawerClose asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-4 top-4"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DrawerClose>
|
||||
|
||||
<DrawerTitle className="text-lg break-words pt-2">
|
||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||
</DrawerTitle>
|
||||
<DrawerDescription className="text-sm break-words text-center">
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
)}
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="flex-1 overflow-y-auto px-4 pb-4">
|
||||
<ZapContent {...contentProps} />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<div className={`cursor-pointer ${className || ''}`}>
|
||||
{children}
|
||||
</div>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg break-words">
|
||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-center break-words">
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
<>
|
||||
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
|
||||
</>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto">
|
||||
<ZapContent {...contentProps} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,362 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings, Trash2, Check } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
apiKeysURL: string;
|
||||
}
|
||||
|
||||
const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
{
|
||||
id: "openrouter",
|
||||
name: "OpenRouter",
|
||||
baseURL: "https://openrouter.ai/api/v1",
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
baseURL: "https://api.ppq.ai",
|
||||
apiKeysURL: "https://ppq.ai/api-docs",
|
||||
},
|
||||
{
|
||||
id: "zai",
|
||||
name: "Z.ai",
|
||||
baseURL: "https://api.z.ai/api/paas/v4",
|
||||
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
|
||||
},
|
||||
{
|
||||
id: "moonshot",
|
||||
name: "Moonshot",
|
||||
baseURL: "https://api.moonshot.ai/v1",
|
||||
apiKeysURL: "https://platform.moonshot.ai/console/api-keys",
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKeysURL: "https://platform.openai.com/api-keys",
|
||||
},
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
baseURL: "https://api.anthropic.com/v1",
|
||||
apiKeysURL: "https://console.anthropic.com/settings/keys",
|
||||
},
|
||||
{
|
||||
id: "xai",
|
||||
name: "xAI",
|
||||
baseURL: "https://api.x.ai/v1",
|
||||
apiKeysURL: "https://console.x.ai",
|
||||
},
|
||||
];
|
||||
|
||||
interface AISettingsDialogProps {
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISettingsDialogProps = {}) {
|
||||
const { settings, updateSettings, isConfigured } = useAISettings();
|
||||
const [internalOpen, setInternalOpen] = useState(false);
|
||||
|
||||
// Use controlled or internal state
|
||||
const open = controlledOpen !== undefined ? controlledOpen : internalOpen;
|
||||
const setOpen = onOpenChange || setInternalOpen;
|
||||
const [localProviders, setLocalProviders] = useState(settings.providers);
|
||||
const [customProviderName, setCustomProviderName] = useState('');
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings({ providers: localProviders });
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setLocalProviders(settings.providers);
|
||||
setCustomProviderName('');
|
||||
setCustomBaseURL('');
|
||||
setCustomApiKey('');
|
||||
setPresetApiKeys({});
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleAddPresetProvider = (preset: PresetProvider) => {
|
||||
const apiKey = presetApiKeys[preset.id] || '';
|
||||
if (!apiKey.trim()) return;
|
||||
|
||||
const newProvider: AIConnection = {
|
||||
baseURL: preset.baseURL,
|
||||
apiKey: apiKey.trim(),
|
||||
};
|
||||
|
||||
setLocalProviders(prev => ({
|
||||
...prev,
|
||||
[preset.id]: newProvider,
|
||||
}));
|
||||
|
||||
// Clear the API key input for this preset
|
||||
setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: '',
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAddCustomProvider = () => {
|
||||
if (!customProviderName.trim() || !customBaseURL.trim()) return;
|
||||
|
||||
const newProvider: AIConnection = {
|
||||
baseURL: customBaseURL.trim(),
|
||||
apiKey: customApiKey.trim(),
|
||||
};
|
||||
|
||||
setLocalProviders(prev => ({
|
||||
...prev,
|
||||
[customProviderName.trim()]: newProvider,
|
||||
}));
|
||||
setCustomProviderName('');
|
||||
setCustomBaseURL('');
|
||||
setCustomApiKey('');
|
||||
};
|
||||
|
||||
const handleRemoveProvider = (name: string) => {
|
||||
setLocalProviders(prev => {
|
||||
const { [name]: removed, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
};
|
||||
|
||||
const handleUpdateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
setLocalProviders(prev => ({
|
||||
...prev,
|
||||
[name]: {
|
||||
...prev[name],
|
||||
...connection,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const configuredProviderIds = Object.keys(localProviders);
|
||||
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
{/* Only show trigger if not controlled externally */}
|
||||
{controlledOpen === undefined && (
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="gap-2">
|
||||
<Settings className="h-4 w-4" />
|
||||
AI Settings
|
||||
{!isConfigured && (
|
||||
<span className="ml-1 h-2 w-2 rounded-full bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>AI Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure AI providers by adding your API keys. Settings are stored locally in your browser.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
{/* Configured Providers */}
|
||||
{configuredProviderIds.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">Configured Providers</h4>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{configuredProviderIds.map((providerId) => {
|
||||
const preset = PRESET_PROVIDERS.find(p => p.id === providerId);
|
||||
const provider = localProviders[providerId];
|
||||
const isCustom = !preset;
|
||||
|
||||
return (
|
||||
<AccordionItem key={providerId} value={providerId} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center justify-between w-full mr-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">
|
||||
{preset?.name || providerId}
|
||||
</span>
|
||||
{isCustom && <Badge variant="outline">Custom</Badge>}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveProvider(providerId);
|
||||
}}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${providerId}-baseURL`}>Base URL</Label>
|
||||
<Input
|
||||
id={`${providerId}-baseURL`}
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={provider?.baseURL || ''}
|
||||
onChange={(e) => handleUpdateProvider(providerId, { baseURL: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${providerId}-apiKey`}>API Key</Label>
|
||||
<Input
|
||||
id={`${providerId}-apiKey`}
|
||||
type="password"
|
||||
placeholder="Enter your API key"
|
||||
value={provider?.apiKey || ''}
|
||||
onChange={(e) => handleUpdateProvider(providerId, { apiKey: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
})}
|
||||
</Accordion>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{configuredProviderIds.length > 0 && availablePresets.length > 0 && <Separator />}
|
||||
|
||||
{/* Available Preset Providers */}
|
||||
{availablePresets.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">Add Provider</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{availablePresets.map((preset) => (
|
||||
<Card key={preset.id}>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground"
|
||||
onClick={() => window.open(preset.apiKeysURL, '_blank')}
|
||||
>
|
||||
Get API key
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Enter your API key"
|
||||
type="password"
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!presetApiKeys[preset.id]?.trim()}
|
||||
size="sm"
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{availablePresets.length > 0 && <Separator />}
|
||||
|
||||
{/* Custom Provider */}
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">Add Custom Provider</h4>
|
||||
<Card>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-name">Provider Name</Label>
|
||||
<Input
|
||||
id="custom-name"
|
||||
placeholder="e.g., my-custom-api"
|
||||
value={customProviderName}
|
||||
onChange={(e) => setCustomProviderName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-baseurl">Base URL</Label>
|
||||
<Input
|
||||
id="custom-baseurl"
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={customBaseURL}
|
||||
onChange={(e) => setCustomBaseURL(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-apikey">API Key</Label>
|
||||
<Input
|
||||
id="custom-apikey"
|
||||
type="password"
|
||||
placeholder="Enter your API key (optional)"
|
||||
value={customApiKey}
|
||||
onChange={(e) => setCustomApiKey(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleAddCustomProvider}
|
||||
disabled={
|
||||
!customProviderName.trim() ||
|
||||
!customBaseURL.trim() ||
|
||||
customProviderName.trim() in localProviders
|
||||
}
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
Add Custom Provider
|
||||
</Button>
|
||||
{customProviderName.trim() in localProviders && (
|
||||
<p className="text-sm text-destructive">
|
||||
Provider with this name already exists
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitHistoryDialog } from './GitHistoryDialog';
|
||||
|
||||
// Mock isomorphic-git
|
||||
vi.mock('isomorphic-git', () => ({
|
||||
default: {
|
||||
log: vi.fn(),
|
||||
resolveRef: vi.fn(),
|
||||
readCommit: vi.fn(),
|
||||
listFiles: vi.fn(),
|
||||
readBlob: vi.fn(),
|
||||
add: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
commit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the useFS hook
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: () => ({
|
||||
fs: {
|
||||
stat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the useToast hook
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('GitHistoryDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the history button', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /history/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when history button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Git History')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows loading state when dialog opens', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Loading git history...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('renders rollback buttons for commits (except the first one)', async () => {
|
||||
const mockCommits = [
|
||||
{
|
||||
oid: 'commit1',
|
||||
commit: {
|
||||
message: 'Latest commit',
|
||||
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
parent: [],
|
||||
tree: 'tree1',
|
||||
},
|
||||
payload: '',
|
||||
},
|
||||
{
|
||||
oid: 'commit2',
|
||||
commit: {
|
||||
message: 'Previous commit',
|
||||
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 },
|
||||
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 },
|
||||
parent: [],
|
||||
tree: 'tree2',
|
||||
},
|
||||
payload: '',
|
||||
},
|
||||
];
|
||||
|
||||
const git = await import('isomorphic-git');
|
||||
vi.mocked(git.default.log).mockResolvedValue(mockCommits);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Latest commit')).toBeInTheDocument();
|
||||
expect(screen.getByText('Previous commit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Should have one rollback button (not for the latest commit)
|
||||
const rollbackButtons = screen.getAllByText('Rollback');
|
||||
expect(rollbackButtons).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('handles multi-line commit messages with expand/collapse', async () => {
|
||||
const mockCommits = [
|
||||
{
|
||||
oid: 'commit1',
|
||||
commit: {
|
||||
message: 'Add new feature\n\nThis commit adds a new feature with the following changes:\n- Added component A\n- Updated component B\n- Fixed bug in component C',
|
||||
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
parent: [],
|
||||
tree: 'tree1',
|
||||
},
|
||||
payload: '',
|
||||
},
|
||||
];
|
||||
|
||||
const git = await import('isomorphic-git');
|
||||
vi.mocked(git.default.log).mockResolvedValue(mockCommits);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Add new feature')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Should show expand button for multi-line commit
|
||||
const expandButton = screen.getByRole('button', { name: '' }); // ChevronDown button
|
||||
expect(expandButton).toBeInTheDocument();
|
||||
|
||||
// Click to expand
|
||||
fireEvent.click(expandButton);
|
||||
|
||||
// Should show the expanded content
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/This commit adds a new feature/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,9 +5,9 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
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 { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import git from 'isomorphic-git';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -43,12 +43,11 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const setIsOpen = onOpenChange || setInternalOpen;
|
||||
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
|
||||
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
|
||||
const git = useGit();
|
||||
const { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
|
||||
const loadGitHistory = useCallback(async () => {
|
||||
if (!fs) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
@@ -57,7 +56,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Check if git repository exists
|
||||
try {
|
||||
await fs.stat(`${projectPath}/.git`);
|
||||
await git.findRoot({ filepath: projectPath });
|
||||
} catch {
|
||||
setError('No git repository found in this project');
|
||||
return;
|
||||
@@ -65,7 +64,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get git log
|
||||
const gitLog = await git.log({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
depth: 50, // Limit to last 50 commits
|
||||
});
|
||||
@@ -77,7 +75,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [fs, projectId]);
|
||||
}, [git, projectId]);
|
||||
|
||||
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
|
||||
if (!fs) return;
|
||||
@@ -89,7 +87,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get the current HEAD commit
|
||||
const currentCommit = await git.resolveRef({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
@@ -105,7 +102,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get all commits between the target commit and HEAD
|
||||
const allCommits = await git.log({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
depth: 1000,
|
||||
});
|
||||
@@ -138,14 +134,12 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get all files from the target commit
|
||||
const targetFiles = await git.listFiles({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
ref: targetCommit.oid,
|
||||
});
|
||||
|
||||
// Get current files to know what to remove
|
||||
const currentFiles = await git.listFiles({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
@@ -156,7 +150,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
try {
|
||||
await fs.unlink(`${projectPath}/${filepath}`);
|
||||
await git.remove({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
filepath,
|
||||
});
|
||||
@@ -171,7 +164,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
for (const filepath of targetFiles) {
|
||||
try {
|
||||
const { blob } = await git.readBlob({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
oid: targetCommit.oid,
|
||||
filepath,
|
||||
@@ -188,7 +180,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Stage the file
|
||||
await git.add({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
filepath,
|
||||
});
|
||||
@@ -210,7 +201,6 @@ ${commitsToRevert.map(c => {
|
||||
}).join('\n')}`;
|
||||
|
||||
await git.commit({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
message: revertMessage,
|
||||
author: {
|
||||
@@ -237,7 +227,7 @@ ${commitsToRevert.map(c => {
|
||||
} finally {
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [fs, projectId, toast, loadGitHistory]);
|
||||
}, [git, fs, projectId, toast, loadGitHistory]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
|
||||
@@ -35,7 +35,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
|
||||
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className='flex-1 text-left hidden md:block truncate'>
|
||||
<div className='flex-1 text-left truncate'>
|
||||
<p className='font-medium text-sm truncate'>{getDisplayName(currentUser)}</p>
|
||||
</div>
|
||||
<ChevronDown className='w-4 h-4 text-muted-foreground' />
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { BrowserAddressBar } from './browser-address-bar';
|
||||
|
||||
describe('BrowserAddressBar', () => {
|
||||
it('renders navigation buttons and address input', () => {
|
||||
render(<BrowserAddressBar />);
|
||||
|
||||
expect(screen.getByTitle('Go back')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Go forward')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Refresh')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('Enter path (e.g., /, /about)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onNavigate with proper path when form is submitted', () => {
|
||||
const onNavigate = vi.fn();
|
||||
render(<BrowserAddressBar onNavigate={onNavigate} />);
|
||||
|
||||
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
|
||||
fireEvent.change(input, { target: { value: 'about' } });
|
||||
fireEvent.submit(input.closest('form')!);
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith('/about');
|
||||
});
|
||||
|
||||
it('disables back/forward buttons based on canGoBack/canGoForward props', () => {
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
canGoBack={false}
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTitle('Go back')).toBeDisabled();
|
||||
expect(screen.getByTitle('Go forward')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('calls navigation handlers when buttons are clicked', () => {
|
||||
const onBack = vi.fn();
|
||||
const onForward = vi.fn();
|
||||
const onRefresh = vi.fn();
|
||||
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
onBack={onBack}
|
||||
onForward={onForward}
|
||||
onRefresh={onRefresh}
|
||||
canGoBack={true}
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByTitle('Go back'));
|
||||
fireEvent.click(screen.getByTitle('Go forward'));
|
||||
fireEvent.click(screen.getByTitle('Refresh'));
|
||||
|
||||
expect(onBack).toHaveBeenCalled();
|
||||
expect(onForward).toHaveBeenCalled();
|
||||
expect(onRefresh).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface BrowserAddressBarProps {
|
||||
currentPath?: string;
|
||||
onNavigate?: (path: string) => void;
|
||||
onRefresh?: () => void;
|
||||
onBack?: () => void;
|
||||
onForward?: () => void;
|
||||
canGoBack?: boolean;
|
||||
canGoForward?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function BrowserAddressBar({
|
||||
currentPath = '/',
|
||||
onNavigate,
|
||||
onRefresh,
|
||||
onBack,
|
||||
onForward,
|
||||
canGoBack = false,
|
||||
canGoForward = false,
|
||||
className,
|
||||
}: BrowserAddressBarProps) {
|
||||
const [inputValue, setInputValue] = useState(currentPath);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let path = inputValue.trim();
|
||||
|
||||
// Ensure path starts with /
|
||||
if (!path.startsWith('/')) {
|
||||
path = '/' + path;
|
||||
}
|
||||
|
||||
onNavigate?.(path);
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setInputValue(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
"flex items-center gap-1 p-2 border-b bg-background",
|
||||
className
|
||||
)}>
|
||||
{/* Navigation buttons */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={!canGoBack}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Go back"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onForward}
|
||||
disabled={!canGoForward}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Go forward"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onRefresh}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Refresh"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Address bar */}
|
||||
<form onSubmit={handleSubmit} className="flex-1 mx-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter path (e.g., /, /about)"
|
||||
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface CircularProgressProps {
|
||||
value?: number;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
const CircularProgress = React.forwardRef<
|
||||
SVGSVGElement,
|
||||
CircularProgressProps
|
||||
>(({ value = 0, size = 24, strokeWidth = 2, className, children }, ref) => {
|
||||
const radius = (size - strokeWidth) / 2;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const strokeDasharray = circumference;
|
||||
const strokeDashoffset = circumference - (value / 100) * circumference;
|
||||
|
||||
return (
|
||||
<div className={cn("relative inline-flex items-center justify-center", className)}>
|
||||
<svg
|
||||
ref={ref}
|
||||
width={size}
|
||||
height={size}
|
||||
className="transform -rotate-90"
|
||||
viewBox={`0 0 ${size} ${size}`}
|
||||
>
|
||||
{/* Background circle */}
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
className="text-muted/30"
|
||||
/>
|
||||
{/* Progress circle */}
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={strokeDasharray}
|
||||
strokeDashoffset={strokeDashoffset}
|
||||
className="text-primary transition-all duration-300 ease-in-out"
|
||||
/>
|
||||
</svg>
|
||||
{children && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
CircularProgress.displayName = "CircularProgress";
|
||||
|
||||
export { CircularProgress };
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { FileAttachment } from './file-attachment';
|
||||
|
||||
describe('FileAttachment', () => {
|
||||
it('renders the attachment button', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
|
||||
render(
|
||||
<FileAttachment onFileSelect={onFileSelect} />
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onFileSelect when file is selected', async () => {
|
||||
const onFileSelect = vi.fn();
|
||||
|
||||
render(
|
||||
<FileAttachment onFileSelect={onFileSelect} />
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
// Get the hidden file input
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
expect(fileInput).toBeInTheDocument();
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
|
||||
|
||||
// Mock the file input change event
|
||||
Object.defineProperty(fileInput, 'files', {
|
||||
value: [file],
|
||||
writable: false,
|
||||
});
|
||||
|
||||
fireEvent.change(fileInput);
|
||||
|
||||
expect(onFileSelect).toHaveBeenCalledWith(file);
|
||||
});
|
||||
|
||||
it('displays selected files', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
const onFileRemove = vi.fn();
|
||||
const selectedFiles = [
|
||||
new File(['content1'], 'file1.txt', { type: 'text/plain' }),
|
||||
new File(['content2'], 'file2.txt', { type: 'text/plain' }),
|
||||
];
|
||||
|
||||
render(
|
||||
<FileAttachment
|
||||
onFileSelect={onFileSelect}
|
||||
onFileRemove={onFileRemove}
|
||||
selectedFiles={selectedFiles}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('file1.txt')).toBeInTheDocument();
|
||||
expect(screen.getByText('file2.txt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onFileRemove when remove button is clicked', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
const onFileRemove = vi.fn();
|
||||
const selectedFiles = [
|
||||
new File(['content'], 'test.txt', { type: 'text/plain' }),
|
||||
];
|
||||
|
||||
render(
|
||||
<FileAttachment
|
||||
onFileSelect={onFileSelect}
|
||||
onFileRemove={onFileRemove}
|
||||
selectedFiles={selectedFiles}
|
||||
/>
|
||||
);
|
||||
|
||||
const removeButtons = screen.getAllByRole('button');
|
||||
// First button is the attachment button, second is the remove button
|
||||
const removeButton = removeButtons[1];
|
||||
|
||||
fireEvent.click(removeButton);
|
||||
|
||||
expect(onFileRemove).toHaveBeenCalledWith(selectedFiles[0]);
|
||||
});
|
||||
|
||||
it('disables interaction when disabled prop is true', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
|
||||
render(
|
||||
<FileAttachment onFileSelect={onFileSelect} disabled={true} />
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeDisabled();
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
expect(fileInput).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Paperclip, X } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface FileAttachmentProps {
|
||||
onFileSelect: (file: File) => void;
|
||||
onFileRemove?: (file: File) => void;
|
||||
selectedFiles?: File[];
|
||||
disabled?: boolean;
|
||||
accept?: string;
|
||||
multiple?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function FileAttachment({
|
||||
onFileSelect,
|
||||
onFileRemove,
|
||||
selectedFiles = [],
|
||||
disabled = false,
|
||||
accept,
|
||||
multiple = false,
|
||||
className
|
||||
}: FileAttachmentProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleButtonClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = event.target.files;
|
||||
if (files) {
|
||||
Array.from(files).forEach(file => {
|
||||
onFileSelect(file);
|
||||
});
|
||||
}
|
||||
// Reset input so the same file can be selected again
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveFile = (file: File) => {
|
||||
if (onFileRemove) {
|
||||
onFileRemove(file);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={handleFileChange}
|
||||
accept={accept}
|
||||
multiple={multiple}
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleButtonClick}
|
||||
disabled={disabled}
|
||||
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50"
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{selectedFiles.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 max-w-48">
|
||||
{selectedFiles.map((file, index) => (
|
||||
<div
|
||||
key={`${file.name}-${index}`}
|
||||
className="flex items-center gap-1 px-2 py-1 bg-muted/50 rounded-md text-xs"
|
||||
>
|
||||
<span className="truncate max-w-24" title={file.name}>
|
||||
{file.name}
|
||||
</span>
|
||||
{onFileRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveFile(file)}
|
||||
className="h-3 w-3 p-0 hover:bg-muted/70"
|
||||
>
|
||||
<X className="h-2 w-2" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner } from "sonner"
|
||||
|
||||
type ToasterProps = React.ComponentProps<typeof Sonner>
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -3,6 +3,7 @@ import { createContext } from 'react';
|
||||
export interface AIConnection {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
|
||||
@@ -7,6 +7,8 @@ export interface AppConfig {
|
||||
theme: Theme;
|
||||
/** Selected relay URL */
|
||||
relayUrl: string;
|
||||
/** Deploy server domain (e.g., "shakespeare.wtf") */
|
||||
deployServer: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface GitCredential {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface GitSettings {
|
||||
credentials: Record<string, GitCredential>; // keyed by origin
|
||||
corsProxy: string;
|
||||
}
|
||||
|
||||
export interface GitSettingsContextType {
|
||||
settings: GitSettings;
|
||||
updateSettings: (settings: Partial<GitSettings>) => void;
|
||||
addCredential: (origin: string, credential: GitCredential) => void;
|
||||
removeCredential: (origin: string) => void;
|
||||
updateCredential: (origin: string, credential: Partial<GitCredential>) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
export const GitSettingsContext = createContext<GitSettingsContextType | undefined>(undefined);
|
||||
@@ -1,8 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
import type { JSRuntime } from '@/lib/JSRuntime';
|
||||
|
||||
export interface JSRuntimeContextType {
|
||||
runtime: JSRuntime;
|
||||
}
|
||||
|
||||
export const JSRuntimeContext = createContext<JSRuntimeContextType | undefined>(undefined);
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { useNWCInternal as useNWCHook } from '@/hooks/useNWC';
|
||||
import { NWCContext } from '@/hooks/useNWCContext';
|
||||
|
||||
export function NWCProvider({ children }: { children: ReactNode }) {
|
||||
const nwc = useNWCHook();
|
||||
return <NWCContext.Provider value={nwc}>{children}</NWCContext.Provider>;
|
||||
}
|
||||
+83
-135
@@ -1,14 +1,13 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
interface UseAIChatSessionOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
@@ -28,7 +27,6 @@ interface StreamingMessage {
|
||||
*/
|
||||
export function useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
@@ -37,161 +35,109 @@ export function useAIChat({
|
||||
}: UseAIChatSessionOptions) {
|
||||
const sessionManager = useSessionManager();
|
||||
const { isConfigured } = useAISettings();
|
||||
const [sessionId, setSessionId] = useState<string>('');
|
||||
const [sessionState, setSessionState] = useState<SessionState | null>(null);
|
||||
|
||||
// Generate consistent session ID for this project
|
||||
const generatedSessionId = useMemo(() => {
|
||||
return `session-${projectId}`;
|
||||
}, [projectId]);
|
||||
// Split session state into individual variables for efficient updates
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [totalCost, setTotalCost] = useState<number>(0);
|
||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||
|
||||
const initSession = useCallback(async () => {
|
||||
// Load or update session
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps);
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...session.messages]);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
}, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]);
|
||||
|
||||
// Initialize session
|
||||
useEffect(() => {
|
||||
const initSession = async () => {
|
||||
// Check if there's already an active session for this project
|
||||
const existingSessions = sessionManager.getProjectSessions(projectId);
|
||||
|
||||
if (existingSessions.length > 0) {
|
||||
// Use the most recent session for this project
|
||||
const mostRecent = existingSessions.sort((a, b) =>
|
||||
b.lastActivity.getTime() - a.lastActivity.getTime()
|
||||
)[0];
|
||||
|
||||
setSessionId(mostRecent.id);
|
||||
setSessionState(mostRecent);
|
||||
|
||||
// Get the latest session state immediately
|
||||
const currentSession = sessionManager.getSession(mostRecent.id);
|
||||
if (currentSession) {
|
||||
setSessionState(currentSession);
|
||||
}
|
||||
} else {
|
||||
// Create new session
|
||||
const config: SessionConfig = {
|
||||
id: generatedSessionId,
|
||||
projectId,
|
||||
projectName,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
maxSteps
|
||||
};
|
||||
|
||||
const newSessionId = await sessionManager.createSession(config);
|
||||
setSessionId(newSessionId);
|
||||
|
||||
const newSession = sessionManager.getSession(newSessionId);
|
||||
if (newSession) {
|
||||
setSessionState(newSession);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
initSession();
|
||||
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
|
||||
}, [initSession]);
|
||||
|
||||
|
||||
// Subscribe to atomic session events for efficient updates
|
||||
useSessionSubscription('messageAdded', (updatedProjectId: string, message: AIMessage) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setMessages(prev => [...prev, message]);
|
||||
// Whenever an assistant message is added, it means streaming is done (until we get another streamingUpdate)
|
||||
if (message.role === 'assistant') {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Subscribe to session events using shared hook
|
||||
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Directly update state with the provided state object
|
||||
setSessionState({
|
||||
...state,
|
||||
messages: [...state.messages],
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined
|
||||
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content,
|
||||
tool_calls: toolCalls
|
||||
});
|
||||
}
|
||||
}, [sessionId]);
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
useSessionSubscription('loadingChanged', (updatedProjectId: string, loading: boolean) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setIsLoading(loading);
|
||||
|
||||
// Clear streaming message when loading stops
|
||||
if (!loading) {
|
||||
setStreamingMessage(undefined);
|
||||
}
|
||||
|
||||
if (onUpdateMetadata && loading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectId}...`);
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
}, [projectId, onUpdateMetadata]);
|
||||
|
||||
useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
useSessionSubscription('costUpdated', (updatedProjectId: string, cost: number) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setTotalCost(cost);
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (onUpdateMetadata && isLoading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
useSessionSubscription('contextUsageUpdated', (updatedProjectId: string, inputTokens: number) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setLastInputTokens(inputTokens);
|
||||
}
|
||||
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
|
||||
|
||||
|
||||
|
||||
// Derived state
|
||||
const messages = sessionState?.messages || [];
|
||||
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
|
||||
const isLoading = sessionState?.isLoading || false;
|
||||
}, [projectId]);
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string, providerModel: string) => {
|
||||
if (!sessionId) return;
|
||||
await sessionManager.sendMessage(sessionId, content, providerModel);
|
||||
}, [sessionId, sessionManager]);
|
||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
|
||||
if (!sessionId) return;
|
||||
|
||||
// If specific messages are provided, we need to update the session first
|
||||
if (messagesToUse) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Replace session messages with provided messages
|
||||
session.messages = [...messagesToUse];
|
||||
|
||||
// Manually trigger session update
|
||||
sessionManager.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
await sessionManager.startGeneration(sessionId, providerModel);
|
||||
}, [sessionId, sessionManager]);
|
||||
const startGeneration = useCallback(async (providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (!sessionId) return;
|
||||
sessionManager.stopGeneration(sessionId);
|
||||
}, [sessionId, sessionManager]);
|
||||
sessionManager.stopGeneration(projectId);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
const addMessage = useCallback(async (message: AIMessage) => {
|
||||
if (!sessionId) return;
|
||||
await sessionManager.addMessage(sessionId, message);
|
||||
}, [sessionId, sessionManager]);
|
||||
await sessionManager.addMessage(projectId, message);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
const startNewSession = useCallback(async () => {
|
||||
if (!sessionId) return;
|
||||
await sessionManager.startNewSession(sessionId);
|
||||
}, [sessionId, sessionManager]);
|
||||
await sessionManager.startNewSession(projectId);
|
||||
|
||||
// Reset individual state variables
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setTotalCost(0);
|
||||
setLastInputTokens(0);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
const clearMessages = useCallback(async () => {
|
||||
// Alias for startNewSession for backward compatibility
|
||||
@@ -202,6 +148,8 @@ export function useAIChat({
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
@@ -209,6 +157,6 @@ export function useAIChat({
|
||||
startNewSession,
|
||||
addMessage,
|
||||
isConfigured,
|
||||
sessionId
|
||||
projectId
|
||||
};
|
||||
}
|
||||
@@ -1,19 +1,64 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useAIProjectId } from './useAIProjectId';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { ProjectsManager } from '@/lib/ProjectsManager';
|
||||
|
||||
// Mock the useAISettings hook
|
||||
// Mock the hooks and dependencies
|
||||
vi.mock('./useAISettings');
|
||||
vi.mock('./useCurrentUser');
|
||||
vi.mock('./useProjectsManager');
|
||||
vi.mock('@/lib/ai-client');
|
||||
vi.mock('@/lib/parseProviderModel');
|
||||
|
||||
describe('useAIProjectId', () => {
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
const mockUseCurrentUser = vi.mocked(useCurrentUser);
|
||||
const mockUseProjectsManager = vi.mocked(useProjectsManager);
|
||||
const mockCreateAIClient = vi.mocked(createAIClient);
|
||||
const mockParseProviderModel = vi.mocked(parseProviderModel);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
|
||||
// Mock useCurrentUser to return undefined user by default
|
||||
mockUseCurrentUser.mockReturnValue({
|
||||
user: undefined,
|
||||
users: [],
|
||||
});
|
||||
|
||||
// Mock useProjectsManager
|
||||
const mockProjectsManager = {
|
||||
getProject: vi.fn().mockResolvedValue(null),
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
// Mock parseProviderModel
|
||||
mockParseProviderModel.mockReturnValue({
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
});
|
||||
|
||||
// Mock createAIClient
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'test-project-name' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
});
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
@@ -46,7 +91,7 @@ describe('useAIProjectId', () => {
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('test prompt')).rejects.toThrow(
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', 'test prompt')).rejects.toThrow(
|
||||
'AI settings not configured'
|
||||
);
|
||||
});
|
||||
@@ -69,7 +114,7 @@ describe('useAIProjectId', () => {
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('')).rejects.toThrow(
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', '')).rejects.toThrow(
|
||||
'Prompt cannot be empty'
|
||||
);
|
||||
});
|
||||
@@ -95,4 +140,177 @@ describe('useAIProjectId', () => {
|
||||
expect(result.current.isConfigured).toBe(true);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should successfully generate project ID', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('test-project-name');
|
||||
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
});
|
||||
expect(mockCreateAIClient).toHaveBeenCalledWith(
|
||||
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
it('should retry with new names when project exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock multiple responses - first one exists, second one is unique
|
||||
const mockCompletion1 = {
|
||||
choices: [{ message: { content: 'existing-project' } }]
|
||||
};
|
||||
const mockCompletion2 = {
|
||||
choices: [{ message: { content: 'unique-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn()
|
||||
.mockResolvedValueOnce(mockCompletion1)
|
||||
.mockResolvedValueOnce(mockCompletion2)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - first call returns project (exists), second returns null (unique)
|
||||
const mockGetProject = vi.fn()
|
||||
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('unique-project');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(2);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'unique-project');
|
||||
|
||||
// Should have called AI twice - once for initial name, once for retry
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Second call should include the "already taken" message
|
||||
const mockCreate = mockOpenAI.chat.completions.create as ReturnType<typeof vi.fn>;
|
||||
const secondCallArgs = mockCreate.mock.calls[1][0];
|
||||
expect(secondCallArgs.messages).toHaveLength(3);
|
||||
expect(secondCallArgs.messages[2].content).toContain('already taken');
|
||||
});
|
||||
|
||||
it('should throw error after maximum iterations', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to always return the same name
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'taken-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject to always return a project (project always exists)
|
||||
const mockGetProject = vi.fn().mockResolvedValue({
|
||||
id: 'taken-project',
|
||||
name: 'Taken Project',
|
||||
path: '/projects/taken-project',
|
||||
lastModified: new Date()
|
||||
});
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', 'A social media app for developers'))
|
||||
.rejects.toThrow('Failed to generate a unique project name after 3 attempts');
|
||||
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(3);
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should handle loading state correctly', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
|
||||
const promise = result.current.generateProjectId('openai/gpt-4', 'Test prompt');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false); // Should be false after completion
|
||||
});
|
||||
|
||||
await promise;
|
||||
});
|
||||
});
|
||||
+62
-49
@@ -1,6 +1,9 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
|
||||
interface UseAIProjectIdOptions {
|
||||
onError?: (error: string) => void;
|
||||
@@ -9,8 +12,10 @@ interface UseAIProjectIdOptions {
|
||||
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const generateProjectId = useCallback(async (prompt: string): Promise<string> => {
|
||||
const generateProjectId = useCallback(async (providerModel: string, prompt: string): Promise<string> => {
|
||||
if (!isConfigured) {
|
||||
throw new Error('AI settings not configured');
|
||||
}
|
||||
@@ -22,61 +27,69 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Use first available provider as fallback
|
||||
const providers = settings.providers || {};
|
||||
const firstProvider = Object.keys(providers)[0];
|
||||
if (!firstProvider) {
|
||||
throw new Error('No configured AI providers available');
|
||||
}
|
||||
|
||||
const connectionConfig = providers[firstProvider];
|
||||
const modelName = 'gpt-3.5-turbo'; // Use a fast, cheap model for ID generation
|
||||
|
||||
// Initialize OpenAI client
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
const { model, connection } = parseProviderModel(providerModel, settings.providers);
|
||||
const openai = createAIClient(connection, user);
|
||||
|
||||
const systemPrompt = `You are a project ID generator. Given a user's description of what they want to build, generate a short, descriptive, kebab-case project ID that captures the essence of their project.
|
||||
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
|
||||
|
||||
Rules:
|
||||
- Use only lowercase letters, numbers, and hyphens
|
||||
- Keep it between 2-4 words
|
||||
- Make it descriptive but concise
|
||||
- No spaces, underscores, or special characters except hyphens
|
||||
- Examples:
|
||||
- "farming equipment marketplace" → "farming-marketplace"
|
||||
- "social media for artists" → "artist-social-app"
|
||||
- "crypto trading dashboard" → "crypto-dashboard"
|
||||
- "recipe sharing platform" → "recipe-platform"
|
||||
const messages = [
|
||||
{ role: 'system' as const, content: systemPrompt },
|
||||
{ role: 'user' as const, content: prompt }
|
||||
];
|
||||
|
||||
Respond with ONLY the project ID, no explanation or additional text.`;
|
||||
let iterations = 0;
|
||||
const maxIterations = 3;
|
||||
|
||||
const completion = await openai.chat.completions.create({
|
||||
model: modelName,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
max_tokens: 20,
|
||||
temperature: 0.3,
|
||||
});
|
||||
while (iterations < maxIterations) {
|
||||
iterations++;
|
||||
|
||||
const projectId = completion.choices[0]?.message?.content?.trim();
|
||||
const completion = await openai.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
temperature: 1,
|
||||
});
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error('Failed to generate project ID');
|
||||
const projectName = completion.choices[0]?.message?.content?.trim();
|
||||
if (!projectName) {
|
||||
throw new Error('Failed to generate project name');
|
||||
}
|
||||
|
||||
// Convert the name into kebab-case
|
||||
const projectId = projectName
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, '-') // Replace spaces with hyphens
|
||||
.replace(/[^a-z0-9-]/g, '') // Remove invalid characters
|
||||
.replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen
|
||||
.replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error('Generated project ID is empty after formatting');
|
||||
}
|
||||
|
||||
// Validate the generated ID
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (!validIdRegex.test(projectId)) {
|
||||
throw new Error('Generated project ID is invalid');
|
||||
}
|
||||
|
||||
// Check if project exists
|
||||
const existingProject = await projectsManager.getProject(projectId);
|
||||
if (existingProject !== null) {
|
||||
// Add user message indicating the name is already taken
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content: `The name "${projectName}" (project ID: ${projectId}) is already taken. Please generate another unique name.`
|
||||
});
|
||||
continue; // Try again with updated conversation
|
||||
}
|
||||
|
||||
// If we reach here, the project ID is valid and unique
|
||||
return projectId;
|
||||
}
|
||||
|
||||
// Validate the generated ID
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (!validIdRegex.test(projectId)) {
|
||||
throw new Error('Generated project ID is invalid');
|
||||
}
|
||||
|
||||
return projectId;
|
||||
// If we've exceeded max iterations, throw an error
|
||||
throw new Error(`Failed to generate a unique project name after ${maxIterations} attempts`);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
@@ -84,7 +97,7 @@ Respond with ONLY the project ID, no explanation or additional text.`;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isConfigured, settings, onError]);
|
||||
}, [isConfigured, settings, onError, user, projectsManager]);
|
||||
|
||||
return {
|
||||
generateProjectId,
|
||||
|
||||
@@ -25,6 +25,11 @@ export function useCurrentUser() {
|
||||
const users = useMemo(() => {
|
||||
const users: NUser[] = [];
|
||||
|
||||
// Safeguard against undefined or null logins
|
||||
if (!logins || !Array.isArray(logins)) {
|
||||
return users;
|
||||
}
|
||||
|
||||
for (const login of logins) {
|
||||
try {
|
||||
const user = loginToUser(login);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useGit } from './useGit';
|
||||
import { useFS } from './useFS';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock('./useFS');
|
||||
vi.mock('./useGitSettings');
|
||||
vi.mock('@/lib/git');
|
||||
|
||||
const mockUseFS = vi.mocked(useFS);
|
||||
const mockUseGitSettings = vi.mocked(useGitSettings);
|
||||
const MockGit = vi.mocked(Git);
|
||||
|
||||
describe('useGit', () => {
|
||||
const mockFS = {} as JSRuntimeFS;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockUseFS.mockReturnValue({ fs: mockFS });
|
||||
});
|
||||
|
||||
it('creates Git instance with default CORS proxy', () => {
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
renderHook(() => useGit());
|
||||
|
||||
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
|
||||
});
|
||||
|
||||
it('creates Git instance with custom CORS proxy', () => {
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
renderHook(() => useGit());
|
||||
|
||||
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://custom-cors.example.com');
|
||||
});
|
||||
|
||||
it('recreates Git instance when CORS proxy changes', () => {
|
||||
const { rerender } = renderHook(() => useGit());
|
||||
|
||||
// First render with default proxy
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
rerender();
|
||||
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
|
||||
|
||||
// Second render with custom proxy
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
rerender();
|
||||
expect(MockGit).toHaveBeenLastCalledWith(mockFS, 'https://custom-cors.example.com');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Git } from '@/lib/git';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
|
||||
/**
|
||||
* Hook that provides a Git instance configured with the virtual filesystem
|
||||
* and configurable CORS proxy for GitHub/GitLab repositories.
|
||||
*/
|
||||
export function useGit() {
|
||||
const { fs } = useFS();
|
||||
const { settings } = useGitSettings();
|
||||
|
||||
const git = useMemo(() => {
|
||||
return new Git(fs, settings.corsProxy);
|
||||
}, [fs, settings.corsProxy]);
|
||||
|
||||
return git;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
|
||||
interface GitHubOAuthState {
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface GitHubTokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
export function useGitHubOAuth() {
|
||||
const [state, setState] = useState<GitHubOAuthState>({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { addCredential } = useGitSettings();
|
||||
|
||||
// Check if OAuth is configured
|
||||
const isOAuthConfigured = !!(
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID &&
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
|
||||
);
|
||||
|
||||
const initiateOAuth = useCallback(() => {
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
|
||||
if (!clientId) {
|
||||
setState(prev => ({ ...prev, error: 'GitHub OAuth client ID not configured' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
localStorage.setItem('github_oauth_state', state);
|
||||
|
||||
// Redirect to GitHub OAuth
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/',
|
||||
scope: 'repo',
|
||||
state: state,
|
||||
});
|
||||
|
||||
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
|
||||
}, []);
|
||||
|
||||
const handleCallback = useCallback(async (code: string, state: string) => {
|
||||
setState(prev => ({ ...prev, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
// Verify state parameter
|
||||
const storedState = localStorage.getItem('github_oauth_state');
|
||||
if (!storedState || storedState !== state) {
|
||||
throw new Error('Invalid OAuth state parameter');
|
||||
}
|
||||
|
||||
// Clean up stored state
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
|
||||
|
||||
if (!clientId || !clientSecret) {
|
||||
throw new Error('GitHub OAuth credentials not configured');
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
throw new Error(`GitHub OAuth token exchange failed: ${tokenResponse.statusText}`);
|
||||
}
|
||||
|
||||
const tokenData: GitHubTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.access_token) {
|
||||
throw new Error('No access token received from GitHub');
|
||||
}
|
||||
|
||||
// Get user info to verify the token works
|
||||
const userResponse = await fetch('https://corsproxy.io/?url=https://api.github.com/user', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokenData.access_token}`,
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify GitHub token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData = await userResponse.json();
|
||||
|
||||
// Store the credentials
|
||||
addCredential('https://github.com', {
|
||||
username: userData.login || 'git',
|
||||
password: tokenData.access_token,
|
||||
});
|
||||
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('GitHub OAuth error:', error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'OAuth authentication failed'
|
||||
}));
|
||||
return false;
|
||||
}
|
||||
}, [addCredential]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useContext } from 'react';
|
||||
import { GitSettingsContext, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
|
||||
/**
|
||||
* Hook to access and update Git settings
|
||||
* @returns Git settings context with settings and update methods
|
||||
*/
|
||||
export function useGitSettings(): GitSettingsContextType {
|
||||
const context = useContext(GitSettingsContext);
|
||||
if (!context) {
|
||||
throw new Error('useGitSettings must be used within GitSettingsProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
+52
-19
@@ -1,6 +1,5 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import git from 'isomorphic-git';
|
||||
import { useFS } from './useFS';
|
||||
import { useGit } from './useGit';
|
||||
|
||||
interface GitFileChange {
|
||||
filepath: string;
|
||||
@@ -41,7 +40,7 @@ interface GitStatus {
|
||||
}
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
const { fs } = useFS();
|
||||
const git = useGit();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['git-status', projectId],
|
||||
@@ -66,7 +65,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await fs.stat(`${cwd}/.git`);
|
||||
await git.findRoot({ filepath: cwd });
|
||||
} catch {
|
||||
return {
|
||||
hasUncommittedChanges: false,
|
||||
@@ -86,7 +85,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
const branch = await git.currentBranch({
|
||||
fs,
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
@@ -99,7 +97,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
const branches: string[] = [];
|
||||
try {
|
||||
const allBranches = await git.listBranches({
|
||||
fs,
|
||||
dir: cwd,
|
||||
});
|
||||
branches.push(...allBranches);
|
||||
@@ -112,7 +109,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
let totalCommits = 0;
|
||||
try {
|
||||
const commits = await git.log({
|
||||
fs,
|
||||
dir: cwd,
|
||||
depth: 1,
|
||||
});
|
||||
@@ -137,7 +133,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
|
||||
// Get total commit count
|
||||
const allCommits = await git.log({
|
||||
fs,
|
||||
dir: cwd,
|
||||
});
|
||||
totalCommits = allCommits.length;
|
||||
@@ -149,7 +144,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
const remotes: GitRemote[] = [];
|
||||
try {
|
||||
const remoteNames = await git.listRemotes({
|
||||
fs,
|
||||
dir: cwd,
|
||||
});
|
||||
|
||||
@@ -165,7 +159,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
|
||||
// Get git status to see what files have changed
|
||||
const statusMatrix = await git.statusMatrix({
|
||||
fs,
|
||||
dir: cwd,
|
||||
});
|
||||
|
||||
@@ -196,18 +189,58 @@ export function useGitStatus(projectId: string | null) {
|
||||
});
|
||||
}
|
||||
|
||||
// Calculate ahead/behind (simplified - would need remote tracking branch info)
|
||||
const ahead = 0;
|
||||
const behind = 0;
|
||||
// Calculate ahead/behind
|
||||
let ahead = 0;
|
||||
let behind = 0;
|
||||
try {
|
||||
// This is a simplified calculation - in a real implementation,
|
||||
// you'd compare with the remote tracking branch
|
||||
if (currentBranch && remotes.length > 0) {
|
||||
// For now, we'll leave these as 0 since calculating ahead/behind
|
||||
// requires more complex remote branch comparison
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
const remoteBranchName = `${remote.name}/${currentBranch}`;
|
||||
|
||||
try {
|
||||
// Try to get the remote branch reference
|
||||
const remoteRef = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: remoteBranchName,
|
||||
});
|
||||
|
||||
const localRef = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
if (remoteRef && localRef && remoteRef !== localRef) {
|
||||
// Get commits between local and remote
|
||||
const localCommits = await git.log({
|
||||
dir: cwd,
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
const remoteCommits = await git.log({
|
||||
dir: cwd,
|
||||
ref: remoteBranchName,
|
||||
});
|
||||
|
||||
// Find commits that are in local but not in remote (ahead)
|
||||
const remoteCommitOids = new Set(remoteCommits.map(c => c.oid));
|
||||
const localOnlyCommits = localCommits.filter(c => !remoteCommitOids.has(c.oid));
|
||||
ahead = localOnlyCommits.length;
|
||||
|
||||
// Find commits that are in remote but not in local (behind)
|
||||
const localCommitOids = new Set(localCommits.map(c => c.oid));
|
||||
const remoteOnlyCommits = remoteCommits.filter(c => !localCommitOids.has(c.oid));
|
||||
behind = remoteOnlyCommits.length;
|
||||
}
|
||||
} catch {
|
||||
// Remote branch might not exist or other issues
|
||||
// If we can't find remote branch, assume we're ahead if we have commits
|
||||
if (totalCommits > 0) {
|
||||
ahead = totalCommits;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not calculate ahead/behind:', error);
|
||||
} catch (err) {
|
||||
console.warn('Could not calculate ahead/behind:', err);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+12
-12
@@ -1,19 +1,19 @@
|
||||
import * as React from "react"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
export function useIsMobile(): boolean {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
mql.addEventListener("change", onChange);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
return !!isMobile
|
||||
return !!isMobile;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { useContext } from 'react';
|
||||
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
|
||||
|
||||
/**
|
||||
* Hook to access the JavaScript runtime
|
||||
* @returns JSRuntime context with runtime instance
|
||||
*/
|
||||
export function useJSRuntime(): JSRuntimeContextType {
|
||||
const context = useContext(JSRuntimeContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useJSRuntime must be used within a JSRuntimeProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
/**
|
||||
* Generic hook for managing localStorage state
|
||||
* Generic hook for managing localStorage state using React Query
|
||||
*/
|
||||
export function useLocalStorage<T>(
|
||||
key: string,
|
||||
@@ -10,11 +11,13 @@ export function useLocalStorage<T>(
|
||||
serialize: (value: T) => string;
|
||||
deserialize: (value: string) => T;
|
||||
}
|
||||
) {
|
||||
): readonly [T, (value: T | ((prev: T) => T)) => void] {
|
||||
const serialize = serializer?.serialize || JSON.stringify;
|
||||
const deserialize = serializer?.deserialize || JSON.parse;
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [state, setState] = useState<T>(() => {
|
||||
const queryFn = () => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? deserialize(item) : defaultValue;
|
||||
@@ -22,13 +25,22 @@ export function useLocalStorage<T>(
|
||||
console.warn(`Failed to load ${key} from localStorage:`, error);
|
||||
return defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
const { data: state } = useQuery({
|
||||
queryKey: ['localStorage', key],
|
||||
queryFn,
|
||||
initialData: queryFn,
|
||||
staleTime: Infinity, // localStorage data doesn't become stale
|
||||
gcTime: Infinity, // Keep in cache indefinitely
|
||||
});
|
||||
|
||||
const setValue = (value: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(state) : value;
|
||||
setState(valueToStore);
|
||||
const currentValue = state ?? defaultValue;
|
||||
const valueToStore = value instanceof Function ? value(currentValue) : value;
|
||||
localStorage.setItem(key, serialize(valueToStore));
|
||||
queryClient.setQueryData(['localStorage', key], valueToStore);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to save ${key} to localStorage:`, error);
|
||||
}
|
||||
@@ -39,7 +51,8 @@ export function useLocalStorage<T>(
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === key && e.newValue !== null) {
|
||||
try {
|
||||
setState(deserialize(e.newValue));
|
||||
const newValue = deserialize(e.newValue);
|
||||
queryClient.setQueryData(['localStorage', key], newValue);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to sync ${key} from localStorage:`, error);
|
||||
}
|
||||
@@ -48,7 +61,7 @@ export function useLocalStorage<T>(
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [key, deserialize]);
|
||||
}, [key, deserialize, queryClient]);
|
||||
|
||||
return [state, setValue] as const;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { LN } from '@getalby/sdk';
|
||||
|
||||
export interface NWCConnection {
|
||||
connectionString: string;
|
||||
alias?: string;
|
||||
isConnected: boolean;
|
||||
client?: LN;
|
||||
}
|
||||
|
||||
export interface NWCInfo {
|
||||
alias?: string;
|
||||
color?: string;
|
||||
pubkey?: string;
|
||||
network?: string;
|
||||
methods?: string[];
|
||||
notifications?: string[];
|
||||
}
|
||||
|
||||
export function useNWCInternal() {
|
||||
const { toast } = useToast();
|
||||
const [connections, setConnections] = useLocalStorage<NWCConnection[]>('nwc-connections', []);
|
||||
const [activeConnection, setActiveConnection] = useLocalStorage<string | null>('nwc-active-connection', null);
|
||||
const [connectionInfo, setConnectionInfo] = useState<Record<string, NWCInfo>>({});
|
||||
|
||||
// Add new connection
|
||||
const addConnection = async (uri: string, alias?: string): Promise<boolean> => {
|
||||
const parseNWCUri = (uri: string): { connectionString: string } | null => {
|
||||
try {
|
||||
if (!uri.startsWith('nostr+walletconnect://') && !uri.startsWith('nostrwalletconnect://')) {
|
||||
console.error('Invalid NWC URI protocol:', { protocol: uri.split('://')[0] });
|
||||
return null;
|
||||
}
|
||||
return { connectionString: uri };
|
||||
} catch (error) {
|
||||
console.error('Failed to parse NWC URI:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const parsed = parseNWCUri(uri);
|
||||
if (!parsed) {
|
||||
toast({
|
||||
title: 'Invalid NWC URI',
|
||||
description: 'Please check the connection string and try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const existingConnection = connections.find(c => c.connectionString === parsed.connectionString);
|
||||
if (existingConnection) {
|
||||
toast({
|
||||
title: 'Connection already exists',
|
||||
description: 'This wallet is already connected.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
const testPromise = new Promise((resolve, reject) => {
|
||||
try {
|
||||
const client = new LN(parsed.connectionString);
|
||||
resolve(client);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Connection test timeout')), 10000);
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.race([testPromise, timeoutPromise]) as LN;
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
} catch (error) {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const connection: NWCConnection = {
|
||||
connectionString: parsed.connectionString,
|
||||
alias: alias || 'NWC Wallet',
|
||||
isConnected: true,
|
||||
};
|
||||
|
||||
setConnectionInfo(prev => ({
|
||||
...prev,
|
||||
[parsed.connectionString]: {
|
||||
alias: connection.alias,
|
||||
methods: ['pay_invoice'],
|
||||
},
|
||||
}));
|
||||
|
||||
const newConnections = [...connections, connection];
|
||||
setConnections(newConnections);
|
||||
|
||||
if (connections.length === 0 || !activeConnection)
|
||||
setActiveConnection(parsed.connectionString);
|
||||
|
||||
toast({
|
||||
title: 'Wallet connected',
|
||||
description: `Successfully connected to ${connection.alias}.`,
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('NWC connection failed:', error);
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
|
||||
toast({
|
||||
title: 'Connection failed',
|
||||
description: `Could not connect to the wallet: ${errorMessage}`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Remove connection
|
||||
const removeConnection = (connectionString: string) => {
|
||||
const filtered = connections.filter(c => c.connectionString !== connectionString);
|
||||
setConnections(filtered);
|
||||
|
||||
if (activeConnection === connectionString) {
|
||||
const newActive = filtered.length > 0 ? filtered[0].connectionString : null;
|
||||
setActiveConnection(newActive);
|
||||
}
|
||||
|
||||
setConnectionInfo(prev => {
|
||||
const newInfo = { ...prev };
|
||||
delete newInfo[connectionString];
|
||||
return newInfo;
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Wallet disconnected',
|
||||
description: 'The wallet connection has been removed.',
|
||||
});
|
||||
};
|
||||
|
||||
// Get active connection
|
||||
const getActiveConnection = useCallback((): NWCConnection | null => {
|
||||
if (!activeConnection && connections.length > 0) {
|
||||
setActiveConnection(connections[0].connectionString);
|
||||
return connections[0];
|
||||
}
|
||||
|
||||
if (!activeConnection) return null;
|
||||
|
||||
const found = connections.find(c => c.connectionString === activeConnection);
|
||||
return found || null;
|
||||
}, [activeConnection, connections, setActiveConnection]);
|
||||
|
||||
// Send payment using the SDK
|
||||
const sendPayment = useCallback(async (
|
||||
connection: NWCConnection,
|
||||
invoice: string
|
||||
): Promise<{ preimage: string }> => {
|
||||
if (!connection.connectionString) {
|
||||
throw new Error('Invalid connection: missing connection string');
|
||||
}
|
||||
|
||||
let client: LN;
|
||||
try {
|
||||
client = new LN(connection.connectionString);
|
||||
} catch (error) {
|
||||
console.error('Failed to create NWC client:', error);
|
||||
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
try {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Payment timeout after 15 seconds')), 15000);
|
||||
});
|
||||
|
||||
const paymentPromise = client.pay(invoice);
|
||||
|
||||
try {
|
||||
const response = await Promise.race([paymentPromise, timeoutPromise]) as { preimage: string };
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('NWC payment failed:', error);
|
||||
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('timeout')) {
|
||||
throw new Error('Payment timed out. Please try again.');
|
||||
} else if (error.message.includes('insufficient')) {
|
||||
throw new Error('Insufficient balance in connected wallet.');
|
||||
} else if (error.message.includes('invalid')) {
|
||||
throw new Error('Invalid invoice or connection. Please check your wallet.');
|
||||
} else {
|
||||
throw new Error(`Payment failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Payment failed with unknown error');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection,
|
||||
getActiveConnection,
|
||||
sendPayment,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useContext } from 'react';
|
||||
import { createContext } from 'react';
|
||||
import { useNWCInternal } from '@/hooks/useNWC';
|
||||
|
||||
type NWCContextType = ReturnType<typeof useNWCInternal>;
|
||||
|
||||
export const NWCContext = createContext<NWCContextType | null>(null);
|
||||
|
||||
export function useNWC(): NWCContextType {
|
||||
const context = useContext(NWCContext);
|
||||
if (!context) {
|
||||
throw new Error('useNWC must be used within a NWCProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -11,11 +11,10 @@ export function useProjectSessionStatus(projectId: string) {
|
||||
|
||||
useEffect(() => {
|
||||
const updateStatus = () => {
|
||||
const projectSessions = sessionManager.getProjectSessions(projectId);
|
||||
const runningSessions = projectSessions.filter(session => session.isLoading);
|
||||
|
||||
setHasActiveSessions(projectSessions.length > 0);
|
||||
setHasRunningSessions(runningSessions.length > 0);
|
||||
const projectSession = sessionManager.getSession(projectId);
|
||||
|
||||
setHasActiveSessions(!!projectSession);
|
||||
setHasRunningSessions(!!projectSession?.isLoading);
|
||||
};
|
||||
|
||||
// Initial update
|
||||
@@ -23,13 +22,11 @@ export function useProjectSessionStatus(projectId: string) {
|
||||
|
||||
// Subscribe to session changes
|
||||
sessionManager.on('sessionCreated', updateStatus);
|
||||
sessionManager.on('sessionUpdated', updateStatus);
|
||||
sessionManager.on('sessionDeleted', updateStatus);
|
||||
sessionManager.on('loadingChanged', updateStatus);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('sessionCreated', updateStatus);
|
||||
sessionManager.off('sessionUpdated', updateStatus);
|
||||
sessionManager.off('sessionDeleted', updateStatus);
|
||||
sessionManager.off('loadingChanged', updateStatus);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React, { type ReactNode } from 'react';
|
||||
import { useProjects } from './useProjects';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
|
||||
// Create a test wrapper that provides a fresh QueryClient for each test
|
||||
function createTestWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// Mock the useProjectsManager hook
|
||||
vi.mock('./useProjectsManager', () => ({
|
||||
useProjectsManager: () => ({
|
||||
init: vi.fn().mockResolvedValue(undefined),
|
||||
getProjects: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Project 1',
|
||||
lastModified: new Date('2023-01-01'),
|
||||
},
|
||||
{
|
||||
id: 'project-2',
|
||||
name: 'Project 2',
|
||||
lastModified: new Date('2023-01-02'),
|
||||
},
|
||||
{
|
||||
id: 'project-3',
|
||||
name: 'Project 3',
|
||||
lastModified: new Date('2023-01-03'),
|
||||
},
|
||||
] as Project[]),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the useLocalStorage hook
|
||||
let mockFavorites: string[] = [];
|
||||
vi.mock('./useLocalStorage', () => ({
|
||||
useLocalStorage: vi.fn((key: string, defaultValue: unknown) => {
|
||||
if (key === 'project-favorites') {
|
||||
return [mockFavorites, vi.fn()];
|
||||
}
|
||||
return [defaultValue, vi.fn()];
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('useProjects', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockFavorites = [];
|
||||
});
|
||||
|
||||
it('should load and return projects', async () => {
|
||||
const { result } = renderHook(() => useProjects(), {
|
||||
wrapper: createTestWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toHaveLength(3);
|
||||
expect(result.current.data?.[0].name).toBe('Project 3'); // Most recent first
|
||||
});
|
||||
|
||||
it('should sort favorites first, then by lastModified', async () => {
|
||||
// Set favorites to include project-1
|
||||
mockFavorites = ['project-1'];
|
||||
|
||||
const { result } = renderHook(() => useProjects(), {
|
||||
wrapper: createTestWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toHaveLength(3);
|
||||
expect(result.current.data?.[0].id).toBe('project-1'); // Favorite first
|
||||
expect(result.current.data?.[1].id).toBe('project-3'); // Then most recent
|
||||
expect(result.current.data?.[2].id).toBe('project-2'); // Then older
|
||||
});
|
||||
|
||||
it('should handle multiple favorites correctly', async () => {
|
||||
// Set favorites to include project-1 and project-2
|
||||
mockFavorites = ['project-1', 'project-2'];
|
||||
|
||||
const { result } = renderHook(() => useProjects(), {
|
||||
wrapper: createTestWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toHaveLength(3);
|
||||
// Favorites should be sorted by lastModified among themselves
|
||||
expect(result.current.data?.[0].id).toBe('project-2'); // Favorite + more recent
|
||||
expect(result.current.data?.[1].id).toBe('project-1'); // Favorite + older
|
||||
expect(result.current.data?.[2].id).toBe('project-3'); // Not favorite
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
|
||||
export function useProjects() {
|
||||
const projectsManager = useProjectsManager();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['projects'],
|
||||
queryFn: async (): Promise<Project[]> => {
|
||||
await projectsManager.init();
|
||||
const projects = await projectsManager.getProjects();
|
||||
|
||||
// Sort projects: favorites first, then by lastModified (newest first)
|
||||
return projects.sort((a, b) => {
|
||||
const aIsFavorite = favorites.includes(a.id);
|
||||
const bIsFavorite = favorites.includes(b.id);
|
||||
|
||||
if (aIsFavorite && !bIsFavorite) return -1;
|
||||
if (!aIsFavorite && bIsFavorite) return 1;
|
||||
|
||||
return b.lastModified.getTime() - a.lastModified.getTime();
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,24 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
|
||||
interface ProviderModel {
|
||||
id: string;
|
||||
name: string;
|
||||
provider: string;
|
||||
fullId: string; // provider/model format
|
||||
/** Maximum size of context window, if available */
|
||||
contextLength?: number;
|
||||
/** Pricing information, if available */
|
||||
pricing?: {
|
||||
/** Input/prompt pricing per token */
|
||||
prompt: Decimal;
|
||||
/** Output/completion pricing per token */
|
||||
completion: Decimal;
|
||||
}
|
||||
}
|
||||
|
||||
interface ModelFetchResult {
|
||||
@@ -19,26 +30,22 @@ interface ModelFetchResult {
|
||||
|
||||
export function useProviderModels(): ModelFetchResult {
|
||||
const { settings } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
data: models = [],
|
||||
isLoading,
|
||||
refetch: queryRefetch,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['provider-models', settings.providers],
|
||||
queryKey: ['provider-models'],
|
||||
queryFn: async () => {
|
||||
const allModels: ProviderModel[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
// Fetch models from each configured provider
|
||||
for (const [providerKey, connection] of Object.entries(settings.providers)) {
|
||||
// Fetch models from each configured provider in parallel
|
||||
const providerPromises = Object.entries(settings.providers).map(async ([providerKey, connection]) => {
|
||||
try {
|
||||
const openai = new OpenAI({
|
||||
baseURL: connection.baseURL,
|
||||
apiKey: connection.apiKey,
|
||||
dangerouslyAllowBrowser: true,
|
||||
});
|
||||
const openai = createAIClient(connection, user);
|
||||
|
||||
// Fetch models with timeout
|
||||
try {
|
||||
@@ -47,20 +54,43 @@ export function useProviderModels(): ModelFetchResult {
|
||||
});
|
||||
|
||||
// Transform models to our format
|
||||
const providerModels = response.data.map((model) => ({
|
||||
id: model.id,
|
||||
name: model.id,
|
||||
provider: providerKey,
|
||||
fullId: `${providerKey}/${model.id}`,
|
||||
}));
|
||||
const providerModels = response.data.map((model) => {
|
||||
const providerModel: ProviderModel = {
|
||||
id: model.id,
|
||||
name: model.id,
|
||||
provider: providerKey,
|
||||
fullId: `${providerKey}/${model.id}`,
|
||||
};
|
||||
|
||||
allModels.push(...providerModels);
|
||||
if ('context_length' in model && typeof model.context_length === 'number') {
|
||||
providerModel.contextLength = model.context_length;
|
||||
}
|
||||
|
||||
if (
|
||||
"pricing" in model && model.pricing && typeof model.pricing === "object" &&
|
||||
"prompt" in model.pricing && "completion" in model.pricing &&
|
||||
typeof model.pricing.prompt === "string" &&
|
||||
typeof model.pricing.completion === "string" &&
|
||||
!isNaN(Number(model.pricing.prompt)) &&
|
||||
!isNaN(Number(model.pricing.completion))
|
||||
) {
|
||||
providerModel.pricing = {
|
||||
prompt: new Decimal(model.pricing.prompt),
|
||||
completion: new Decimal(model.pricing.completion),
|
||||
};
|
||||
}
|
||||
|
||||
return providerModel;
|
||||
});
|
||||
|
||||
return providerModels;
|
||||
} catch (fetchError) {
|
||||
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
|
||||
errors.push(`${providerKey}: Request timeout`);
|
||||
} else {
|
||||
throw fetchError;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
} catch (providerError) {
|
||||
console.warn(`Failed to fetch models from ${providerKey}:`, providerError);
|
||||
@@ -69,8 +99,15 @@ export function useProviderModels(): ModelFetchResult {
|
||||
providerError instanceof Error ? providerError.message : 'Unknown error'
|
||||
}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for all provider requests to complete
|
||||
const providerResults = await Promise.all(providerPromises);
|
||||
|
||||
// Flatten all models into a single array
|
||||
const allModels = providerResults.flat();
|
||||
|
||||
// Set error state if there were any errors
|
||||
if (errors.length > 0) {
|
||||
@@ -79,14 +116,6 @@ export function useProviderModels(): ModelFetchResult {
|
||||
setError(null);
|
||||
}
|
||||
|
||||
// Sort models by provider, then by name
|
||||
allModels.sort((a, b) => {
|
||||
if (a.provider !== b.provider) {
|
||||
return a.provider.localeCompare(b.provider);
|
||||
}
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return allModels;
|
||||
},
|
||||
enabled: Object.keys(settings.providers).length > 0,
|
||||
@@ -94,11 +123,6 @@ export function useProviderModels(): ModelFetchResult {
|
||||
retry: false, // Don't retry on failure
|
||||
});
|
||||
|
||||
const refetch = useCallback(() => {
|
||||
setError(null);
|
||||
queryRefetch();
|
||||
}, [queryRefetch]);
|
||||
|
||||
return {
|
||||
models,
|
||||
isLoading,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { requestProvider } from 'webln';
|
||||
|
||||
export interface WalletStatus {
|
||||
hasWebLN: boolean;
|
||||
hasNWC: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
||||
isDetecting: boolean;
|
||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
||||
}
|
||||
|
||||
export function useWallet() {
|
||||
const [webln, setWebln] = useState<WebLNProvider | null>(null);
|
||||
const [isDetecting, setIsDetecting] = useState(false);
|
||||
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
|
||||
const { connections, getActiveConnection } = useNWC();
|
||||
|
||||
// Get the active connection directly - no memoization to avoid stale state
|
||||
const activeNWC = getActiveConnection();
|
||||
|
||||
// Detect WebLN
|
||||
const detectWebLN = useCallback(async () => {
|
||||
if (webln || isDetecting) return webln;
|
||||
|
||||
setIsDetecting(true);
|
||||
try {
|
||||
const provider = await requestProvider();
|
||||
setWebln(provider);
|
||||
setHasAttemptedDetection(true);
|
||||
return provider;
|
||||
} catch (error) {
|
||||
// Only log the error if it's not the common "no provider" error
|
||||
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
|
||||
console.warn('WebLN detection error:', error);
|
||||
}
|
||||
setWebln(null);
|
||||
setHasAttemptedDetection(true);
|
||||
return null;
|
||||
} finally {
|
||||
setIsDetecting(false);
|
||||
}
|
||||
}, [webln, isDetecting]);
|
||||
|
||||
// Only auto-detect once on mount
|
||||
useEffect(() => {
|
||||
if (!hasAttemptedDetection) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [detectWebLN, hasAttemptedDetection]);
|
||||
|
||||
// Test WebLN connection
|
||||
const testWebLN = useCallback(async (): Promise<boolean> => {
|
||||
if (!webln) return false;
|
||||
|
||||
try {
|
||||
await webln.enable();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('WebLN test failed:', error);
|
||||
return false;
|
||||
}
|
||||
}, [webln]);
|
||||
|
||||
// Calculate status values reactively
|
||||
const hasNWC = useMemo(() => {
|
||||
return connections.length > 0 && connections.some(c => c.isConnected);
|
||||
}, [connections]);
|
||||
|
||||
// Determine preferred payment method
|
||||
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
|
||||
? 'nwc'
|
||||
: webln
|
||||
? 'webln'
|
||||
: 'manual';
|
||||
|
||||
const status: WalletStatus = {
|
||||
hasWebLN: !!webln,
|
||||
hasNWC,
|
||||
webln,
|
||||
activeNWC,
|
||||
isDetecting,
|
||||
preferredMethod,
|
||||
};
|
||||
|
||||
return {
|
||||
...status,
|
||||
hasAttemptedDetection,
|
||||
detectWebLN,
|
||||
testWebLN,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
import { useState, useMemo, useEffect, useCallback } from 'react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import type { NWCConnection } from '@/hooks/useNWC';
|
||||
import { nip57 } from 'nostr-tools';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
export function useZaps(
|
||||
target: Event | Event[],
|
||||
webln: WebLNProvider | null,
|
||||
_nwcConnection: NWCConnection | null,
|
||||
onZapSuccess?: () => void
|
||||
) {
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Handle the case where an empty array is passed (from ZapButton when external data is provided)
|
||||
const actualTarget = Array.isArray(target) ? (target.length > 0 ? target[0] : null) : target;
|
||||
|
||||
const author = useAuthor(actualTarget?.pubkey);
|
||||
const { sendPayment, getActiveConnection } = useNWC();
|
||||
const [isZapping, setIsZapping] = useState(false);
|
||||
const [invoice, setInvoice] = useState<string | null>(null);
|
||||
|
||||
// Cleanup state when component unmounts
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const { data: zapEvents, ...query } = useQuery<NostrEvent[], Error>({
|
||||
queryKey: ['zaps', actualTarget?.id],
|
||||
staleTime: 30000, // 30 seconds
|
||||
refetchInterval: (query) => {
|
||||
// Only refetch if the query is currently being observed (component is mounted)
|
||||
return query.getObserversCount() > 0 ? 60000 : false;
|
||||
},
|
||||
queryFn: async (c) => {
|
||||
if (!actualTarget) return [];
|
||||
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||
|
||||
// Query for zap receipts for this specific event
|
||||
if (actualTarget.kind >= 30000 && actualTarget.kind < 40000) {
|
||||
// Addressable event
|
||||
const identifier = actualTarget.tags.find((t) => t[0] === 'd')?.[1] || '';
|
||||
const events = await nostr.query([{
|
||||
kinds: [9735],
|
||||
'#a': [`${actualTarget.kind}:${actualTarget.pubkey}:${identifier}`],
|
||||
}], { signal });
|
||||
return events;
|
||||
} else {
|
||||
// Regular event
|
||||
const events = await nostr.query([{
|
||||
kinds: [9735],
|
||||
'#e': [actualTarget.id],
|
||||
}], { signal });
|
||||
return events;
|
||||
}
|
||||
},
|
||||
enabled: !!actualTarget?.id,
|
||||
});
|
||||
|
||||
// Process zap events into simple counts and totals
|
||||
const { zapCount, totalSats, zaps } = useMemo(() => {
|
||||
if (!zapEvents || !Array.isArray(zapEvents) || !actualTarget) {
|
||||
return { zapCount: 0, totalSats: 0, zaps: [] };
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
let sats = 0;
|
||||
|
||||
zapEvents.forEach(zap => {
|
||||
count++;
|
||||
|
||||
// Try multiple methods to extract the amount:
|
||||
|
||||
// Method 1: amount tag (from zap request, sometimes copied to receipt)
|
||||
const amountTag = zap.tags.find(([name]) => name === 'amount')?.[1];
|
||||
if (amountTag) {
|
||||
const millisats = parseInt(amountTag);
|
||||
sats += Math.floor(millisats / 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
// Method 2: Extract from bolt11 invoice
|
||||
const bolt11Tag = zap.tags.find(([name]) => name === 'bolt11')?.[1];
|
||||
if (bolt11Tag) {
|
||||
try {
|
||||
const invoiceSats = nip57.getSatoshisAmountFromBolt11(bolt11Tag);
|
||||
sats += invoiceSats;
|
||||
return;
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse bolt11 amount:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Method 3: Parse from description (zap request JSON)
|
||||
const descriptionTag = zap.tags.find(([name]) => name === 'description')?.[1];
|
||||
if (descriptionTag) {
|
||||
try {
|
||||
const zapRequest = JSON.parse(descriptionTag);
|
||||
const requestAmountTag = zapRequest.tags?.find(([name]: string[]) => name === 'amount')?.[1];
|
||||
if (requestAmountTag) {
|
||||
const millisats = parseInt(requestAmountTag);
|
||||
sats += Math.floor(millisats / 1000);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse description JSON:', error);
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('Could not extract amount from zap receipt:', zap.id);
|
||||
});
|
||||
|
||||
|
||||
return { zapCount: count, totalSats: sats, zaps: zapEvents };
|
||||
}, [zapEvents, actualTarget]);
|
||||
|
||||
const zap = async (amount: number, comment: string) => {
|
||||
if (amount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsZapping(true);
|
||||
setInvoice(null); // Clear any previous invoice at the start
|
||||
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Login required',
|
||||
description: 'You must be logged in to send a zap.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!actualTarget) {
|
||||
toast({
|
||||
title: 'Event not found',
|
||||
description: 'Could not find the event to zap.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!author.data || !author.data?.metadata || !author.data?.event ) {
|
||||
toast({
|
||||
title: 'Author not found',
|
||||
description: 'Could not find the author of this item.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { lud06, lud16 } = author.data.metadata;
|
||||
if (!lud06 && !lud16) {
|
||||
toast({
|
||||
title: 'Lightning address not found',
|
||||
description: 'The author does not have a lightning address configured.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get zap endpoint using the old reliable method
|
||||
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
|
||||
if (!zapEndpoint) {
|
||||
toast({
|
||||
title: 'Zap endpoint not found',
|
||||
description: 'Could not find a zap endpoint for the author.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
|
||||
const zapRequest = nip57.makeZapRequest({
|
||||
event: actualTarget,
|
||||
amount: zapAmount,
|
||||
relays: [config.relayUrl],
|
||||
comment
|
||||
});
|
||||
|
||||
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
|
||||
if (!user.signer) {
|
||||
throw new Error('No signer available');
|
||||
}
|
||||
const signedZapRequest = await user.signer.signEvent(zapRequest);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
|
||||
const responseData = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
|
||||
}
|
||||
|
||||
const newInvoice = responseData.pr;
|
||||
if (!newInvoice || typeof newInvoice !== 'string') {
|
||||
throw new Error('Lightning service did not return a valid invoice');
|
||||
}
|
||||
|
||||
// Get the current active NWC connection dynamically
|
||||
const currentNWCConnection = getActiveConnection();
|
||||
|
||||
// Try NWC first if available and properly connected
|
||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
||||
try {
|
||||
await sendPayment(currentNWCConnection, newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats via NWC to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
return;
|
||||
} catch (nwcError) {
|
||||
console.error('NWC payment failed, falling back:', nwcError);
|
||||
|
||||
// Show specific NWC error to user for debugging
|
||||
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
|
||||
toast({
|
||||
title: 'NWC payment failed',
|
||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (webln) { // Try WebLN next
|
||||
try {
|
||||
await webln.sendPayment(newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
} catch (weblnError) {
|
||||
console.error('webln payment failed, falling back:', weblnError);
|
||||
|
||||
// Show specific WebLN error to user for debugging
|
||||
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
||||
toast({
|
||||
title: 'WebLN payment failed',
|
||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
|
||||
setInvoice(newInvoice);
|
||||
setIsZapping(false);
|
||||
}
|
||||
} else { // Default - show QR code and manual Lightning URI
|
||||
setInvoice(newInvoice);
|
||||
setIsZapping(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Zap error:', err);
|
||||
toast({
|
||||
title: 'Zap failed',
|
||||
description: (err as Error).message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Zap error:', err);
|
||||
toast({
|
||||
title: 'Zap failed',
|
||||
description: (err as Error).message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetInvoice = useCallback(() => {
|
||||
setInvoice(null);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
zaps,
|
||||
zapCount,
|
||||
totalSats,
|
||||
...query,
|
||||
zap,
|
||||
isZapping,
|
||||
invoice,
|
||||
setInvoice,
|
||||
resetInvoice,
|
||||
};
|
||||
}
|
||||
@@ -188,6 +188,112 @@ invalid json line
|
||||
// Should not throw
|
||||
await expect(dotAI.setHistory('test-session', messages)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('should validate tool messages have matching tool_call_id', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
|
||||
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'I need to use a tool',
|
||||
tool_calls: [{ id: 'call_123', type: 'function', function: { name: 'test_tool', arguments: '{}' } }]
|
||||
},
|
||||
{ role: 'tool', content: 'Tool result', tool_call_id: 'call_123' }
|
||||
];
|
||||
|
||||
// Should not throw for valid messages
|
||||
await expect(dotAI.setHistory('test-session', validMessages)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('should throw error for tool message without preceding assistant message with tool_calls', async () => {
|
||||
const invalidMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{ role: 'assistant', content: 'Response without tool calls' },
|
||||
{ role: 'tool', content: 'Tool result', tool_call_id: 'call_123' }
|
||||
];
|
||||
|
||||
await expect(dotAI.setHistory('test-session', invalidMessages))
|
||||
.rejects.toThrow('Tool message at index 2 with tool_call_id "call_123" must be preceded by an assistant message with a matching tool_call id');
|
||||
});
|
||||
|
||||
it('should throw error for tool message with non-matching tool_call_id', async () => {
|
||||
const invalidMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'I need to use a tool',
|
||||
tool_calls: [{ id: 'call_456', type: 'function', function: { name: 'test_tool', arguments: '{}' } }]
|
||||
},
|
||||
{ role: 'tool', content: 'Tool result', tool_call_id: 'call_123' }
|
||||
];
|
||||
|
||||
await expect(dotAI.setHistory('test-session', invalidMessages))
|
||||
.rejects.toThrow('Tool message at index 2 with tool_call_id "call_123" must be preceded by an assistant message with a matching tool_call id');
|
||||
});
|
||||
|
||||
it('should throw error for tool message without tool_call_id', async () => {
|
||||
const invalidMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'I need to use a tool',
|
||||
tool_calls: [{ id: 'call_123', type: 'function', function: { name: 'test_tool', arguments: '{}' } }]
|
||||
},
|
||||
{ role: 'tool', content: 'Tool result' } as OpenAI.Chat.Completions.ChatCompletionMessageParam
|
||||
];
|
||||
|
||||
await expect(dotAI.setHistory('test-session', invalidMessages))
|
||||
.rejects.toThrow('Tool message at index 2 is missing tool_call_id');
|
||||
});
|
||||
|
||||
it('should validate multiple tool messages correctly', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
|
||||
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'I need to use tools',
|
||||
tool_calls: [
|
||||
{ id: 'call_123', type: 'function', function: { name: 'tool1', arguments: '{}' } },
|
||||
{ id: 'call_456', type: 'function', function: { name: 'tool2', arguments: '{}' } }
|
||||
]
|
||||
},
|
||||
{ role: 'tool', content: 'Tool 1 result', tool_call_id: 'call_123' },
|
||||
{ role: 'tool', content: 'Tool 2 result', tool_call_id: 'call_456' }
|
||||
];
|
||||
|
||||
// Should not throw for valid messages
|
||||
await expect(dotAI.setHistory('test-session', validMessages)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('should allow tool messages to reference tool calls from the most recent assistant message', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
|
||||
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'First request' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'First response',
|
||||
tool_calls: [{ id: 'call_old', type: 'function', function: { name: 'old_tool', arguments: '{}' } }]
|
||||
},
|
||||
{ role: 'tool', content: 'Old tool result', tool_call_id: 'call_old' },
|
||||
{ role: 'user', content: 'Second request' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'Second response',
|
||||
tool_calls: [{ id: 'call_new', type: 'function', function: { name: 'new_tool', arguments: '{}' } }]
|
||||
},
|
||||
{ role: 'tool', content: 'New tool result', tool_call_id: 'call_new' }
|
||||
];
|
||||
|
||||
// Should not throw for valid messages
|
||||
await expect(dotAI.setHistory('test-session', validMessages)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSessionName', () => {
|
||||
|
||||
@@ -86,6 +86,9 @@ export class DotAI {
|
||||
sessionName: string,
|
||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
|
||||
): Promise<void> {
|
||||
// Validate messages before saving
|
||||
this.validateMessages(messages);
|
||||
|
||||
// Only save if history should be enabled based on the new criteria
|
||||
if (!(await this.isEnabled())) {
|
||||
return;
|
||||
@@ -111,6 +114,55 @@ export class DotAI {
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate that tool messages are properly preceded by assistant messages with matching tool calls */
|
||||
private validateMessages(messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): void {
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const message = messages[i];
|
||||
|
||||
// Check if this is a tool message
|
||||
if (message.role === 'tool') {
|
||||
// Tool messages must have tool_call_id
|
||||
if (!('tool_call_id' in message) || !message.tool_call_id) {
|
||||
throw new Error(`Tool message at index ${i} is missing tool_call_id`);
|
||||
}
|
||||
|
||||
// Find the preceding assistant message with tool calls
|
||||
let foundMatchingToolCall = false;
|
||||
|
||||
// Look backwards from the current position to find the assistant message with matching tool call
|
||||
for (let j = i - 1; j >= 0; j--) {
|
||||
const prevMessage = messages[j];
|
||||
|
||||
if (prevMessage.role === 'assistant') {
|
||||
// Check if this assistant message has tool_calls
|
||||
if ('tool_calls' in prevMessage && prevMessage.tool_calls) {
|
||||
// Check if any tool call ID matches
|
||||
const hasMatchingId = prevMessage.tool_calls.some(
|
||||
toolCall => toolCall.id === message.tool_call_id
|
||||
);
|
||||
|
||||
if (hasMatchingId) {
|
||||
foundMatchingToolCall = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If we found an assistant message without the matching tool call, stop looking
|
||||
// (tool messages should be paired with the most recent assistant message with tool calls)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundMatchingToolCall) {
|
||||
throw new Error(
|
||||
`Tool message at index ${i} with tool_call_id "${message.tool_call_id}" ` +
|
||||
`must be preceded by an assistant message with a matching tool_call id`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
|
||||
*/
|
||||
|
||||
+2
-58
@@ -1,25 +1,6 @@
|
||||
/**
|
||||
* JavaScript runtime interface for executing code and managing files
|
||||
*/
|
||||
export interface JSRuntime {
|
||||
/**
|
||||
* Filesystem access
|
||||
*/
|
||||
fs(): Promise<JSRuntimeFS>;
|
||||
|
||||
/**
|
||||
* Spawn a process in the runtime environment
|
||||
* @param command Command to execute
|
||||
* @param args Command arguments
|
||||
* @param options Spawn options
|
||||
* @returns Process handle
|
||||
*/
|
||||
spawn(command: string, args?: string[], options?: SpawnOptions): Promise<JSRuntimeChildProcess>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filesystem interface compatible with both WebContainer and LightningFS
|
||||
* This interface unifies the APIs of both filesystem implementations
|
||||
* Filesystem interface for LightningFS
|
||||
* This interface provides a unified API for filesystem operations
|
||||
*/
|
||||
export interface JSRuntimeFS {
|
||||
// Core file operations with proper overloads for type safety
|
||||
@@ -64,41 +45,4 @@ export interface DirectoryEntry {
|
||||
name: string;
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified child process interface
|
||||
*/
|
||||
export interface JSRuntimeChildProcess {
|
||||
/**
|
||||
* A promise for the exit code of the process.
|
||||
*/
|
||||
exit: Promise<number>;
|
||||
/**
|
||||
* An input stream for the attached pseudoterminal device.
|
||||
*/
|
||||
input: WritableStream<string>;
|
||||
/**
|
||||
* A stream that receives all terminal output, including the stdout and stderr emitted by the spawned process
|
||||
* _and_ its descendants.
|
||||
*/
|
||||
output: ReadableStream<string>;
|
||||
/**
|
||||
* Kills the process.
|
||||
*/
|
||||
kill(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options that control process spawning.
|
||||
*/
|
||||
export interface SpawnOptions {
|
||||
/**
|
||||
* Current working directory for the process, relative to the workdir of this instance.
|
||||
*/
|
||||
cwd?: string;
|
||||
/**
|
||||
* Environment variables to set for the process.
|
||||
*/
|
||||
env?: Record<string, string | number | boolean>;
|
||||
}
|
||||
@@ -328,13 +328,13 @@ describe('KindGenerator', () => {
|
||||
expect(usedKinds.has(regularKind)).toBe(false);
|
||||
});
|
||||
|
||||
it('should generate random kinds with good distribution', () => {
|
||||
it('should generate random kinds with good distribution', { timeout: 10000 }, () => {
|
||||
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
|
||||
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
|
||||
|
||||
// Generate many kinds and check distribution
|
||||
const results = new Map<number, number>();
|
||||
const iterations = 100;
|
||||
const iterations = 50; // Reduced from 100 to 50 for performance
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const kind = KindGenerator.generateAvailableKind('regular', usedKinds);
|
||||
@@ -346,15 +346,15 @@ describe('KindGenerator', () => {
|
||||
expect(usedKinds.has(kind)).toBe(false);
|
||||
}
|
||||
|
||||
// Check that we get good variety (at least 10 unique kinds in 100 iterations)
|
||||
// Check that we get good variety (at least 5 unique kinds in 50 iterations)
|
||||
// Reduced expectations due to fewer iterations
|
||||
expect(results.size).toBeGreaterThanOrEqual(10);
|
||||
expect(results.size).toBeGreaterThanOrEqual(5);
|
||||
|
||||
// Check that no single kind dominates (no kind should appear more than 30% of the time)
|
||||
// Check that no single kind dominates (no kind should appear more than 50% of the time)
|
||||
// Increased threshold due to fewer iterations
|
||||
const maxFrequency = Math.max(...results.values());
|
||||
const maxFrequencyPercent = (maxFrequency / iterations) * 100;
|
||||
expect(maxFrequencyPercent).toBeLessThanOrEqual(30);
|
||||
expect(maxFrequencyPercent).toBeLessThanOrEqual(50);
|
||||
|
||||
// Check that all generated kinds follow our constraints
|
||||
for (const [kind] of results) {
|
||||
|
||||
+24
-17
@@ -84,37 +84,44 @@ export class KindGenerator {
|
||||
): number {
|
||||
const rangeInfo = this.getKindRangeInfo(range);
|
||||
|
||||
// Create a set of all numbers to avoid (used kinds + buffer)
|
||||
const kindsToAvoid = new Set<number>();
|
||||
|
||||
// Add used kinds and their buffer zones
|
||||
// Filter used kinds to only those relevant to our range (including buffer zone)
|
||||
const relevantUsedKinds = new Set<number>();
|
||||
for (const usedKind of usedKinds) {
|
||||
kindsToAvoid.add(usedKind);
|
||||
// Add buffer of 2 kinds on each side
|
||||
kindsToAvoid.add(usedKind - 2);
|
||||
kindsToAvoid.add(usedKind - 1);
|
||||
kindsToAvoid.add(usedKind + 1);
|
||||
kindsToAvoid.add(usedKind + 2);
|
||||
// Include used kinds that are in our range or close enough to affect our buffer
|
||||
if (usedKind >= rangeInfo.min - 2 && usedKind <= rangeInfo.max + 2) {
|
||||
relevantUsedKinds.add(usedKind);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to check if a number conflicts with buffer constraints
|
||||
const hasBufferConflict = (num: number): boolean => {
|
||||
for (const usedKind of relevantUsedKinds) {
|
||||
const distance = Math.abs(num - usedKind);
|
||||
if (distance <= 2) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// Collect all available numbers in the range
|
||||
const availableKinds: number[] = [];
|
||||
for (let i = rangeInfo.min; i <= rangeInfo.max; i++) {
|
||||
// Skip if in range to avoid
|
||||
if (kindsToAvoid.has(i)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip even numbers
|
||||
if (i % 2 === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Skip multiples of 5
|
||||
if (i % 5 === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Skip if used or has buffer conflict
|
||||
if (usedKinds.has(i) || hasBufferConflict(i)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
availableKinds.push(i);
|
||||
}
|
||||
|
||||
|
||||
+96
-18
@@ -1,6 +1,5 @@
|
||||
import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import { Buffer } from 'buffer';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
|
||||
@@ -9,8 +8,8 @@ if (typeof window !== 'undefined') {
|
||||
(window as { Buffer?: typeof Buffer }).Buffer = Buffer;
|
||||
}
|
||||
|
||||
const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git';
|
||||
// const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/lovable-blank.git';
|
||||
// const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git';
|
||||
const GIT_TEMPLATE_URL = 'https://gitlab.com/soapbox-pub/mkstack.git';
|
||||
|
||||
export interface Project {
|
||||
id: string;
|
||||
@@ -21,10 +20,12 @@ export interface Project {
|
||||
|
||||
export class ProjectsManager {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
dir: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
this.git = new Git(fs, 'https://cors.isomorphic-git.org');
|
||||
this.dir = '/projects';
|
||||
}
|
||||
|
||||
@@ -37,7 +38,7 @@ export class ProjectsManager {
|
||||
}
|
||||
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId);
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
|
||||
@@ -45,11 +46,52 @@ export class ProjectsManager {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Delete README.md if it exists
|
||||
try {
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
} catch {
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
// Delete .git directory and reinitialize
|
||||
try {
|
||||
await this.deleteDirectory(`${project.path}/.git`);
|
||||
} catch {
|
||||
// .git directory might not exist, ignore error
|
||||
}
|
||||
|
||||
// Initialize new git repository
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
const files = await this.getAllFiles(project.path);
|
||||
for (const file of files) {
|
||||
// Skip .git directory and other hidden files we don't want to track
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
async cloneProject(name: string, repoUrl: string, customId?: string): Promise<Project> {
|
||||
const url = new URL(repoUrl);
|
||||
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
// Check if project with this ID already exists when using custom ID
|
||||
@@ -62,18 +104,11 @@ export class ProjectsManager {
|
||||
await this.fs.mkdir(projectPath);
|
||||
|
||||
// Clone the repository
|
||||
await git.clone({
|
||||
fs: this.fs,
|
||||
http,
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
// Use the CORS proxy only for GitHub and GitLab URLs
|
||||
// More info: https://github.com/isomorphic-git/isomorphic-git#cors-support
|
||||
corsProxy: url.hostname === 'github.com' || url.hostname === 'gitlab.com'
|
||||
? 'https://cors.isomorphic-git.org'
|
||||
: undefined,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
@@ -160,6 +195,24 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
async readFileBytes(projectId: string, filePath: string): Promise<Uint8Array> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
try {
|
||||
const stat = await this.fs.stat(fullPath);
|
||||
if (stat.isFile()) {
|
||||
return await this.fs.readFile(fullPath);
|
||||
} else {
|
||||
throw new Error(`Path is not a file: ${filePath}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const fsError = error as NodeJS.ErrnoException;
|
||||
if (fsError.code === 'ENOENT') {
|
||||
throw new Error(`File not found: ${filePath}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(projectId: string, filePath: string, content: string): Promise<void> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
const dir = fullPath.split('/').slice(0, -1).join('/');
|
||||
@@ -256,8 +309,7 @@ export class ProjectsManager {
|
||||
async getNostrRepoAddress(projectId: string): Promise<string | null> {
|
||||
try {
|
||||
const projectPath = `${this.dir}/${projectId}`;
|
||||
const config = await git.getConfig({
|
||||
fs: this.fs,
|
||||
const config = await this.git.getConfig({
|
||||
dir: projectPath,
|
||||
path: 'nostr.repo',
|
||||
});
|
||||
@@ -276,4 +328,30 @@ export class ProjectsManager {
|
||||
// Return the original directory name without formatting
|
||||
return dirName;
|
||||
}
|
||||
|
||||
private async getAllFiles(dirPath: string, relativePath: string = ''): Promise<string[]> {
|
||||
const files: string[] = [];
|
||||
const entries = await this.fs.readdir(dirPath);
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry}`;
|
||||
const relativeFilePath = relativePath ? `${relativePath}/${entry}` : entry;
|
||||
|
||||
try {
|
||||
const stat = await this.fs.lstat(fullPath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Recursively get files from subdirectories
|
||||
const subFiles = await this.getAllFiles(fullPath, relativeFilePath);
|
||||
files.push(...subFiles);
|
||||
} else if (stat.isFile()) {
|
||||
files.push(relativeFilePath);
|
||||
}
|
||||
} catch {
|
||||
// Skip files we can't stat
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
}
|
||||
+203
-266
@@ -2,37 +2,18 @@ import OpenAI from 'openai';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import { DotAI } from './DotAI';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import { createAIClient } from './ai-client';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import { join } from '@std/path';
|
||||
|
||||
// Simple debounce utility
|
||||
const debounce = <T extends (...args: unknown[]) => void>(
|
||||
func: T,
|
||||
wait: number
|
||||
): ((...args: Parameters<T>) => void) => {
|
||||
let timeout: NodeJS.Timeout;
|
||||
return (...args: Parameters<T>) => {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => func(...args), wait);
|
||||
};
|
||||
};
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
export interface SessionConfig {
|
||||
id: string;
|
||||
export interface SessionState {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
maxSteps?: number;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
id: string;
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
messages: AIMessage[];
|
||||
streamingMessage?: {
|
||||
role: 'assistant';
|
||||
@@ -43,86 +24,104 @@ export interface SessionState {
|
||||
sessionName: string;
|
||||
lastActivity: Date;
|
||||
abortController?: AbortController;
|
||||
totalCost?: number; // Total cost in USD for this session
|
||||
lastInputTokens?: number; // Input tokens from the last AI request
|
||||
}
|
||||
|
||||
export interface SessionManagerEvents {
|
||||
sessionCreated: (sessionId: string) => void;
|
||||
sessionUpdated: (sessionId: string, state: SessionState) => void;
|
||||
sessionDeleted: (sessionId: string) => void;
|
||||
messageAdded: (sessionId: string, message: AIMessage) => void;
|
||||
streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (sessionId: string, isLoading: boolean) => void;
|
||||
sessionCreated: (projectId: string) => void;
|
||||
sessionDeleted: (projectId: string) => void;
|
||||
messageAdded: (projectId: string, message: AIMessage) => void;
|
||||
streamingUpdate: (projectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||
costUpdated: (projectId: string, totalCost: number) => void;
|
||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Global session manager that handles multiple AI chat sessions running concurrently.
|
||||
* Sessions can run in the background without interruption when switching between projects.
|
||||
* Global session manager that handles AI chat sessions keyed by project ID.
|
||||
* Only one session can be active per project at once.
|
||||
*/
|
||||
export class SessionManager {
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private sessionConfigs = new Map<string, SessionConfig>();
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> };
|
||||
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> };
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
private getCurrentUser?: () => NUser | undefined;
|
||||
|
||||
// Performance constants
|
||||
private readonly MAX_SESSIONS = 50;
|
||||
private readonly MAX_SESSION_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
private debouncedPersist = debounce(() => this.persistSessions(), 1000);
|
||||
private dotAI: DotAI;
|
||||
|
||||
constructor(fs: JSRuntimeFS, aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }) {
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> },
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => NUser | undefined
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
this.dotAI = new DotAI(fs, '/');
|
||||
|
||||
// Load persisted sessions on initialization
|
||||
this.loadPersistedSessions().catch(error => {
|
||||
console.warn('Failed to load sessions during initialization:', error);
|
||||
});
|
||||
this.getProviderModels = getProviderModels;
|
||||
this.getCurrentUser = getCurrentUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session for a project
|
||||
*/
|
||||
async createSession(config: SessionConfig): Promise<string> {
|
||||
const sessionState: SessionState = {
|
||||
id: config.id,
|
||||
projectId: config.projectId,
|
||||
projectName: config.projectName,
|
||||
messages: [],
|
||||
isLoading: false,
|
||||
sessionName: DotAI.generateSessionName(),
|
||||
lastActivity: new Date(),
|
||||
};
|
||||
async loadSession(
|
||||
projectId: string,
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
systemPrompt?: string,
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
let sessionName = DotAI.generateSessionName();
|
||||
|
||||
// Try to load existing history
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `/projects/${config.projectId}`);
|
||||
const dotAI = new DotAI(this.fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
sessionState.messages = lastSession.messages;
|
||||
sessionState.sessionName = lastSession.sessionName;
|
||||
messages = lastSession.messages;
|
||||
sessionName = lastSession.sessionName;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load session history:', error);
|
||||
}
|
||||
|
||||
this.sessions.set(config.id, sessionState);
|
||||
this.sessionConfigs.set(config.id, config);
|
||||
const session = this.sessions.get(projectId) ?? {
|
||||
projectId,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
maxSteps,
|
||||
isLoading: false,
|
||||
lastActivity: new Date(),
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
...this.sessions.get(projectId),
|
||||
messages,
|
||||
sessionName,
|
||||
};
|
||||
|
||||
this.persistSessions();
|
||||
this.emit('sessionCreated', config.id);
|
||||
this.emit('sessionUpdated', config.id, sessionState);
|
||||
// Update session configuration
|
||||
session.projectId = projectId;
|
||||
session.tools = tools;
|
||||
|
||||
return config.id;
|
||||
session.customTools = customTools;
|
||||
session.systemPrompt = systemPrompt;
|
||||
session.maxSteps = maxSteps;
|
||||
|
||||
this.sessions.set(projectId, session);
|
||||
|
||||
this.emit('sessionCreated', projectId);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a session by ID
|
||||
* Get a session by project ID
|
||||
*/
|
||||
getSession(sessionId: string): SessionState | undefined {
|
||||
return this.sessions.get(sessionId);
|
||||
getSession(projectId: string): SessionState | undefined {
|
||||
return this.sessions.get(projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,77 +131,56 @@ export class SessionManager {
|
||||
return Array.from(this.sessions.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get sessions for a specific project
|
||||
*/
|
||||
getProjectSessions(projectId: string): SessionState[] {
|
||||
return Array.from(this.sessions.values()).filter(
|
||||
session => session.projectId === projectId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a session
|
||||
*/
|
||||
async deleteSession(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
async deleteSession(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
session?.abortController?.abort();
|
||||
|
||||
this.sessions.delete(sessionId);
|
||||
this.sessionConfigs.delete(sessionId);
|
||||
this.sessions.delete(projectId);
|
||||
|
||||
await this.persistSessions();
|
||||
this.emit('sessionDeleted', sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all sessions for a project
|
||||
*/
|
||||
async deleteProjectSessions(projectId: string): Promise<void> {
|
||||
await Promise.all(
|
||||
this.getProjectSessions(projectId).map(session => this.deleteSession(session.id))
|
||||
);
|
||||
this.emit('sessionDeleted', projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a message to a session
|
||||
*/
|
||||
async addMessage(sessionId: string, message: AIMessage): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
async addMessage(projectId: string, message: AIMessage): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
session.messages.push(message);
|
||||
session.lastActivity = new Date();
|
||||
|
||||
await this.saveSessionHistory(sessionId);
|
||||
this.debouncedPersist();
|
||||
this.cleanupOldSessions();
|
||||
|
||||
this.emit('messageAdded', sessionId, message);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
await this.saveSessionHistory(projectId);
|
||||
this.emit('messageAdded', projectId, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message and start AI generation
|
||||
*/
|
||||
async sendMessage(sessionId: string, content: string, providerModel: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
const config = this.sessionConfigs.get(sessionId);
|
||||
async sendMessage(projectId: string, content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
|
||||
if (!session || !config || session.isLoading) return;
|
||||
if (!session || session.isLoading) return;
|
||||
|
||||
await this.addMessage(sessionId, { role: 'user', content });
|
||||
await this.startGeneration(sessionId, providerModel);
|
||||
await this.addMessage(projectId, { role: 'user', content });
|
||||
await this.startGeneration(projectId, providerModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start AI generation for a session
|
||||
*/
|
||||
async startGeneration(sessionId: string, providerModel: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
const config = this.sessionConfigs.get(sessionId);
|
||||
async startGeneration(projectId: string, providerModel: string): Promise<void> {
|
||||
let session = this.sessions.get(projectId);
|
||||
|
||||
if (!session || !config || session.isLoading || session.messages.length === 0) return;
|
||||
if (!session) {
|
||||
throw new Error('Session not found');
|
||||
}
|
||||
if (session.messages.length === 0) {
|
||||
throw new Error('No messages in session');
|
||||
}
|
||||
|
||||
// Check if last message is from user
|
||||
const lastMessage = session.messages[session.messages.length - 1];
|
||||
@@ -211,9 +189,9 @@ export class SessionManager {
|
||||
session.isLoading = true;
|
||||
session.abortController = new AbortController();
|
||||
session.lastActivity = new Date();
|
||||
this.sessions.set(projectId, session);
|
||||
|
||||
this.emit('loadingChanged', sessionId, true);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
this.emit('loadingChanged', projectId, true);
|
||||
|
||||
try {
|
||||
// Parse provider and model
|
||||
@@ -222,27 +200,19 @@ export class SessionManager {
|
||||
const modelName = parsed.model;
|
||||
|
||||
// Initialize OpenAI client
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
const currentUser = this.getCurrentUser?.();
|
||||
const openai = createAIClient(connectionConfig, currentUser);
|
||||
|
||||
// Prepare messages for AI
|
||||
const modelMessages: AIMessage[] = [...session.messages];
|
||||
if (config.systemPrompt) {
|
||||
modelMessages.unshift({
|
||||
role: 'system',
|
||||
content: config.systemPrompt
|
||||
});
|
||||
}
|
||||
|
||||
const conversationMessages = [...modelMessages];
|
||||
let stepCount = 0;
|
||||
const maxSteps = config.maxSteps || 50;
|
||||
const maxSteps = session.maxSteps || 50;
|
||||
|
||||
// Main AI generation loop
|
||||
while (stepCount < maxSteps && session.isLoading) {
|
||||
session = this.sessions.get(projectId);
|
||||
if (!session) {
|
||||
throw new Error('Session not found');
|
||||
}
|
||||
|
||||
stepCount++;
|
||||
|
||||
// Initialize streaming message
|
||||
@@ -252,15 +222,21 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
// Prepare messages for AI
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt
|
||||
? [{ role: 'system', content: session.systemPrompt }, ...session.messages]
|
||||
: session.messages;
|
||||
|
||||
// Prepare completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
messages: conversationMessages,
|
||||
tools: config.tools && Object.keys(config.tools).length > 0 ? Object.values(config.tools) : undefined,
|
||||
tool_choice: config.tools && Object.keys(config.tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true
|
||||
messages,
|
||||
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
|
||||
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true,
|
||||
stream_options: {
|
||||
include_usage: true,
|
||||
},
|
||||
};
|
||||
|
||||
// Generate streaming response
|
||||
@@ -273,6 +249,7 @@ export class SessionManager {
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
|
||||
for await (const chunk of stream) {
|
||||
// Check if session was cancelled
|
||||
if (!session.isLoading) break;
|
||||
@@ -283,8 +260,7 @@ export class SessionManager {
|
||||
accumulatedContent += delta.content;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.content += delta.content;
|
||||
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,14 +283,21 @@ export class SessionManager {
|
||||
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.choices[0]?.finish_reason) {
|
||||
finishReason = chunk.choices[0].finish_reason;
|
||||
}
|
||||
|
||||
// Capture usage data if available (some providers include it in the final chunk)
|
||||
if (chunk.usage) {
|
||||
usage = {
|
||||
prompt_tokens: chunk.usage.prompt_tokens || 0,
|
||||
completion_tokens: chunk.usage.completion_tokens || 0
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
@@ -324,14 +307,12 @@ export class SessionManager {
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Clear streaming message and add final message
|
||||
session.streamingMessage = undefined;
|
||||
await this.addMessage(sessionId, assistantMessage);
|
||||
conversationMessages.push(assistantMessage);
|
||||
// Add final message but keep streaming message until finally block
|
||||
await this.addMessage(projectId, assistantMessage);
|
||||
|
||||
// Check if we should stop
|
||||
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
|
||||
break;
|
||||
// Update cost if usage data is available
|
||||
if (usage) {
|
||||
this.updateSessionCost(projectId, usage, providerModel);
|
||||
}
|
||||
|
||||
// Handle tool calls
|
||||
@@ -341,25 +322,36 @@ export class SessionManager {
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
const toolName = functionToolCall.function.name;
|
||||
const tool = config.customTools[toolName];
|
||||
const tool = session.customTools[toolName];
|
||||
|
||||
if (!tool) {
|
||||
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Tool ${toolName} not found`);
|
||||
await this.addToolMessage(projectId, functionToolCall.id, `Tool ${toolName} not found`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const toolArgs = tool.inputSchema.parse(JSON.parse(functionToolCall.function.arguments));
|
||||
let toolArgs: unknown;
|
||||
if (tool.inputSchema) {
|
||||
toolArgs = tool.inputSchema.parse(JSON.parse(functionToolCall.function.arguments || '{}'));
|
||||
} else {
|
||||
// For tools without inputSchema, use empty object or parsed arguments as-is
|
||||
const rawArgs = functionToolCall.function.arguments;
|
||||
toolArgs = rawArgs ? JSON.parse(rawArgs) : {};
|
||||
}
|
||||
const content = await tool.execute(toolArgs);
|
||||
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, content);
|
||||
await this.addToolMessage(projectId, functionToolCall.id, content);
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
|
||||
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`);
|
||||
await this.addToolMessage(projectId, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we should stop
|
||||
if (finishReason === 'stop') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
@@ -379,22 +371,23 @@ export class SessionManager {
|
||||
errorMessage = `AI service error: ${errorMsg}`;
|
||||
}
|
||||
|
||||
await this.addMessage(sessionId, { role: 'assistant', content: errorMessage });
|
||||
await this.addMessage(projectId, { role: 'assistant', content: errorMessage });
|
||||
} finally {
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
if (session) {
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
}
|
||||
|
||||
this.emit('loadingChanged', sessionId, false);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
this.emit('loadingChanged', projectId, false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop AI generation for a session
|
||||
*/
|
||||
stopGeneration(sessionId: string): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
stopGeneration(projectId: string): void {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
session.abortController?.abort();
|
||||
@@ -402,69 +395,87 @@ export class SessionManager {
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
|
||||
this.emit('loadingChanged', sessionId, false);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old sessions to prevent memory bloat
|
||||
*/
|
||||
private cleanupOldSessions(): void {
|
||||
const now = Date.now();
|
||||
|
||||
// Delete old sessions
|
||||
for (const [id, session] of this.sessions) {
|
||||
if (now - session.lastActivity.getTime() > this.MAX_SESSION_AGE) {
|
||||
this.deleteSession(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete oldest sessions if we have too many
|
||||
if (this.sessions.size > this.MAX_SESSIONS) {
|
||||
Array.from(this.sessions.entries())
|
||||
.sort(([, a], [, b]) => a.lastActivity.getTime() - b.lastActivity.getTime())
|
||||
.slice(0, this.sessions.size - this.MAX_SESSIONS)
|
||||
.forEach(([id]) => this.deleteSession(id));
|
||||
}
|
||||
this.emit('loadingChanged', projectId, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new session (clear messages but keep configuration)
|
||||
*/
|
||||
async startNewSession(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
async startNewSession(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
this.stopGeneration(sessionId);
|
||||
this.stopGeneration(projectId);
|
||||
|
||||
session.messages = [];
|
||||
session.streamingMessage = undefined;
|
||||
session.sessionName = DotAI.generateSessionName();
|
||||
session.lastActivity = new Date();
|
||||
session.totalCost = 0;
|
||||
session.lastInputTokens = 0;
|
||||
|
||||
this.debouncedPersist();
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
this.emit('costUpdated', projectId, 0);
|
||||
this.emit('contextUsageUpdated', projectId, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to add tool messages and update conversation
|
||||
*/
|
||||
private async addToolMessage(sessionId: string, conversationMessages: AIMessage[], toolCallId: string, content: string): Promise<void> {
|
||||
private async addToolMessage(projectId: string, toolCallId: string, content: string): Promise<void> {
|
||||
const toolMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content,
|
||||
tool_call_id: toolCallId
|
||||
};
|
||||
|
||||
await this.addMessage(sessionId, toolMessage);
|
||||
conversationMessages.push(toolMessage);
|
||||
await this.addMessage(projectId, toolMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update session cost and context usage based on usage data
|
||||
*/
|
||||
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
|
||||
if (!this.getProviderModels) return;
|
||||
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const modelName = parsed.model;
|
||||
const providerName = parsed.provider;
|
||||
|
||||
// Find the model in provider models to get pricing and context length
|
||||
const models = this.getProviderModels();
|
||||
const model = models.find(m => m.id === modelName && m.provider === providerName);
|
||||
|
||||
// Update input tokens for context usage tracking
|
||||
session.lastInputTokens = usage.prompt_tokens;
|
||||
this.emit('contextUsageUpdated', projectId, usage.prompt_tokens);
|
||||
|
||||
if (!model?.pricing) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate cost for this request
|
||||
const promptCost = model.pricing.prompt.times(usage.prompt_tokens);
|
||||
const completionCost = model.pricing.completion.times(usage.completion_tokens);
|
||||
const requestCost = promptCost.add(completionCost).toNumber();
|
||||
|
||||
// Update session total cost
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session history to file
|
||||
*/
|
||||
private async saveSessionHistory(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
private async saveSessionHistory(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
@@ -497,87 +508,13 @@ export class SessionManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session states using DotAI for persistence
|
||||
*/
|
||||
private async persistSessions(): Promise<void> {
|
||||
try {
|
||||
if (!this.dotAI.fs?.writeFile) return;
|
||||
|
||||
const sessionData = {
|
||||
sessions: Array.from(this.sessions.entries()).map(([id, session]) => ({
|
||||
id,
|
||||
session: {
|
||||
...session,
|
||||
isLoading: false,
|
||||
streamingMessage: undefined,
|
||||
abortController: undefined
|
||||
}
|
||||
})),
|
||||
configs: Array.from(this.sessionConfigs.entries()),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
// Ensure .ai directory exists before writing
|
||||
const aiDir = join(this.dotAI.workingDir, '.ai');
|
||||
try {
|
||||
await this.dotAI.fs.mkdir(aiDir, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist, continue
|
||||
}
|
||||
|
||||
await this.dotAI.fs.writeFile(
|
||||
join(aiDir, 'sessions.json'),
|
||||
JSON.stringify(sessionData)
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('Failed to persist sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load persisted sessions using DotAI
|
||||
*/
|
||||
private async loadPersistedSessions(): Promise<void> {
|
||||
try {
|
||||
if (!this.dotAI.fs?.readFile) return;
|
||||
|
||||
const sessionsPath = join(this.dotAI.workingDir, '.ai', 'sessions.json');
|
||||
|
||||
try {
|
||||
const sessionsJson = await this.dotAI.fs.readFile(sessionsPath, 'utf8');
|
||||
const sessionData = JSON.parse(sessionsJson);
|
||||
|
||||
// Restore sessions
|
||||
sessionData.sessions?.forEach(({ id, session }: { id: string; session: Omit<SessionState, 'lastActivity'> & { lastActivity: string } }) => {
|
||||
this.sessions.set(id, {
|
||||
...session,
|
||||
lastActivity: new Date(session.lastActivity)
|
||||
});
|
||||
});
|
||||
|
||||
// Restore configs
|
||||
sessionData.configs?.forEach(([id, config]: [string, SessionConfig]) => {
|
||||
this.sessionConfigs.set(id, config);
|
||||
});
|
||||
} catch {
|
||||
// File doesn't exist or is invalid - start fresh
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup - stop all sessions and clear data
|
||||
*/
|
||||
async cleanup(): Promise<void> {
|
||||
await this.persistSessions();
|
||||
|
||||
this.sessions.forEach((_, sessionId) => this.stopGeneration(sessionId));
|
||||
this.sessions.forEach((_, projectId) => this.stopGeneration(projectId));
|
||||
|
||||
this.sessions.clear();
|
||||
this.sessionConfigs.clear();
|
||||
this.listeners = {};
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
import { WebContainer } from '@webcontainer/api';
|
||||
import type { JSRuntime, JSRuntimeFS, JSRuntimeChildProcess, DirectoryEntry, SpawnOptions } from './JSRuntime';
|
||||
|
||||
/**
|
||||
* WebContainer adapter that implements the JSRuntime interface
|
||||
*/
|
||||
export class WebContainerAdapter implements JSRuntime {
|
||||
private webcontainer: WebContainer | null = null;
|
||||
private bootPromise: Promise<WebContainer> | null = null;
|
||||
|
||||
/**
|
||||
* Get the filesystem interface
|
||||
*/
|
||||
async fs(): Promise<JSRuntimeFS> {
|
||||
const webcontainer = await this.ensureBooted();
|
||||
return new WebContainerFSAdapter(webcontainer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure WebContainer is booted
|
||||
*/
|
||||
private async ensureBooted(): Promise<WebContainer> {
|
||||
if (this.webcontainer) {
|
||||
return this.webcontainer;
|
||||
}
|
||||
|
||||
if (!this.bootPromise) {
|
||||
this.bootPromise = WebContainer.boot();
|
||||
}
|
||||
|
||||
this.webcontainer = await this.bootPromise;
|
||||
return this.webcontainer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a process in the WebContainer
|
||||
* Automatically boots the container on first call
|
||||
*/
|
||||
async spawn(command: string, args: string[] = [], options: SpawnOptions = {}): Promise<JSRuntimeChildProcess> {
|
||||
const webcontainer = await this.ensureBooted();
|
||||
return webcontainer.spawn(command, args, options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebContainer filesystem adapter that implements JSRuntimeFS
|
||||
*/
|
||||
class WebContainerFSAdapter implements JSRuntimeFS {
|
||||
constructor(private webcontainer: WebContainer) {}
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array>;
|
||||
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, encoding: string): Promise<string>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||
if (encoding) {
|
||||
return this.webcontainer.fs.readFile(path, encoding as 'utf8');
|
||||
} else {
|
||||
return this.webcontainer.fs.readFile(path);
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void> {
|
||||
if (encoding) {
|
||||
return this.webcontainer.fs.writeFile(path, data, encoding as 'utf8');
|
||||
} else {
|
||||
return this.webcontainer.fs.writeFile(path, data);
|
||||
}
|
||||
}
|
||||
|
||||
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[]> {
|
||||
if (options?.withFileTypes) {
|
||||
return this.webcontainer.fs.readdir(path, { withFileTypes: true });
|
||||
} else {
|
||||
return this.webcontainer.fs.readdir(path);
|
||||
}
|
||||
}
|
||||
|
||||
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
if (options?.recursive) {
|
||||
await this.webcontainer.fs.mkdir(path, { recursive: true });
|
||||
} else {
|
||||
await this.webcontainer.fs.mkdir(path);
|
||||
}
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
// WebContainer doesn't have a stat method, so we'll implement a workaround
|
||||
try {
|
||||
// Try to read as directory first
|
||||
await this.webcontainer.fs.readdir(path);
|
||||
return {
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: undefined,
|
||||
mtimeMs: undefined,
|
||||
};
|
||||
} catch {
|
||||
// If readdir fails, assume it's a file
|
||||
try {
|
||||
const content = await this.webcontainer.fs.readFile(path) as string | Uint8Array;
|
||||
const size = typeof content === 'string' ? content.length : content.byteLength;
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size,
|
||||
mtimeMs: Date.now(), // WebContainer doesn't provide modification time
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: undefined,
|
||||
mtimeMs: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
// WebContainer doesn't have a lstat method, so we can use stat directly
|
||||
return this.stat(path);
|
||||
}
|
||||
|
||||
async unlink(_path: string): Promise<void> {
|
||||
// WebContainer doesn't expose unlink, so we'll throw an error for now
|
||||
throw new Error('unlink operation not supported in WebContainer');
|
||||
}
|
||||
|
||||
async rmdir(_path: string): Promise<void> {
|
||||
// WebContainer doesn't expose rmdir, so we'll throw an error for now
|
||||
throw new Error('rmdir operation not supported in WebContainer');
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
// WebContainer doesn't expose rename, so we'll implement it by copying and deleting
|
||||
const content = await this.webcontainer.fs.readFile(oldPath);
|
||||
await this.webcontainer.fs.writeFile(newPath, content);
|
||||
// Note: We can't delete the old file since WebContainer doesn't expose unlink
|
||||
console.warn('WebContainer rename: copied file but could not delete original');
|
||||
}
|
||||
|
||||
async readlink(_path: string): Promise<string> {
|
||||
// WebContainer doesn't support symlinks, so we'll throw an error
|
||||
throw new Error('readlink operation not supported in WebContainer');
|
||||
}
|
||||
|
||||
async symlink(_target: string, _path: string): Promise<void> {
|
||||
// WebContainer doesn't support symlinks, so we'll throw an error
|
||||
throw new Error('symlink operation not supported in WebContainer');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import OpenAI from 'openai';
|
||||
import { NIP98Client } from '@nostrify/nostrify';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
|
||||
/**
|
||||
* Create an OpenAI client instance with the appropriate configuration.
|
||||
* If the connection requires Nostr authentication (NIP-98), it will use
|
||||
* the NIP98Client for authenticated requests.
|
||||
*/
|
||||
export function createAIClient(connection: AIConnection, user?: NUser): OpenAI {
|
||||
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
|
||||
baseURL: connection.baseURL,
|
||||
apiKey: connection.apiKey ?? '',
|
||||
dangerouslyAllowBrowser: true,
|
||||
};
|
||||
|
||||
// If Nostr authentication is required and we have a user, use NIP-98
|
||||
if (connection.nostr && user?.signer) {
|
||||
const nip98Client = new NIP98Client({ signer: user.signer });
|
||||
|
||||
return new OpenAI({
|
||||
...baseConfig,
|
||||
fetch: (input, init) => nip98Client.fetch(input, init),
|
||||
});
|
||||
}
|
||||
|
||||
// Standard OpenAI client
|
||||
return new OpenAI(baseConfig);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { buildProject } from './index';
|
||||
import { copyFiles } from '../copyFiles';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock esbuild
|
||||
vi.mock('../esbuild', () => ({
|
||||
getEsbuild: vi.fn(() => ({
|
||||
build: vi.fn(() => ({
|
||||
outputFiles: [
|
||||
{
|
||||
path: '/stdin.js',
|
||||
contents: new Uint8Array([1, 2, 3]),
|
||||
},
|
||||
{
|
||||
path: '/stdin.css',
|
||||
contents: new Uint8Array([4, 5, 6]),
|
||||
},
|
||||
],
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock copyFiles
|
||||
vi.mock('../copyFiles', () => ({
|
||||
copyFiles: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('buildProject', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockDOMParser: DOMParser;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockFS = {
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
} as JSRuntimeFS;
|
||||
|
||||
mockDOMParser = {
|
||||
parseFromString: vi.fn(() => ({
|
||||
documentElement: {
|
||||
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
|
||||
},
|
||||
querySelector: vi.fn(() => ({
|
||||
setAttribute: vi.fn(),
|
||||
})),
|
||||
head: {
|
||||
appendChild: vi.fn(),
|
||||
},
|
||||
createElement: vi.fn(() => ({
|
||||
setAttribute: vi.fn(),
|
||||
})),
|
||||
})),
|
||||
} as unknown as DOMParser;
|
||||
});
|
||||
|
||||
it('should include files from public directory in build output', async () => {
|
||||
// Mock required files
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('package.json')) {
|
||||
return '{"name": "test-project"}';
|
||||
}
|
||||
if (path.endsWith('index.html')) {
|
||||
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
|
||||
}
|
||||
if (path.endsWith('package-lock.json')) {
|
||||
return '{"dependencies": {}}';
|
||||
}
|
||||
if (path === '/test/project/public/favicon.ico') {
|
||||
return new Uint8Array([10, 11, 12]);
|
||||
}
|
||||
if (path === '/test/project/public/images/logo.png') {
|
||||
return new Uint8Array([20, 21, 22]);
|
||||
}
|
||||
throw new Error(`Unexpected file read: ${path}`);
|
||||
});
|
||||
|
||||
// Mock public directory structure
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path === '/test/project/public') {
|
||||
return { isDirectory: () => true, isFile: () => false };
|
||||
}
|
||||
if (path === '/test/project/public/images') {
|
||||
return { isDirectory: () => true, isFile: () => false };
|
||||
}
|
||||
return { isDirectory: () => false, isFile: () => true };
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.readdir)
|
||||
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
|
||||
if (path === '/test/project/public') {
|
||||
return [
|
||||
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
|
||||
{ name: 'images', isDirectory: () => true, isFile: () => false },
|
||||
];
|
||||
}
|
||||
if (path === '/test/project/public/images') {
|
||||
return [
|
||||
{ name: 'logo.png', isDirectory: () => false, isFile: () => true },
|
||||
];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
// Mock additional filesystem operations for buildProject
|
||||
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
|
||||
// Handle regular readdir calls for dist cleanup
|
||||
if (path === '/test/project/dist') {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await buildProject({
|
||||
fs: mockFS,
|
||||
projectPath: '/test/project',
|
||||
domParser: mockDOMParser,
|
||||
});
|
||||
|
||||
// Should include built files
|
||||
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// Public files should be copied to filesystem, not included in files object
|
||||
// Verify copyFiles was called for public directory
|
||||
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public');
|
||||
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
||||
|
||||
// Should have correct metadata
|
||||
expect(result.outputPath).toBe('/test/project/dist');
|
||||
expect(result.projectId).toBe('project');
|
||||
});
|
||||
|
||||
it('should handle missing public directory gracefully', async () => {
|
||||
// Mock required files
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('package.json')) {
|
||||
return '{"name": "test-project"}';
|
||||
}
|
||||
if (path.endsWith('index.html')) {
|
||||
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
|
||||
}
|
||||
if (path.endsWith('package-lock.json')) {
|
||||
return '{"dependencies": {}}';
|
||||
}
|
||||
throw new Error(`File not found: ${path}`);
|
||||
});
|
||||
|
||||
// Mock missing public directory
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path === '/test/project/public') {
|
||||
throw new Error('Directory not found');
|
||||
}
|
||||
return { isDirectory: () => false, isFile: () => true };
|
||||
});
|
||||
|
||||
// Mock additional filesystem operations for buildProject
|
||||
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
|
||||
if (path === '/test/project/dist') {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await buildProject({
|
||||
fs: mockFS,
|
||||
projectPath: '/test/project',
|
||||
domParser: mockDOMParser,
|
||||
});
|
||||
|
||||
// Should still include built files
|
||||
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// Should not include any public files in bundle
|
||||
expect(Object.keys(result.files)).not.toContain('favicon.ico');
|
||||
|
||||
// Should not try to copy public files if directory doesn't exist
|
||||
expect(copyFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle empty public directory', async () => {
|
||||
// Mock required files
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('package.json')) {
|
||||
return '{"name": "test-project"}';
|
||||
}
|
||||
if (path.endsWith('index.html')) {
|
||||
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
|
||||
}
|
||||
if (path.endsWith('package-lock.json')) {
|
||||
return '{"dependencies": {}}';
|
||||
}
|
||||
throw new Error(`File not found: ${path}`);
|
||||
});
|
||||
|
||||
// Mock empty public directory
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path === '/test/project/public') {
|
||||
return { isDirectory: () => true, isFile: () => false };
|
||||
}
|
||||
return { isDirectory: () => false, isFile: () => true };
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.readdir)
|
||||
.mockImplementation(async (path: string) => {
|
||||
// Handle regular readdir calls for dist cleanup
|
||||
if (path === '/test/project/dist') {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
// Mock additional filesystem operations for buildProject
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await buildProject({
|
||||
fs: mockFS,
|
||||
projectPath: '/test/project',
|
||||
domParser: mockDOMParser,
|
||||
});
|
||||
|
||||
// Should include built files
|
||||
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// Should have exactly 3 files (main.js, main.css, index.html)
|
||||
expect(Object.keys(result.files)).toHaveLength(3);
|
||||
|
||||
// Should try to copy public files but directory is empty
|
||||
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
||||
});
|
||||
});
|
||||
+80
-3
@@ -1,4 +1,5 @@
|
||||
import { getEsbuild } from "@/lib/esbuild";
|
||||
import { copyFiles } from "@/lib/copyFiles";
|
||||
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
@@ -10,14 +11,15 @@ export interface BuildProjectOptions {
|
||||
projectPath: string;
|
||||
domParser: DOMParser;
|
||||
target?: string;
|
||||
outputPath?: string;
|
||||
}
|
||||
|
||||
export async function buildProject(
|
||||
async function bundle(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
const esbuild = await getEsbuild();
|
||||
|
||||
const { fs, projectPath, domParser, target } = options;
|
||||
const { fs, projectPath, domParser, target = "esnext" } = options;
|
||||
|
||||
const indexHtmlText = await fs.readFile(
|
||||
`${projectPath}/index.html`,
|
||||
@@ -43,7 +45,7 @@ export async function buildProject(
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "esm",
|
||||
target: target ?? "esnext",
|
||||
target,
|
||||
outdir: "/",
|
||||
jsx: "automatic",
|
||||
plugins: [
|
||||
@@ -77,6 +79,81 @@ export async function buildProject(
|
||||
return dist;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build project and write output files to the filesystem
|
||||
*/
|
||||
export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
files: Record<string, Uint8Array>;
|
||||
outputPath: string;
|
||||
projectId?: string;
|
||||
}> {
|
||||
const { fs, projectPath, outputPath = `${projectPath}/dist` } = options;
|
||||
|
||||
// Check if we're in a valid project directory
|
||||
try {
|
||||
await fs.readFile(`${projectPath}/package.json`, "utf8");
|
||||
} catch {
|
||||
throw new Error(`❌ Could not find package.json at ${projectPath}. Make sure you're in a valid project directory.`);
|
||||
}
|
||||
|
||||
// Check if index.html exists
|
||||
try {
|
||||
await fs.readFile(`${projectPath}/index.html`, "utf8");
|
||||
} catch {
|
||||
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
|
||||
}
|
||||
|
||||
// Run the build
|
||||
const dist = await bundle(options);
|
||||
|
||||
// Delete all existing files in output directory
|
||||
try {
|
||||
const distFiles = await fs.readdir(outputPath);
|
||||
for (const file of distFiles) {
|
||||
await fs.unlink(`${outputPath}/${file}`);
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors (e.g., directory doesn't exist)
|
||||
}
|
||||
|
||||
// Create output directory if it doesn't exist
|
||||
await fs.mkdir(outputPath, { recursive: true });
|
||||
|
||||
// Write all built files to output directory
|
||||
for (const [path, contents] of Object.entries(dist)) {
|
||||
await fs.writeFile(`${outputPath}/${path}`, contents);
|
||||
}
|
||||
|
||||
// Copy files from public directory if it exists
|
||||
try {
|
||||
const publicPath = `${projectPath}/public`;
|
||||
const stat = await fs.stat(publicPath);
|
||||
if (stat.isDirectory()) {
|
||||
await copyFiles(fs, fs, publicPath, outputPath);
|
||||
}
|
||||
} catch {
|
||||
// Public directory doesn't exist, which is fine
|
||||
}
|
||||
|
||||
// Extract project ID from the project path
|
||||
// Expected format: /projects/{projectId}
|
||||
const projectId = projectPath.split('/').pop();
|
||||
|
||||
// Emit build completion event for PreviewPane to listen to
|
||||
if (projectId && typeof window !== 'undefined') {
|
||||
const buildCompleteEvent = new CustomEvent('buildComplete', {
|
||||
detail: { projectId }
|
||||
});
|
||||
window.dispatchEvent(buildCompleteEvent);
|
||||
}
|
||||
|
||||
return {
|
||||
files: dist,
|
||||
outputPath,
|
||||
projectId,
|
||||
};
|
||||
}
|
||||
|
||||
function updateIndexHtml(doc: Document): void {
|
||||
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
# Shell Commands
|
||||
|
||||
This directory contains pure TypeScript implementations of basic shell commands that can be executed through the `ShellTool`.
|
||||
|
||||
## Architecture
|
||||
|
||||
### ShellCommand Interface
|
||||
|
||||
All commands implement the `ShellCommand` interface which defines:
|
||||
|
||||
- `name`: The command name (e.g., 'cat', 'ls', 'cd')
|
||||
- `description`: Brief description of what the command does
|
||||
- `usage`: Usage syntax for the command
|
||||
- `execute(args, cwd)`: Executes the command and returns a `ShellCommandResult`
|
||||
|
||||
### ShellCommandResult
|
||||
|
||||
Commands return a `ShellCommandResult` object containing:
|
||||
|
||||
- `exitCode`: 0 for success, non-zero for error
|
||||
- `stdout`: Standard output content
|
||||
- `stderr`: Standard error content
|
||||
- `newCwd`: Optional new working directory (for commands like 'cd')
|
||||
|
||||
## Available Commands
|
||||
|
||||
The shell supports 25 essential commands for file and directory operations, text processing, content analysis, and system utilities.
|
||||
|
||||
### cat
|
||||
|
||||
**Usage:** `cat [file...]`
|
||||
|
||||
Concatenate and display file contents. Supports multiple files which will be concatenated in order.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cat file.txt # Display single file
|
||||
cat file1.txt file2.txt # Concatenate multiple files
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Reads and displays file contents
|
||||
- Supports multiple files (concatenated output)
|
||||
- Proper error handling for missing files, directories, and permission issues
|
||||
- Rejects absolute paths for security
|
||||
|
||||
### ls
|
||||
|
||||
**Usage:** `ls [-la] [file...]`
|
||||
|
||||
List directory contents with support for long format and hidden files.
|
||||
|
||||
**Options:**
|
||||
- `-l`: Use long listing format (shows permissions, size, modification time)
|
||||
- `-a`: Show hidden files (files starting with '.')
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
ls # List current directory
|
||||
ls src/ # List specific directory
|
||||
ls -l # Long format listing
|
||||
ls -la # Long format with hidden files
|
||||
ls file.txt # Show info for specific file
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Simple and long format listings
|
||||
- Shows file types (directories have trailing `/`)
|
||||
- Sorts directories first, then files alphabetically
|
||||
- Filters hidden files by default
|
||||
- Handles both files and directories as arguments
|
||||
|
||||
### cd
|
||||
|
||||
**Usage:** `cd [directory]`
|
||||
|
||||
Change the current working directory.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cd # Go to project root
|
||||
cd src/ # Change to src directory
|
||||
cd .. # Go to parent directory
|
||||
cd . # Stay in current directory
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Changes working directory for subsequent commands
|
||||
- Supports relative paths (., .., subdirectories)
|
||||
- Validates target exists and is a directory
|
||||
- Updates shell working directory state
|
||||
|
||||
### pwd
|
||||
|
||||
**Usage:** `pwd`
|
||||
|
||||
Print the current working directory path.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
pwd # Show current directory
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Simple, no-argument command
|
||||
- Always shows absolute path of current directory
|
||||
|
||||
### echo
|
||||
|
||||
**Usage:** `echo [text...]`
|
||||
|
||||
Display text to output.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
echo hello world # Output: hello world
|
||||
echo "quoted text" # Output: quoted text
|
||||
echo # Output: (empty line)
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Joins arguments with spaces
|
||||
- Adds trailing newline
|
||||
- Handles special characters
|
||||
- Always succeeds (exit code 0)
|
||||
|
||||
### rm
|
||||
|
||||
**Usage:** `rm [-rf] file...`
|
||||
|
||||
Remove files and directories.
|
||||
|
||||
**Options:**
|
||||
- `-r`, `-R`: Remove directories recursively
|
||||
- `-f`: Force removal, ignore non-existent files
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
rm file.txt # Remove single file
|
||||
rm file1.txt file2.txt # Remove multiple files
|
||||
rm -r directory/ # Remove directory recursively
|
||||
rm -rf temp/ # Force remove directory
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Removes files and directories
|
||||
- Recursive directory removal with `-r`
|
||||
- Force flag `-f` ignores missing files
|
||||
- Prevents removal of `.` and `..`
|
||||
- Proper error handling for permissions and missing files
|
||||
|
||||
### cp
|
||||
|
||||
**Usage:** `cp [-r] source... destination`
|
||||
|
||||
Copy files and directories.
|
||||
|
||||
**Options:**
|
||||
- `-r`, `-R`: Copy directories recursively
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cp file.txt backup.txt # Copy file
|
||||
cp file.txt dir/ # Copy file into directory
|
||||
cp -r src/ backup/ # Copy directory recursively
|
||||
cp file1.txt file2.txt dest/ # Copy multiple files to directory
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Copies files and directories
|
||||
- Recursive directory copying with `-r`
|
||||
- Supports copying into existing directories
|
||||
- Creates target directories as needed
|
||||
- Handles multiple source files
|
||||
|
||||
### head
|
||||
|
||||
**Usage:** `head [-n lines] [file...]`
|
||||
|
||||
Display the first lines of files. Shows first 10 lines by default.
|
||||
|
||||
**Options:**
|
||||
- `-n lines`: Show specific number of lines (e.g., `-n 5` or `-n5`)
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
head file.txt # Show first 10 lines
|
||||
head -n 5 file.txt # Show first 5 lines
|
||||
head -n3 file1.txt file2.txt # Show first 3 lines of multiple files
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Configurable line count with `-n` option
|
||||
- Supports multiple files with headers
|
||||
- Proper error handling for missing files and directories
|
||||
- Rejects absolute paths for security
|
||||
|
||||
### tail
|
||||
|
||||
**Usage:** `tail [-n lines] [file...]`
|
||||
|
||||
Display the last lines of files. Shows last 10 lines by default.
|
||||
|
||||
**Options:**
|
||||
- `-n lines`: Show specific number of lines (e.g., `-n 5` or `-n5`)
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
tail file.txt # Show last 10 lines
|
||||
tail -n 5 file.txt # Show last 5 lines
|
||||
tail -n3 file1.txt file2.txt # Show last 3 lines of multiple files
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Configurable line count with `-n` option
|
||||
- Supports multiple files with headers
|
||||
- Handles files with or without trailing newlines
|
||||
- Proper error handling for missing files and directories
|
||||
|
||||
### grep
|
||||
|
||||
**Usage:** `grep [-i] [-n] [-r] pattern [file...]`
|
||||
|
||||
Search for patterns in files using regular expressions.
|
||||
|
||||
**Options:**
|
||||
- `-i`: Case-insensitive search
|
||||
- `-n`: Show line numbers
|
||||
- `-r`, `-R`: Search directories recursively
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
grep "error" log.txt # Search for "error" in log.txt
|
||||
grep -i "hello" file.txt # Case-insensitive search
|
||||
grep -n "function" *.js # Show line numbers
|
||||
grep -r "TODO" src/ # Recursive search in directory
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Regular expression pattern matching
|
||||
- Case-insensitive search option
|
||||
- Line number display
|
||||
- Recursive directory search
|
||||
- Multiple file support with filename prefixes
|
||||
- Returns exit code 1 when no matches found (standard grep behavior)
|
||||
|
||||
### find
|
||||
|
||||
**Usage:** `find [path...] [-name pattern] [-type f|d]`
|
||||
|
||||
Search for files and directories by name and type.
|
||||
|
||||
**Options:**
|
||||
- `-name pattern`: Search by filename pattern (supports * and ? wildcards)
|
||||
- `-type f`: Find only files
|
||||
- `-type d`: Find only directories
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
find . # List all files and directories
|
||||
find . -name "*.js" # Find all JavaScript files
|
||||
find . -type d # Find only directories
|
||||
find src/ -name "test*" -type f # Find files starting with "test" in src/
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Recursive directory traversal
|
||||
- Glob-style pattern matching with * and ? wildcards
|
||||
- File type filtering (files vs directories)
|
||||
- Multiple search paths
|
||||
- Case-insensitive pattern matching
|
||||
|
||||
### wc
|
||||
|
||||
**Usage:** `wc [-l] [-w] [-c] [file...]`
|
||||
|
||||
Count lines, words, and characters in files.
|
||||
|
||||
**Options:**
|
||||
- `-l`: Count only lines
|
||||
- `-w`: Count only words
|
||||
- `-c`: Count only characters
|
||||
- (no options): Show all counts (lines, words, characters)
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
wc file.txt # Show lines, words, and characters
|
||||
wc -l file.txt # Count only lines
|
||||
wc -w *.txt # Count words in all .txt files
|
||||
wc file1.txt file2.txt # Show counts and totals for multiple files
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Line, word, and character counting
|
||||
- Multiple file support with totals
|
||||
- Configurable output (lines, words, characters, or all)
|
||||
- Proper handling of empty files
|
||||
- Formatted columnar output
|
||||
|
||||
### touch
|
||||
|
||||
**Usage:** `touch file...`
|
||||
|
||||
Create empty files or update timestamps.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
touch newfile.txt # Create empty file
|
||||
touch file1.txt file2.txt # Create multiple files
|
||||
touch existing.txt # Update timestamp (no-op in this implementation)
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Creates empty files if they don't exist
|
||||
- Handles existing files gracefully
|
||||
- Multiple file support
|
||||
- Validates parent directory exists
|
||||
- Prevents touching directories
|
||||
|
||||
### mkdir
|
||||
|
||||
**Usage:** `mkdir [-p] directory...`
|
||||
|
||||
Create directories.
|
||||
|
||||
**Options:**
|
||||
- `-p`: Create parent directories as needed
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
mkdir newdir # Create single directory
|
||||
mkdir dir1 dir2 dir3 # Create multiple directories
|
||||
mkdir -p deep/nested/path # Create nested directories
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Single and multiple directory creation
|
||||
- Recursive directory creation with `-p` option
|
||||
- Proper error handling for existing files/directories
|
||||
- Validates parent directory permissions
|
||||
- Prevents conflicts with existing files
|
||||
|
||||
### mv
|
||||
|
||||
**Usage:** `mv source... destination`
|
||||
|
||||
Move or rename files and directories.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
mv old.txt new.txt # Rename file
|
||||
mv file.txt dir/ # Move file into directory
|
||||
mv dir1/ dir2/ # Rename directory
|
||||
mv file1.txt file2.txt dest/ # Move multiple files to directory
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Moves/renames files and directories
|
||||
- Supports moving into existing directories
|
||||
- Creates target directories as needed
|
||||
- Handles multiple source files
|
||||
- Prevents overwriting existing files
|
||||
|
||||
### sort
|
||||
|
||||
**Usage:** `sort [-r] [-n] [-u] [file...]`
|
||||
|
||||
Sort lines of text files.
|
||||
|
||||
**Options:**
|
||||
- `-r`: Sort in reverse order
|
||||
- `-n`: Sort numerically instead of alphabetically
|
||||
- `-u`: Remove duplicate lines (unique)
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
sort file.txt # Sort lines alphabetically
|
||||
sort -r file.txt # Sort in reverse order
|
||||
sort -n numbers.txt # Sort numerically
|
||||
sort -u file.txt # Sort and remove duplicates
|
||||
sort -rnu data.txt # Combine options: reverse, numeric, unique
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Alphabetical and numerical sorting
|
||||
- Reverse order sorting
|
||||
- Duplicate removal
|
||||
- Multiple file support
|
||||
- Configurable sort behavior
|
||||
|
||||
### uniq
|
||||
|
||||
**Usage:** `uniq [-c] [-d] [-u] [file]`
|
||||
|
||||
Report or omit repeated consecutive lines.
|
||||
|
||||
**Options:**
|
||||
- `-c`: Show count of each line
|
||||
- `-d`: Show only duplicate lines
|
||||
- `-u`: Show only unique lines (not repeated)
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
uniq file.txt # Remove consecutive duplicates
|
||||
uniq -c file.txt # Show count of each line
|
||||
uniq -d file.txt # Show only duplicated lines
|
||||
uniq -u file.txt # Show only unique lines
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Removes consecutive duplicate lines
|
||||
- Line counting with `-c` option
|
||||
- Filter duplicates or unique lines
|
||||
- Formatted output with proper spacing
|
||||
- Note: Only removes consecutive duplicates (use with `sort` for all duplicates)
|
||||
|
||||
### cut
|
||||
|
||||
**Usage:** `cut -c LIST | -f LIST [-d DELIM] [file...]`
|
||||
|
||||
Extract sections from lines of files.
|
||||
|
||||
**Options:**
|
||||
- `-c LIST`: Extract characters at specified positions
|
||||
- `-f LIST`: Extract fields using delimiter
|
||||
- `-d DELIM`: Use DELIM as field delimiter (default: tab)
|
||||
|
||||
**LIST format:**
|
||||
- `1,3,5`: Specific positions
|
||||
- `1-5`: Range of positions
|
||||
- `1,3-5,7`: Combination of positions and ranges
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cut -c 1,3,5 file.txt # Extract characters 1, 3, and 5
|
||||
cut -c 1-10 file.txt # Extract characters 1 through 10
|
||||
cut -f 1,3 data.csv # Extract fields 1 and 3 (tab-delimited)
|
||||
cut -f 2-4 -d ',' data.csv # Extract fields 2-4 using comma delimiter
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Character-based extraction
|
||||
- Field-based extraction with custom delimiters
|
||||
- Range and list specifications
|
||||
- Multiple file support
|
||||
|
||||
### tr
|
||||
|
||||
**Usage:** `tr [-d] SET1 [SET2] [file...]`
|
||||
|
||||
Translate or delete characters.
|
||||
|
||||
**Options:**
|
||||
- `-d`: Delete characters in SET1
|
||||
|
||||
**SET format:**
|
||||
- `abc`: Literal characters
|
||||
- `a-z`: Character ranges
|
||||
- `0-9`: Numeric ranges
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
tr 'a-z' 'A-Z' file.txt # Convert lowercase to uppercase
|
||||
tr -d 'aeiou' file.txt # Delete all vowels
|
||||
tr '0-9' 'X' file.txt # Replace all digits with 'X'
|
||||
tr 'abc' '123' file.txt # Replace a→1, b→2, c→3
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Character translation with ranges
|
||||
- Character deletion
|
||||
- Multiple file support
|
||||
- Range expansion (a-z, 0-9, etc.)
|
||||
|
||||
### diff
|
||||
|
||||
**Usage:** `diff [-u] file1 file2`
|
||||
|
||||
Compare files line by line.
|
||||
|
||||
**Options:**
|
||||
- `-u`: Use unified diff format
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
diff file1.txt file2.txt # Compare files in normal format
|
||||
diff -u file1.txt file2.txt # Compare files in unified format
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Line-by-line file comparison
|
||||
- Normal and unified diff formats
|
||||
- Shows additions, deletions, and changes
|
||||
- Exit code 0 for identical files, 1 for differences
|
||||
|
||||
### which
|
||||
|
||||
**Usage:** `which command...`
|
||||
|
||||
Locate commands and show their paths.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
which ls # Show path to ls command
|
||||
which cat grep find # Show paths to multiple commands
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Locates available shell commands
|
||||
- Shows simulated paths (/usr/bin/command)
|
||||
- Multiple command support
|
||||
- Exit code 1 if any command not found
|
||||
|
||||
### whoami
|
||||
|
||||
**Usage:** `whoami`
|
||||
|
||||
Display current username.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
whoami # Display current user
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Simple username display
|
||||
- No arguments accepted
|
||||
- Always returns "user" in this implementation
|
||||
|
||||
### date
|
||||
|
||||
**Usage:** `date [+FORMAT]`
|
||||
|
||||
Display current date and time.
|
||||
|
||||
**Format specifiers:**
|
||||
- `%Y`: 4-digit year
|
||||
- `%y`: 2-digit year
|
||||
- `%m`: Month (01-12)
|
||||
- `%d`: Day of month (01-31)
|
||||
- `%H`: Hour (00-23)
|
||||
- `%M`: Minute (00-59)
|
||||
- `%S`: Second (00-59)
|
||||
- `%A`: Full weekday name
|
||||
- `%a`: Abbreviated weekday name
|
||||
- `%B`: Full month name
|
||||
- `%b`: Abbreviated month name
|
||||
- `%s`: Unix timestamp
|
||||
- `%%`: Literal %
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
date # Default format
|
||||
date '+%Y-%m-%d' # ISO date format
|
||||
date '+%H:%M:%S' # Time only
|
||||
date '+%A, %B %d, %Y' # Full date
|
||||
date '+%s' # Unix timestamp
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Default and custom date formatting
|
||||
- Standard format specifiers
|
||||
- Unix timestamp support
|
||||
- Weekday and month name formatting
|
||||
|
||||
### env
|
||||
|
||||
**Usage:** `env`
|
||||
|
||||
Display environment variables.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
env # Show all environment variables
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Displays simulated environment variables
|
||||
- Shows common variables (HOME, PATH, USER, PWD, etc.)
|
||||
- PWD reflects current working directory
|
||||
|
||||
### clear
|
||||
|
||||
**Usage:** `clear`
|
||||
|
||||
Clear terminal screen.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
clear # Clear screen
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Sends ANSI escape sequence to clear screen
|
||||
- Moves cursor to top-left position
|
||||
- No arguments accepted
|
||||
|
||||
## Usage with ShellTool
|
||||
|
||||
Commands are executed through the `ShellTool` which handles:
|
||||
|
||||
- Command parsing (including quoted arguments)
|
||||
- Command registration and lookup
|
||||
- Working directory management
|
||||
- Error formatting and output handling
|
||||
|
||||
```typescript
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
|
||||
// Create shell tool with filesystem and working directory
|
||||
const shell = new ShellTool(fs, '/project/root');
|
||||
|
||||
// Execute commands
|
||||
const result = await shell.execute({ command: 'cat package.json' });
|
||||
console.log(result); // File contents or error message
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
All commands have comprehensive test coverage. Some complex integration tests for `cp` and `mv` commands are currently skipped due to the complexity of mocking filesystem operations with multiple interdependent calls. The basic functionality and error handling is well tested.
|
||||
|
||||
To run tests:
|
||||
```bash
|
||||
npm test
|
||||
```
|
||||
|
||||
## Adding New Commands
|
||||
|
||||
To add a new command:
|
||||
|
||||
1. Create a new file in this directory (e.g., `newcommand.ts`)
|
||||
2. Implement the `ShellCommand` interface
|
||||
3. Register the command in `ShellTool.ts` constructor
|
||||
4. Add exports to `index.ts`
|
||||
5. Write tests for the command
|
||||
|
||||
Example command structure:
|
||||
|
||||
```typescript
|
||||
import type { ShellCommand, ShellCommandResult } from './ShellCommand';
|
||||
import { createSuccessResult, createErrorResult } from './ShellCommand';
|
||||
|
||||
export class MyCommand implements ShellCommand {
|
||||
name = 'mycommand';
|
||||
description = 'Description of what the command does';
|
||||
usage = 'mycommand [options] [args]';
|
||||
|
||||
constructor(private fs: JSRuntimeFS) {}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
// Implementation here
|
||||
return createSuccessResult('output');
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Interface for shell command implementations
|
||||
*/
|
||||
export interface ShellCommand {
|
||||
/** The name of the command (e.g., 'cat', 'ls', 'cd') */
|
||||
name: string;
|
||||
|
||||
/** Brief description of what the command does */
|
||||
description: string;
|
||||
|
||||
/** Usage syntax for the command */
|
||||
usage: string;
|
||||
|
||||
/**
|
||||
* Execute the command with the given arguments
|
||||
* @param args Array of command arguments (excluding the command name itself)
|
||||
* @param cwd Current working directory
|
||||
* @param input Optional input for pipe operations
|
||||
* @returns Promise resolving to the command output or error message
|
||||
*/
|
||||
execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of executing a shell command
|
||||
*/
|
||||
export interface ShellCommandResult {
|
||||
/** Exit code (0 for success, non-zero for error) */
|
||||
exitCode: number;
|
||||
|
||||
/** Standard output content */
|
||||
stdout: string;
|
||||
|
||||
/** Standard error content */
|
||||
stderr: string;
|
||||
|
||||
/** New working directory (for commands like 'cd' that change directory) */
|
||||
newCwd?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a successful command result
|
||||
*/
|
||||
export function createSuccessResult(stdout: string, newCwd?: string): ShellCommandResult {
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout,
|
||||
stderr: '',
|
||||
newCwd,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an error command result
|
||||
*/
|
||||
export function createErrorResult(stderr: string, exitCode: number = 1): ShellCommandResult {
|
||||
return {
|
||||
exitCode,
|
||||
stdout: '',
|
||||
stderr,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { CatCommand } from './cat';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('CatCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let catCommand: CatCommand;
|
||||
const testCwd = '/test/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
catCommand = new CatCommand(mockFS);
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(catCommand.name).toBe('cat');
|
||||
expect(catCommand.description).toBe('Concatenate and display file contents');
|
||||
expect(catCommand.usage).toBe('cat [file...]');
|
||||
});
|
||||
|
||||
it('should return error when no arguments provided', async () => {
|
||||
const result = await catCommand.execute([], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing file operand');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should read and return file content', async () => {
|
||||
const fileContent = 'Hello, World!';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
|
||||
|
||||
const result = await catCommand.execute(['test.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(fileContent);
|
||||
expect(result.stderr).toBe('');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/test.txt', 'utf8');
|
||||
});
|
||||
|
||||
it('should concatenate multiple files', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockResolvedValueOnce('File 1 content\n')
|
||||
.mockResolvedValueOnce('File 2 content\n');
|
||||
|
||||
const result = await catCommand.execute(['file1.txt', 'file2.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('File 1 content\nFile 2 content\n');
|
||||
expect(result.stderr).toBe('');
|
||||
});
|
||||
|
||||
it('should return error for directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await catCommand.execute(['somedir'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Is a directory');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should return error for non-existent file', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await catCommand.execute(['nonexistent.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle absolute paths', async () => {
|
||||
const fileContent = 'Absolute path content';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
|
||||
|
||||
const result = await catCommand.execute(['/absolute/path.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(fileContent);
|
||||
expect(result.stderr).toBe('');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/absolute/path.txt', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle Windows-style absolute paths', async () => {
|
||||
const fileContent = 'Windows path content';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
|
||||
|
||||
const result = await catCommand.execute(['C:\\temp\\file.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(fileContent);
|
||||
expect(result.stderr).toBe('');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('C:\\temp\\file.txt', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle permission errors', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('EACCES: permission denied'));
|
||||
|
||||
const result = await catCommand.execute(['restricted.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Permission denied');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { join } from "@std/path";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'cat' command
|
||||
* Concatenate and display file contents
|
||||
*/
|
||||
export class CatCommand implements ShellCommand {
|
||||
name = 'cat';
|
||||
description = 'Concatenate and display file contents';
|
||||
usage = 'cat [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
|
||||
// If input is provided (from pipe), return it
|
||||
if (input !== undefined) {
|
||||
return createSuccessResult(input);
|
||||
}
|
||||
|
||||
// If no arguments provided, show usage
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const outputs: string[] = [];
|
||||
|
||||
for (const filePath of args) {
|
||||
try {
|
||||
// Handle both absolute and relative paths
|
||||
let absolutePath: string;
|
||||
|
||||
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
|
||||
// It's an absolute path - use it directly
|
||||
absolutePath = filePath;
|
||||
} else {
|
||||
// It's a relative path - resolve it relative to the current working directory
|
||||
absolutePath = join(cwd, filePath);
|
||||
}
|
||||
|
||||
// Check if path exists and is a file
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const content = await this.fs.readFile(absolutePath, 'utf8');
|
||||
outputs.push(content);
|
||||
|
||||
} catch (error) {
|
||||
// Handle file not found or permission errors
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join all file contents
|
||||
const result = outputs.join('');
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { CdCommand } from './cd';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('CdCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let cdCommand: CdCommand;
|
||||
const testCwd = '/test/current/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
cdCommand = new CdCommand(mockFS);
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(cdCommand.name).toBe('cd');
|
||||
expect(cdCommand.description).toBe('Change directory');
|
||||
expect(cdCommand.usage).toBe('cd [directory]');
|
||||
});
|
||||
|
||||
it('should change to specified directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await cdCommand.execute(['subdir'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.newCwd).toBe('/test/current/dir/subdir');
|
||||
expect(result.stderr).toBe('');
|
||||
});
|
||||
|
||||
it('should handle current directory (.)', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await cdCommand.execute(['.'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.newCwd).toBe(testCwd);
|
||||
});
|
||||
|
||||
it('should handle parent directory (..)', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await cdCommand.execute(['..'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.newCwd).toBe('/test/current');
|
||||
});
|
||||
|
||||
it('should stay in current directory when no arguments', async () => {
|
||||
const result = await cdCommand.execute([], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.newCwd).toBe(testCwd);
|
||||
});
|
||||
|
||||
it('should return error for non-existent directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await cdCommand.execute(['nonexistent'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should return error when target is not a directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
|
||||
const result = await cdCommand.execute(['file.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Not a directory');
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await cdCommand.execute(['/absolute/path'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
|
||||
it('should reject too many arguments', async () => {
|
||||
const result = await cdCommand.execute(['dir1', 'dir2'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('too many arguments');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { join, resolve, dirname } from "@std/path";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'cd' command
|
||||
* Change directory
|
||||
*/
|
||||
export class CdCommand implements ShellCommand {
|
||||
name = 'cd';
|
||||
description = 'Change directory';
|
||||
usage = 'cd [directory]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
let targetPath: string;
|
||||
|
||||
if (args.length === 0) {
|
||||
// cd with no arguments - stay in current directory for simplicity
|
||||
return createSuccessResult('', cwd);
|
||||
} else if (args.length === 1) {
|
||||
targetPath = args[0];
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: too many arguments`);
|
||||
}
|
||||
|
||||
// Handle absolute paths
|
||||
if (targetPath.startsWith('/') || targetPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(targetPath)) {
|
||||
return createErrorResult(`${this.name}: absolute paths are not supported: ${targetPath}`);
|
||||
}
|
||||
|
||||
// Resolve the new path
|
||||
let newCwd: string;
|
||||
if (targetPath === '.') {
|
||||
// Current directory
|
||||
newCwd = cwd;
|
||||
} else if (targetPath === '..') {
|
||||
// Parent directory
|
||||
const parentPath = dirname(cwd);
|
||||
// Don't allow going above the project root
|
||||
if (parentPath === cwd) {
|
||||
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
|
||||
}
|
||||
newCwd = parentPath;
|
||||
} else {
|
||||
// Relative path
|
||||
newCwd = join(cwd, targetPath);
|
||||
}
|
||||
|
||||
// Normalize the path
|
||||
newCwd = resolve(newCwd);
|
||||
|
||||
// Check if the target directory exists and is a directory
|
||||
try {
|
||||
const stats = await this.fs.stat(newCwd);
|
||||
|
||||
if (!stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${targetPath}: Not a directory`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${targetPath}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${targetPath}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${targetPath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${targetPath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
|
||||
// Return success with the new working directory
|
||||
return createSuccessResult('', newCwd);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ClearCommand } from './clear';
|
||||
|
||||
describe('ClearCommand', () => {
|
||||
const clearCommand = new ClearCommand();
|
||||
|
||||
it('should return ANSI clear screen sequence', async () => {
|
||||
const result = await clearCommand.execute([], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('\x1b[2J\x1b[H');
|
||||
expect(result.stderr).toBe('');
|
||||
});
|
||||
|
||||
it('should error when arguments provided', async () => {
|
||||
const result = await clearCommand.execute(['arg'], '/test');
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.stderr).toContain('arguments not supported');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user