Compare commits

...
Author SHA1 Message Date
Alex Gleason 9390ae4152 release: v9.9.2 2026-04-02 03:08:22 -05:00
Alex Gleason 7ecab519ed Fix VersionCheck crash: move VersionCheck and Toaster inside BrowserRouter
VersionCheck uses <Link> which requires React Router context. It was
rendered in App.tsx outside BrowserRouter, causing a null destructuring
error at runtime. Moved VersionCheck and Toaster into AppRouter.tsx
inside BrowserRouter.

Also added null check and truncation for changelog excerpt items to
prevent undefined access and overly long toast descriptions.
2026-04-02 03:05:15 -05:00
Alex Gleason 85afb6828e Remove root site option from nsite deploy form, always use named sites 2026-04-02 02:55:12 -05:00
Alex Gleason d4d6ff0d89 Include nsite "a" tag in kind 31990 app events when deployment exists 2026-04-02 02:47:52 -05:00
Alex Gleason f29510ed00 Left-align changelog page content instead of centering 2026-04-02 02:40:31 -05:00
Alex Gleason 62f6bd439e Add release job to GitLab CI
Triggered by version tags (vX.Y.Z), extracts the changelog section
for the tagged version and creates a GitLab release with it.
2026-04-02 02:23:21 -05:00
Alex Gleason 37c19be7ee Fix versioning: start at 9.9.1, move changelog into app shell
Bump starting version from 9.9.0 to 9.9.1. Move the /changelog page
from a standalone layout into AppLayout so the project sidebar is
available. Remove it from the settings nav since it's its own page.
2026-04-02 02:19:50 -05:00
Alex Gleason b7ce705b2b Add versioning system, changelog page, and release skill
Replace calver (YYYY.MM.DD+sha) with marketing versioning (X.Y.Z),
starting at 9.9.0. Add changelog page at /changelog with Keep a
Changelog parsing, pre-release banner, and expandable entries linked
to GitLab releases. Add VersionCheck component that shows a "What's
new" toast when the app version changes. Add release skill for
managing versioned releases with changelog and git tagging.
2026-04-02 02:09:00 -05:00
Alex Gleason 380e6f3b84 Add shakespeare and template t-tags to kind 31990 app events 2026-04-02 01:51:11 -05:00
Alex Gleason ed55e600d4 Add NIP-89 kind 31990 app management for projects
- AppDialog with app preview card, Blossom icon upload, and collapsible advanced section
- AppTool for AI to view/update app with view-before-update guard
- Shared buildAppEvent utility for DRY event construction
- Auto-fill website from deployment URL, default name from project ID
- Add repo 'a' tag when origin is a nostr:// URI owned by the user
- Custom tool call rendering with AppWindow icon
- System prompt guidance for app publishing workflow and prerequisites
- Store app coordinate in .git/shakespeare/app.json via DotAI
2026-04-02 01:36:15 -05:00
Alex Gleason ed40469af4 Add agent rule: always commit after finishing a turn 2026-03-29 01:34:42 -05:00
Alex Gleason 049ad5bd04 Normalize GitHub/GitLab web URLs to .git clone URLs on submit 2026-03-29 01:34:24 -05:00
Alex Gleason 34bfbb971b Revert "Enable AI to see images when using the read tool"
This reverts commit 2641252c6a.
2026-03-28 22:21:17 -05:00
Alex Gleason 2641252c6a Enable AI to see images when using the read tool
Return JPG/PNG images as structured image content parts from ReadTool
instead of embedding base64 data URLs as plain text. Since OpenAI tool
messages only support text content, images are injected as a follow-up
user message with image_url parts that vision models can interpret.
2026-03-28 18:27:41 -05:00
Alex Gleason d6e8b9bc84 Merge branch 'nsite-source-tags' into 'main'
Include `source` tags in nsite deployments

See merge request soapbox-pub/shakespeare!105
2026-03-25 22:14:01 +00:00
hzrd149 113fc0a326 Include source tags in nsite deployments 2026-03-25 16:25:22 -05:00
Alex Gleason ee240cdfda Fix ESLint errors: remove unused NPool import, fix useEffect dependencies 2026-03-24 19:36:19 -05:00
Alex Gleason 9e29153a95 npm audit fix 2026-03-24 17:27:40 -05:00
Alex Gleason a8c19bd0ad Merge branch 'nsite-v2' into 'main'
Update nsite deployment

See merge request soapbox-pub/shakespeare!104
2026-03-24 22:26:26 +00:00
hzrd149 4f103d6ad4 Cleanup nsite deployment config 2026-03-24 17:21:07 -05:00
hzrd149 d51fee34e3 Update nsite deployment
Add support for named sites under users key
2026-03-24 17:03:39 -05:00
Alex Gleason c5ed881af0 Fix git sync nag showing immediately after cloning external projects
Store the HEAD commit OID as 'shakespeare.clonedAt' git config at clone
time, then use it to determine whether the user has actually altered the
project before showing the backup warning.
2026-03-18 01:24:10 -05:00
Alex Gleason 459311bd7b Add background parameter to GenerateImageTool for transparency support
The previous commit tried to enable transparency by allowing output_format: "png",
but transparency in the OpenAI Image API is controlled by a separate "background"
parameter, not the output format. Without it, the model was drawing checkerboard
patterns to visually represent transparency instead of producing actual alpha channels.

Add the background parameter ("transparent", "opaque", "auto") to the tool schema
and pass it through to the API. Update the system prompt to instruct the AI to use
both background: "transparent" and output_format: "png"/"webp" together.
2026-03-17 19:22:31 -05:00
Alex Gleason 119b28d0f5 Allow PNG output format in image generation for transparency support 2026-03-17 17:43:56 -05:00
Alex Gleason 3741782c62 Fix CI: remove unused toast import and fix indentation in App provider tree 2026-03-12 03:14:44 -05:00
Alex Gleason 50bc875423 Fix stale template cache by re-cloning when force-pull fails
Shallow clones (depth=1) cause isomorphic-git's fetch to fail when the
remote template has new commits. Instead of showing an error toast and
falling back to the stale cached template, delete the cache and re-clone
fresh to ensure users always get the latest template.
2026-03-11 19:14:31 -05:00
Alex Gleason 9c2984f69f Add Plausible Analytics variables to .env.example 2026-03-11 18:47:49 -05:00
Alex Gleason a5c293bcc9 Add Plausible Analytics settings to System Settings page 2026-03-11 18:47:09 -05:00
Alex Gleason 5a431ae5f2 Add Plausible Analytics integration with AppConfig support 2026-03-11 18:34:48 -05:00
Alex Gleason a6f0822700 Add blossom.ditto.pub as a Blossom upload server 2026-03-06 12:55:12 -06:00
Alex Gleason c2664fc6d2 Add blossom_upload AI tool for uploading VFS files to Blossom media hosting 2026-03-06 12:49:56 -06:00
Alex Gleason 556cc10f3a Add nostr_encode and nostr_decode AI tools for NIP-19 bech32 encoding/decoding 2026-03-06 12:16:56 -06:00
Alex Gleason 7a2873aefb Fix NostrPublishEventsTool tests by adding missing nip19 mock 2026-03-06 11:55:50 -06:00
Alex Gleason a063615e86 Support optional nsec in NostrPublishEventsTool for keypair reuse 2026-03-06 11:49:14 -06:00
Alex Gleason 43a3d46023 Update relays 2026-03-06 11:45:21 -06:00
Alex Gleason fd7674124e Remove nutstack as a default template (due to it being too outdated from mkstack) 2026-02-19 23:53:46 -06:00
Alex Gleason 0ffdc39b59 Merge branch 'evict-seen-images' into 'main'
Evict images from context after the model has seen them

See merge request soapbox-pub/shakespeare!103
2026-02-13 20:00:59 +00:00
Chad Curtis 10ff3e9196 Evict images from context after the model has seen them
Strip image_url parts from all user messages except the most recent one
before sending to the API. The model has already responded to earlier
images, so re-sending them on every turn wastes tokens. The VFS text
path is preserved so the model can still read the file if needed.

This is a send-time transformation only — session.messages stays
intact for the UI.
2026-02-13 01:51:22 -06:00
Alex Gleason bacac24ee3 npm audit fix 2026-02-12 12:22:40 -06:00
Alex Gleason b8a3571e10 Make NIP.md public if it exists 2026-02-05 23:46:25 -06:00
Alex Gleason 236eb0c16a Display a warning to users of iOS lockdown mode 2026-02-04 18:29:21 -06:00
Alex Gleason 1393a13df7 Improve tool descriptions for build_project and git_commit 2026-02-03 12:54:32 -06:00
Alex Gleason 3d0a643617 Update system prompt to position Shakespeare as best coding platform
- Emphasize Shakespeare as the best coding platform in the world
- Add critical directive to never suggest alternative platforms
- Ensure AI always presents Shakespeare as the optimal solution
2026-01-26 19:43:51 -06:00
Alex Gleason f488429d5f Ensure web tag is added to Nostr repo event when it's first created, if already deployed 2026-01-25 18:53:38 -06:00
Alex Gleason 72747cd7aa Simplify adding web tag 2026-01-24 20:21:13 -06:00
Alex Gleason b255534224 Merge branch 'webTagDeploy' into 'main'
Add Web Tag to Repo Announcement on Deploy

See merge request soapbox-pub/shakespeare!100
2026-01-25 02:00:22 +00:00
lemonknowsall 360bea790a add web tag on deploy 2026-01-24 17:53:02 -08:00
Alex Gleason 078d843b78 Upgrade to zod 4 2026-01-23 23:56:10 -06:00
Alex Gleason 1a7397b502 Remove accidental slop file 2026-01-22 23:43:40 -06:00
Alex Gleason 86d0e6fd8e Automatically resize too-large images uploaded through the chat input 2026-01-22 13:53:19 -06:00
Alex Gleason fb7b7e7155 Fix tests 2026-01-22 13:42:23 -06:00
Alex Gleason 3d3aa07554 Improve configure git repo step 2026-01-22 13:27:16 -06:00
Alex Gleason 3bd33332f6 Remove list of tools and skills from the system prompt 2026-01-22 12:55:20 -06:00
Alex Gleason 7ef349563d List available skills in the skill tool itself 2026-01-22 12:55:17 -06:00
Alex Gleason a2c472bfef Add slash commands 2026-01-22 12:39:18 -06:00
Alex Gleason 8d6f5e6320 Fix hardcoded projectsPath in todo tools 2026-01-22 00:47:57 -06:00
Alex Gleason ec5dc6d963 Add todo tools 2026-01-22 00:42:01 -06:00
Alex Gleason 87956df961 Add webfetch and websearch tools 2026-01-21 23:25:29 -06:00
Alex Gleason 79b336f967 stripProjectPrefix tweak 2026-01-21 21:52:58 -06:00
Alex Gleason bb28e71e50 Fix grep and glob tools 2026-01-21 21:45:30 -06:00
Alex Gleason 2971a91fbb Merge branch 'main' of https://gitlab.com/soapbox-pub/shakespeare 2026-01-21 21:40:29 -06:00
Alex Gleason 48f1a59c2a Default to worker.ts, actually 2026-01-21 21:40:18 -06:00
Alex Gleason 2bc5f45512 Bundle Cloudflare Worker before deploying 2026-01-21 21:36:06 -06:00
Alex Gleason b0a48accf3 npm audit fix 2026-01-21 21:20:10 -06:00
Alex Gleason 24e367315e Fix git fetch context 2026-01-21 21:19:06 -06:00
Alex Gleason 18bdf741d3 Tool improvements 2026-01-21 21:04:52 -06:00
Alex Gleason 765652ec67 Replace text_editor_* tools with OpenCode-inspired alternatives (read/write/edit) 2026-01-21 19:40:32 -06:00
Alex Gleason 47a7835797 Brevity when explaining deployment options 2026-01-21 18:32:45 -06:00
Alex Gleason 949e7bb1f7 Stricter phrasing in deployment options system prompt 2026-01-21 17:34:24 -06:00
Alex Gleason dd5f9fe379 Support Netlify functions 2026-01-21 17:15:49 -06:00
Alex Gleason a27317ea10 Add deployment options hints to the system prompt 2026-01-21 16:30:06 -06:00
Alex Gleason c9178643fb Make Cloudflare Workers deployment aware of wrangler.jsonc, allow specifying main module 2026-01-21 16:06:45 -06:00
Alex Gleason 6ba5cf9bb2 Enable TypeScript strict mode 2026-01-21 14:46:11 -06:00
Alex Gleason d5e267103c Clean up old electron code 2026-01-21 14:37:58 -06:00
Alex Gleason ac6d4643af Only navigate to preferences on desktop 2026-01-21 14:35:07 -06:00
Alex Gleason 9f60a72621 Add "Build" button back to preview pane 2026-01-21 14:29:49 -06:00
Alex Gleason f289735da9 Fix tests by mocking the localStorage API 2026-01-21 14:08:23 -06:00
Alex Gleason 71631d3375 Upgrade to Node 25 2026-01-21 13:54:24 -06:00
Alex Gleason 79759af337 Merge branch 'ppqFeedback' into 'main'
PPQ Feedback

See merge request soapbox-pub/shakespeare!97
2026-01-21 19:53:27 +00:00
Alex Gleason 6473b6c57a Fix type error 2026-01-21 13:50:11 -06:00
Alex Gleason add3c62bda Revert "breakout new chat button from dropdown menu"
This reverts commit 05100d295e.
2026-01-21 13:48:02 -06:00
Alex Gleason 46c2539543 Fix chat scrolling issues 2026-01-21 13:40:50 -06:00
Alex Gleason c95a1a3278 Remove legacy refresh from Preview Pane 2026-01-21 12:49:40 -06:00
Alex Gleason 5dfc1d8897 Fix deleting a deployment provider and editing Railway API token 2026-01-20 23:50:58 -06:00
Alex Gleason 428b1bee2a Generate a domain automatically on Railway 2026-01-20 23:43:29 -06:00
Alex Gleason 65495ba1dd Add Railway deployment 2026-01-20 23:13:49 -06:00
Alex Gleason 5c842bed9a Read project skills from multiple supported locations 2026-01-20 22:30:39 -06:00
Alex Gleason c8e8ef714e Split apart skills.ts from plugin.ts 2026-01-20 22:16:02 -06:00
Alex Gleason 16d4f814e5 Subtle OpenSecret body fix 2026-01-20 22:02:29 -06:00
Alex Gleason 31ab27a79a Polyfill node:crypto, allow building with files outside of project directory 2026-01-20 16:50:46 -06:00
Alex Gleason 13ea7c192e Support file: URIs in package.json 2026-01-18 03:22:07 -06:00
Alex Gleason 0d6bee2025 Add Maple AI support 2026-01-17 23:22:02 -06:00
Alex Gleason fba950aeb5 Support json ESM imports 2026-01-17 18:48:29 -06:00
lemonknowsall 5348ab1fda remove unused import and prop 2026-01-16 23:15:00 -08:00
lemonknowsall 3d36c35baa add missing languages for copy all and new chat 2026-01-16 23:04:43 -08:00
lemonknowsall f1e2823882 make log pane horizontal 2026-01-16 22:50:31 -08:00
lemonknowsall 4842ac8fa4 resizeable log pane 2026-01-16 22:50:31 -08:00
lemonknowsall 7a4cd6cd00 media drag and drop in chat view 2026-01-16 22:50:31 -08:00
lemonknowsall eb381bc37e add copy all button to logs popover 2026-01-16 14:41:00 -08:00
lemonknowsall 05100d295e breakout new chat button from dropdown menu 2026-01-16 13:55:29 -08:00
lemonknowsall a4271de370 add icon tooltips for info on hover 2026-01-16 13:48:55 -08:00
lemonknowsall 5b2359d671 default settings navigation to preferences 2026-01-16 12:52:41 -08:00
Alex Gleason a047f913b4 Truncate large tool calls and save the output to tmpDir 2026-01-15 12:45:01 -06:00
Alex Gleason 44805ce481 Move OpenCode Zen up in the presets list 2026-01-14 13:13:31 -06:00
Alex Gleason a8eec32842 Update URL templates to use opts objects 2026-01-14 11:16:40 -06:00
Alex Gleason 5d075e02ab npm audit fix 2026-01-11 13:18:05 -06:00
164 changed files with 12404 additions and 4303 deletions

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
---
name: plausible-analytics
description: Add Plausible Analytics tracking to the application, configured through AppConfig and environment variables.
---
# Plausible Analytics
Add privacy-friendly analytics with [Plausible](https://plausible.io/) using the `@plausible-analytics/tracker` npm package. Configuration lives in `AppConfig` so it can be set via `VITE_` environment variables.
## 1. Install the package
```bash
npm install @plausible-analytics/tracker
```
## 2. Add fields to `AppConfig`
In `src/contexts/AppContext.ts`, add two fields to the `AppConfig` interface:
```typescript
export interface AppConfig {
// ...existing fields...
/** Plausible Analytics domain (empty string = disabled). */
plausibleDomain: string;
/** Plausible Analytics API endpoint (empty string = use default). */
plausibleEndpoint: string;
}
```
## 3. Update the Zod schema in `AppProvider.tsx`
Add the new fields to the `AppConfigSchema`:
```typescript
const AppConfigSchema = z.object({
// ...existing fields...
plausibleDomain: z.string(),
plausibleEndpoint: z.string(),
}) satisfies z.ZodType<AppConfig>;
```
## 4. Create `PlausibleProvider`
Create `src/components/PlausibleProvider.tsx`:
```tsx
import { ReactNode, useEffect, useRef } from 'react';
import { useAppContext } from '@/hooks/useAppContext';
interface PlausibleProviderProps {
children: ReactNode;
}
/**
* Reactively initializes Plausible Analytics from AppConfig.
* Plausible's `init()` can only be called once, so we guard with a ref.
*/
export function PlausibleProvider({ children }: PlausibleProviderProps) {
const { config } = useAppContext();
const initializedRef = useRef(false);
useEffect(() => {
if (initializedRef.current || !config.plausibleDomain) return;
initializedRef.current = true;
import('@plausible-analytics/tracker').then(({ init }) => {
init({
domain: config.plausibleDomain,
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
});
}).catch(console.error);
}, [config.plausibleDomain, config.plausibleEndpoint]);
return <>{children}</>;
}
```
## 5. Wire into `App.tsx`
Import `PlausibleProvider` and add it inside `AppProvider` (it needs access to `useAppContext`):
```tsx
import { PlausibleProvider } from '@/components/PlausibleProvider';
// In the defaultConfig, add:
const defaultConfig: AppConfig = {
// ...existing fields...
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || '',
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || '',
};
// In the JSX, wrap children of AppProvider:
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<PlausibleProvider>
{/* ...rest of providers... */}
</PlausibleProvider>
</AppProvider>
```
## 6. Update `TestApp.tsx`
Add the new fields to the test default config with empty strings (disabled):
```typescript
const defaultConfig: AppConfig = {
// ...existing fields...
plausibleDomain: '',
plausibleEndpoint: '',
};
```
## 7. Configure via environment variables
Create or update `.env`:
```
VITE_PLAUSIBLE_DOMAIN="example.com"
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
```
`VITE_PLAUSIBLE_ENDPOINT` is optional -- it defaults to Plausible Cloud's endpoint if omitted. Set it when using a self-hosted Plausible instance.
+198
View File
@@ -0,0 +1,198 @@
---
name: release
description: Publish a new app release with versioning, changelog, and git tagging. Triggered by "publish a new release" or similar requests.
---
# Release Skill
This skill guides you through publishing a new release of the app. It handles version bumping, changelog generation, and git tagging/pushing.
## Overview
- **Version format**: Marketing version (X.Y.Z), starting from 9.9.1. **This is NOT semver.** Version numbers are chosen based on how the release looks to end users, not based on API compatibility or breaking changes. Think of it like an app store version -- the number reflects the perceived significance of the update to a regular user.
- **Version source of truth**: `package.json` `version` field
- **Changelog**: `CHANGELOG.md` in repo root, using [Keep a Changelog](https://keepachangelog.com/) format
- **Version bumping**:
- **Patch (Z)**: Most releases. Bug fixes, tweaks, internal improvements, anything a user wouldn't specifically notice or seek out.
- **Minor (Y)**: Releases with headline features -- things worth announcing. A user should be able to look at the minor bump and think "oh, something new happened."
- **Major (X)**: Only when the user explicitly requests it (milestones, rebrands, major redesigns)
- **CI trigger**: Pushing a version tag (`v9.9.0`) triggers the CI pipeline to build and create a GitLab release
## Release Procedure
Follow these steps in order. Do NOT skip any step.
### Step 1: Required Reading
Before writing any release notes, you MUST read these pages to understand the product context, voice, and values:
1. **https://soapbox.pub/** -- Soapbox company overview and product suite
2. **https://shakespeare.diy/** -- Shakespeare product page
These pages define what Shakespeare is, how it's positioned, and the tone of voice to use. Changelog entries should reflect this identity: creative, empowering, user-focused, emphasizing building and self-expression. Avoid dry technical jargon -- write for people who use the app, not developers.
### Step 2: Pre-flight Checks
```bash
# Ensure working directory is clean
git status
# Ensure we're on main branch
git branch --show-current
# Run the full test suite
npm run test
```
- If the working directory has uncommitted changes, ask the user whether to commit them first or abort.
- If not on `main`, warn the user and ask whether to proceed.
- If tests fail, stop and fix the issues before continuing.
### Step 3: Determine What Changed
```bash
# Get the current version from package.json
node -p "require('./package.json').version"
# Get commits since the last version tag
git log v$(node -p "require('./package.json').version")..HEAD --oneline
```
- If there are no commits since the last tag, inform the user there is nothing to release and stop.
- Review the commit list to understand the scope of changes.
### Step 4: Decide the Version Bump
Analyze the commits from Step 3 and determine the appropriate bump level:
| Bump | When to use | Example |
|------|-------------|---------|
| **Patch** | Bug fixes, minor tweaks, dependency updates, small UI polish, internal tooling, developer-facing pages, CI/build changes, settings/admin screens | 9.9.0 -> 9.9.1 |
| **Minor** | Significant new product features that change how users interact with the app -- the kind of thing you'd highlight in an app store update or announce on social media (e.g., new template support, new AI features, new deployment options, major UI overhaul) | 9.9.1 -> 9.10.0 |
| **Major** | ONLY when the user explicitly instructs a major bump | 9.10.0 -> 10.0.0 |
**Default to patch** when in doubt. The bar for a minor bump is high -- ask yourself: "Would a regular user notice and care about this change?" If the answer is no, it's a patch. Internal pages (changelog, settings, about screens), infrastructure improvements, CI fixes, and developer tooling are always patch-level regardless of whether they technically add a new page or screen.
When bumping minor, reset patch to 0 (e.g., 9.9.3 -> 9.10.0).
When bumping major, reset minor and patch to 0 (e.g., 9.3.1 -> 10.0.0).
### Step 5: Write the Changelog Entry
Prepend a new section to `CHANGELOG.md` directly below the `# Changelog` heading.
**Format:**
```markdown
## [X.Y.Z] - YYYY-MM-DD
### Added
- Description of new features
### Changed
- Description of changes to existing features
### Fixed
- Description of bug fixes
### Removed
- Description of removed features
```
**Rules:**
- Only include categories that have entries (omit empty categories)
- Write **user-facing descriptions**, not raw commit messages
- Keep descriptions concise -- one line per change
- Group related commits into single entries where appropriate
- Use present tense ("Add dark mode toggle", not "Added dark mode toggle")
- Focus on what the user sees/experiences, not internal implementation details
- Use the current date in YYYY-MM-DD format
- **Collapse related work into one entry.** If a feature was added and then fixed/tweaked across multiple commits in the same release, present the finished result as a single "Added" entry. Never list something as "Added" and then also list fixes for that same thing -- the user sees the end product, not the development history.
- **Omit purely internal changes.** CI fixes, build pipeline tweaks, developer tooling, and infrastructure changes should be omitted from the changelog entirely unless they have a direct, visible impact on the user experience. The changelog is for users, not developers.
- **Compare the actual code between versions** to understand what really changed, rather than just reading commit messages. Commit messages may over- or under-represent the significance of changes.
### Step 6: Update Version in All Files
#### 6a. `package.json`
Update the `version` field:
```json
"version": "X.Y.Z"
```
### Step 7: Copy Changelog to Public Directory
The changelog is served at runtime by the app from the `public/` directory. After updating `CHANGELOG.md`, copy it:
```bash
cp CHANGELOG.md public/CHANGELOG.md
```
### Step 8: Pull Latest Changes
Before committing the release, pull the latest changes from the remote to ensure the release commit sits on top of the latest code. This **must** happen before committing and tagging.
```bash
git pull origin main
```
**CRITICAL**: Always use `git pull` (merge), NEVER `git pull --rebase`. Rebasing rewrites commit hashes, which would orphan any tag pointing to the original commit. Since version tags are often protected on the remote and cannot be deleted or updated, a broken tag cannot be easily fixed.
If there are merge conflicts with the pulled changes, resolve them before proceeding.
### Step 9: Commit the Release
```bash
git add package.json CHANGELOG.md public/CHANGELOG.md
git commit -m "release: vX.Y.Z"
```
### Step 10: Tag the Release
```bash
git tag vX.Y.Z
```
The tag format is `v` followed by the version with no suffix. Examples: `v9.9.0`, `v9.10.0`, `v10.0.0`.
### Step 11: Push
```bash
git push origin main vX.Y.Z
```
**CRITICAL**: Push only the specific tag being released. NEVER use `--tags` -- that pushes ALL local tags, including stale or deleted ones.
### Step 12: Confirm
After pushing, inform the user:
- The new version number
- A brief summary of what was released
- That CI will handle building and publishing the artifacts
## File Reference
| File | What to update | Notes |
|------|---------------|-------|
| `package.json` | `version` field | Source of truth for the version |
| `CHANGELOG.md` | Prepend new section | User-facing changelog |
| `public/CHANGELOG.md` | Copy from `CHANGELOG.md` | Served at runtime by the app |
## Troubleshooting
### "Nothing to release"
If `git log` shows no commits since the last tag, there genuinely is nothing to release.
### Tests fail
Fix the failing tests before proceeding. The release must not contain broken code.
### Wrong version bumped
If you tagged the wrong version and haven't pushed yet:
```bash
git tag -d vX.Y.Z # delete the local tag
git reset --soft HEAD~1 # undo the commit but keep changes staged
```
Then redo steps 4-10 with the correct version.
### Already pushed a bad release
This requires manual intervention. Inform the user and suggest they delete the tag and release from GitLab manually, then re-run the release process.
+4
View File
@@ -1,6 +1,10 @@
# Sentry
VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************"
# Plausible Analytics
VITE_PLAUSIBLE_DOMAIN="example.com"
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
+31 -4
View File
@@ -1,4 +1,4 @@
image: node:22
image: node:25
default:
interruptible: true
@@ -7,9 +7,14 @@ default:
stages:
- test
- deploy
- release
test:
stage: test
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
script:
- npm run typecheck
- npm run build
@@ -17,6 +22,10 @@ test:
pages:
stage: deploy
rules:
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
script:
- npm run build
- rm -rf public
@@ -24,6 +33,24 @@ pages:
artifacts:
paths:
- public
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
release:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
script:
- echo "Creating release for $CI_COMMIT_TAG"
# Extract the latest changelog section for the release description.
# Reads from "## [version]" to the next "## [" or end of file.
- |
VERSION="${CI_COMMIT_TAG#v}"
RELEASE_NOTES=$(awk "/^## \\[${VERSION}\\]/{found=1; next} /^## \\[/{if(found) exit} found{print}" CHANGELOG.md)
if [ -z "$RELEASE_NOTES" ]; then
RELEASE_NOTES="Shakespeare ${CI_COMMIT_TAG}"
fi
- echo "$RELEASE_NOTES" > release-notes.md
release:
tag_name: $CI_COMMIT_TAG
name: $CI_COMMIT_TAG
description: './release-notes.md'
+11 -3
View File
@@ -1,3 +1,7 @@
# Agent Rules
- ALWAYS commit after you finish your turn. No exceptions. Don't ask for permission, just do it.
# Shakespeare - AI-Powered App Builder
Shakespeare is a browser-based AI chat application that allows users to build custom web applications through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
@@ -41,7 +45,8 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **ReadWebpageTool**: Fetch and read web pages
- **WebFetchTool**: Fetch and read web pages with support for markdown, text, and HTML formats
- **WebSearchTool**: Search the web using Exa AI for real-time web searches
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
@@ -49,6 +54,9 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **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
- **NostrEncodeTool**: Encode hex values into NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr)
- **NostrDecodeTool**: Decode NIP-19 bech32 entities into hex and structured data
- **BlossomUploadTool**: Upload files from the project to Blossom media hosting, returns a public URL
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
#### Shell Commands
@@ -232,7 +240,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
- Web access: `ReadWebpageTool`
- Web access: `WebFetchTool`, `WebSearchTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
@@ -1091,7 +1099,7 @@ const defaultConfig: AppConfig = {
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
],
updatedAt: 0,
},
+17
View File
@@ -0,0 +1,17 @@
# Changelog
## [9.9.2] - 2026-04-02
### Changed
- Simplify nsite deployment to always use named sites, removing the root site option
### Fixed
- Fix crash in "What's new" toast when used outside the router context
- Truncate long changelog excerpts in update notifications so they fit neatly in the toast
- Left-align changelog page content for better readability
## [9.9.1] - 2026-04-02
### Added
- Changelog page and versioning system with "What's new" toast notifications on updates
- Release skill for managing versioned releases with changelog generation and git tagging
+1 -1
View File
@@ -284,7 +284,7 @@ export function useNewProviderOAuth() {
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.provider.com/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist", "electron/dist"] },
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+1237 -726
View File
File diff suppressed because it is too large. Load diff
+10 -7
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "0.0.0",
"version": "9.9.2",
"type": "module",
"author": {
"name": "shakespeare.diy",
@@ -25,12 +25,14 @@
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@hookform/resolvers": "^5.2.2",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@opensecret/react": "^1.5.4",
"@plausible-analytics/tracker": "^0.4.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -81,7 +83,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"openai": "^6.16.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -89,7 +91,7 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.53.0",
"react-hook-form": "^7.71.1",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
@@ -106,7 +108,7 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^3.25.76"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -116,6 +118,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jsdom": "^27.0.0",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
+17
View File
@@ -0,0 +1,17 @@
# Changelog
## [9.9.2] - 2026-04-02
### Changed
- Simplify nsite deployment to always use named sites, removing the root site option
### Fixed
- Fix crash in "What's new" toast when used outside the router context
- Truncate long changelog excerpts in update notifications so they fit neatly in the toast
- Left-align changelog page content for better readability
## [9.9.1] - 2026-04-02
### Added
- Changelog page and versioning system with "What's new" toast notifications on updates
- Release skill for managing versioned releases with changelog generation and git tagging
+5
View File
@@ -48,6 +48,11 @@ export default {
hostname = 'docs.z.ai';
}
// Deployment-provider-specific hacks
if (url.host === 'backboard.railway.com') {
hostname = 'railway.com';
}
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
-11
View File
@@ -1,11 +0,0 @@
import { render } from '@testing-library/react';
import { test, expect } from 'vitest';
import App from './App';
test('App', () => {
const { container } = render(<App />);
// Basic smoke test to ensure App renders without crashing
expect(container).toBeInTheDocument();
})
+39 -38
View File
@@ -8,13 +8,13 @@ import { Suspense, useEffect } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { useAppContext } from '@/hooks/useAppContext';
import { SentryProvider } from '@/components/SentryProvider';
import { PlausibleProvider } from '@/components/PlausibleProvider';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
@@ -28,6 +28,8 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { LockdownModeDetector } from '@/components/LockdownModeDetector';
import AppRouter from './AppRouter';
@@ -52,7 +54,7 @@ const defaultConfig: AppConfig = {
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
],
updatedAt: 0,
@@ -70,11 +72,6 @@ const defaultConfig: AppConfig = {
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
url: "https://gitlab.com/soapbox-pub/mkstack.git",
},
{
name: "Nutstack",
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
url: "https://gitlab.com/lemonknowsall/nutstack.git",
},
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
@@ -91,6 +88,8 @@ const defaultConfig: AppConfig = {
fsPathTemplates: "/templates",
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true,
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || "",
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || "",
};
// Initialize filesystem adapter
@@ -135,37 +134,39 @@ export function App() {
<UnheadProvider head={head}>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<SentryProvider>
<FSProvider fs={fs}>
<ConsoleErrorProvider>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<GitSyncProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSyncProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider>
</SentryProvider>
<PlausibleProvider>
<SentryProvider>
<FSProvider fs={fs}>
<ConsoleErrorProvider>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<GitSyncProvider>
<SessionManagerProvider>
<TooltipProvider>
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<LockdownModeDetector />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSyncProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider>
</SentryProvider>
</PlausibleProvider>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
+9 -6
View File
@@ -1,7 +1,9 @@
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { Toaster } from "./components/ui/toaster";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import { VersionCheck } from "./components/VersionCheck";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
@@ -23,13 +25,13 @@ import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
import { ChangelogPage } from "./pages/ChangelogPage";
export function AppRouter() {
// Use HashRouter in Electron, BrowserRouter in web
const Router = globalThis.electron ? HashRouter : BrowserRouter;
return (
<Router>
<BrowserRouter>
<Toaster />
<VersionCheck />
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
@@ -52,13 +54,14 @@ export function AppRouter() {
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/changelog" element={<ChangelogPage />} />
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</BrowserRouter>
);
}
export default AppRouter;
+3
View File
@@ -19,12 +19,14 @@ interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
projectId: string; // Current project ID for path display
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
projectId,
}: AIMessageItemProps) => {
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
@@ -71,6 +73,7 @@ export const AIMessageItem = memo(({
toolArgs={toolArgs}
state="completed"
result={content}
projectId={projectId}
/>
);
}
+41 -7
View File
@@ -1041,12 +1041,31 @@ export function AIProviderConfigDialog({
<div className="grid gap-2">
<Label htmlFor="provider-auth">{t('authentication')}</Label>
<Select
value={localProvider.nostr ? 'nostr' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
...localProvider,
nostr: value === 'nostr' || undefined,
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
})}
value={localProvider.nostr ? 'nostr' : localProvider.openSecret ? 'opensecret' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
if (value === 'nostr') {
setLocalProvider({
...localProvider,
nostr: true,
openSecret: undefined,
apiKey: undefined
});
} else if (value === 'opensecret') {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: localProvider.openSecret,
apiKey: localProvider.apiKey
});
} else {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: undefined,
apiKey: localProvider.apiKey
});
}
}}
>
<SelectTrigger>
<SelectValue />
@@ -1054,10 +1073,25 @@ export function AIProviderConfigDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{localProvider.openSecret && (
<div className="grid gap-2">
<Label htmlFor="provider-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="provider-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={localProvider.openSecret || ''}
onChange={(e) => setLocalProvider({ ...localProvider, openSecret: e.target.value })}
/>
</div>
)}
{!localProvider.nostr && (
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">{t('apiKey')}</Label>
@@ -1139,7 +1173,7 @@ export function AIProviderConfigDialog({
<div className="space-y-3">
<Label className="text-sm font-medium">{t('paymentMethod')}</Label>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<Tabs value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
+26 -3
View File
@@ -50,7 +50,8 @@ export function AddCustomAIProviderDialog({
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const handleAdd = () => {
@@ -66,6 +67,11 @@ export function AddCustomAIProviderDialog({
provider.apiKey = customApiKey.trim();
} else if (customAuthMethod === 'nostr') {
provider.nostr = true;
} else if (customAuthMethod === 'opensecret') {
provider.openSecret = customOpenSecretUrl.trim();
if (customApiKey.trim()) {
provider.apiKey = customApiKey.trim();
}
}
if (customProxy) {
@@ -81,6 +87,7 @@ export function AddCustomAIProviderDialog({
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setCustomOpenSecretUrl('');
setCustomProxy(false);
onOpenChange(false);
@@ -89,6 +96,7 @@ export function AddCustomAIProviderDialog({
const isValid = customProviderName.trim() &&
customProviderId.trim() &&
customBaseURL.trim() &&
(customAuthMethod !== 'opensecret' || customOpenSecretUrl.trim()) &&
!existingIds.includes(customProviderId.trim());
const idExists = existingIds.includes(customProviderId.trim());
@@ -156,7 +164,7 @@ export function AddCustomAIProviderDialog({
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr') => {
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
@@ -169,11 +177,26 @@ export function AddCustomAIProviderDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'api-key' && (
{customAuthMethod === 'opensecret' && (
<div className="grid gap-2">
<Label htmlFor="custom-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="custom-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={customOpenSecretUrl}
onChange={(e) => setCustomOpenSecretUrl(e.target.value)}
/>
</div>
)}
{(customAuthMethod === 'api-key' || customAuthMethod === 'opensecret') && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
+46 -37
View File
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { UrlListEditor } from '@/components/UrlListEditor';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
@@ -28,6 +29,7 @@ import type {
NsiteProvider,
CloudflareProvider,
DenoDeployProvider,
RailwayProvider,
} from '@/contexts/DeploySettingsContext';
// Type for provider without the 'id' field (will be generated)
@@ -37,7 +39,8 @@ type DeployProviderInput =
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
| Omit<CloudflareProvider, 'id'>
| Omit<DenoDeployProvider, 'id'>;
| Omit<DenoDeployProvider, 'id'>
| Omit<RailwayProvider, 'id'>;
interface AddCustomProviderDialogProps {
open: boolean;
@@ -51,7 +54,7 @@ export function AddCustomProviderDialog({
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
@@ -61,8 +64,8 @@ export function AddCustomProviderDialog({
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState('');
const [customBlossomServers, setCustomBlossomServers] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
const [customBlossomServers, setCustomBlossomServers] = useState<string[]>([]);
const handleAdd = () => {
if (!customProviderType || !customName.trim()) return;
@@ -82,12 +85,8 @@ export function AddCustomProviderDialog({
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'nsite.lol',
relayUrls: customRelayUrls.trim()
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
: ['wss://relay.nostr.band'],
blossomServers: customBlossomServers.trim()
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
: ['https://blossom.primal.net/'],
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
@@ -129,6 +128,15 @@ export function AddCustomProviderDialog({
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'railway') {
if (!customApiKey.trim()) return;
provider = {
type: 'railway',
name: customName.trim(),
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else {
return; // Unknown type
}
@@ -146,8 +154,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls('');
setCustomBlossomServers('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
onOpenChange(false);
};
@@ -156,7 +164,8 @@ export function AddCustomProviderDialog({
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim())));
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
(customProviderType !== 'railway' || true)));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -175,7 +184,7 @@ export function AddCustomProviderDialog({
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
@@ -186,8 +195,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls('');
setCustomBlossomServers('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
}}
>
<SelectTrigger>
@@ -200,6 +209,7 @@ export function AddCustomProviderDialog({
<SelectItem value="vercel">Vercel</SelectItem>
<SelectItem value="cloudflare">Cloudflare</SelectItem>
<SelectItem value="deno">Deno Deploy</SelectItem>
<SelectItem value="railway">Railway</SelectItem>
</SelectContent>
</Select>
</div>
@@ -236,7 +246,7 @@ export function AddCustomProviderDialog({
) : customProviderType === 'nsite' ? (
<>
<p className="text-sm text-muted-foreground">
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
Deploy to Nostr as a static website. Uses a kind 15128 site manifest event and Blossom file storage.
</p>
<div className="grid gap-2">
<Label htmlFor="custom-gateway">Gateway</Label>
@@ -247,24 +257,20 @@ export function AddCustomProviderDialog({
onChange={(e) => setCustomGateway(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
<Input
id="custom-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={customRelayUrls}
onChange={(e) => setCustomRelayUrls(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
<Input
id="custom-blossom"
placeholder="https://blossom.primal.net/"
value={customBlossomServers}
onChange={(e) => setCustomBlossomServers(e.target.value)}
/>
</div>
<UrlListEditor
label="Relay URLs"
items={customRelayUrls}
onChange={setCustomRelayUrls}
protocol="wss"
placeholder="relay.ditto.pub"
/>
<UrlListEditor
label="Blossom Servers"
items={customBlossomServers}
onChange={setCustomBlossomServers}
protocol="https"
placeholder="blossom.primal.net"
/>
</>
) : (
<>
@@ -299,7 +305,8 @@ export function AddCustomProviderDialog({
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
'Access Token'} <span className="text-destructive">*</span>
customProviderType === 'railway' ? 'API Token' :
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
@@ -319,7 +326,9 @@ export function AddCustomProviderDialog({
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: 'https://api.cloudflare.com/client/v4'
: customProviderType === 'railway'
? 'https://backboard.railway.com'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
+567
View File
@@ -0,0 +1,567 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from '@/components/ui/dialog';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { useAppEvent } from '@/hooks/useAppEvent';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useQueryClient } from '@tanstack/react-query';
import { DotAI } from '@/lib/DotAI';
import { buildAppEvent } from '@/lib/appEvent';
import {
Loader2,
Save,
Plus,
X,
ExternalLink,
Pencil,
Upload,
ChevronDown,
CircleHelp,
} from 'lucide-react';
import type { NostrEvent } from '@nostrify/nostrify';
interface AppDialogProps {
projectId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface AppFormData {
name: string;
about: string;
picture: string;
website: string;
dTag: string;
supportedKinds: string[];
webHandlers: Array<{ url: string; type: string }>;
}
/** Parse a kind 31990 event into form data */
function eventToFormData(event: NostrEvent): AppFormData {
let metadata: Record<string, string> = {};
try {
if (event.content) {
metadata = JSON.parse(event.content);
}
} catch {
// Invalid JSON content, use empty metadata
}
const dTag = event.tags.find(([t]) => t === 'd')?.[1] ?? '';
const supportedKinds = event.tags
.filter(([t]) => t === 'k')
.map(([, v]) => v)
.filter(Boolean);
const webHandlers = event.tags
.filter(([t]) => t === 'web')
.map(([, url, type]) => ({ url: url ?? '', type: type ?? '' }));
return {
name: metadata.name ?? '',
about: metadata.about ?? '',
picture: metadata.picture ?? '',
website: metadata.website ?? '',
dTag,
supportedKinds,
webHandlers,
};
}
/** Convert a slug like "my-cool-app" to title case like "My Cool App" */
function toTitleCase(slug: string): string {
return slug
.replace(/[-_]+/g, ' ')
.replace(/\b\w/g, (c) => c.toUpperCase())
.trim();
}
/** Create empty form data for a new app */
function emptyFormData(projectId: string): AppFormData {
return {
name: toTitleCase(projectId),
about: '',
picture: '',
website: '',
dTag: projectId,
supportedKinds: [],
webHandlers: [],
};
}
export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
const { mutateAsync: publishEvent } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const cwd = `${projectsPath}/${projectId}`;
const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd });
const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId);
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
const [isSaving, setIsSaving] = useState(false);
const [newKind, setNewKind] = useState('');
const [newHandlerUrl, setNewHandlerUrl] = useState('');
const [newHandlerType, setNewHandlerType] = useState('');
const [advancedOpen, setAdvancedOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Get the deployed URL from project deploy settings
const deployedUrl = (() => {
if (!deploySettings?.currentProvider || !deploySettings?.providers) return null;
const config = deploySettings.providers[deploySettings.currentProvider];
return config?.url ?? null;
})();
// Populate form when event loads
useEffect(() => {
if (event) {
setFormData(eventToFormData(event));
} else if (!isLoading && !hasApp) {
setFormData(emptyFormData(projectId));
}
}, [event, isLoading, hasApp, projectId]);
// Auto-fill website from deployment URL when creating a new app (not editing existing)
useEffect(() => {
if (!hasApp && !isDeployLoading && deployedUrl && !formData.website) {
setFormData(prev => ({ ...prev, website: deployedUrl }));
}
}, [hasApp, isDeployLoading, deployedUrl, formData.website]);
const updateField = useCallback(<K extends keyof AppFormData>(key: K, value: AppFormData[K]) => {
setFormData(prev => ({ ...prev, [key]: value }));
}, []);
const addKind = useCallback(() => {
const kind = newKind.trim();
if (kind && !formData.supportedKinds.includes(kind)) {
updateField('supportedKinds', [...formData.supportedKinds, kind]);
setNewKind('');
}
}, [newKind, formData.supportedKinds, updateField]);
const removeKind = useCallback((kind: string) => {
updateField('supportedKinds', formData.supportedKinds.filter(k => k !== kind));
}, [formData.supportedKinds, updateField]);
const addHandler = useCallback(() => {
const url = newHandlerUrl.trim();
if (url) {
updateField('webHandlers', [...formData.webHandlers, { url, type: newHandlerType.trim() }]);
setNewHandlerUrl('');
setNewHandlerType('');
}
}, [newHandlerUrl, newHandlerType, formData.webHandlers, updateField]);
const removeHandler = useCallback((index: number) => {
updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index));
}, [formData.webHandlers, updateField]);
const handleIconUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) {
updateField('picture', url);
toast({ title: 'Icon uploaded', description: 'Your app icon has been uploaded.' });
}
} catch (error) {
toast({
title: 'Upload failed',
description: error instanceof Error ? error.message : 'Failed to upload icon.',
variant: 'destructive',
});
} finally {
// Reset input so re-selecting the same file triggers onChange
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [uploadFile, updateField, toast]);
const handleSave = async () => {
if (!user) {
toast({
title: 'Not logged in',
description: 'You must be logged in with Nostr to publish an app.',
variant: 'destructive',
});
return;
}
if (!formData.name.trim()) {
toast({
title: 'Name required',
description: 'Please enter a name for your app.',
variant: 'destructive',
});
return;
}
if (!formData.dTag.trim()) {
toast({
title: 'Identifier required',
description: 'Please enter a unique identifier (d-tag) for your app.',
variant: 'destructive',
});
return;
}
setIsSaving(true);
try {
// Build event content and tags
const { content, tags } = await buildAppEvent(
{
name: formData.name,
about: formData.about,
picture: formData.picture,
website: formData.website,
dTag: formData.dTag,
supportedKinds: formData.supportedKinds,
webHandlers: formData.webHandlers,
},
{ fs, cwd, pubkey: user.pubkey },
);
// Publish the event
const published = await publishEvent({
kind: 31990,
content,
tags,
});
// Store the "a" coordinate in .git/shakespeare/app.json
const aValue = `31990:${published.pubkey}:${formData.dTag.trim()}`;
const dotAI = new DotAI(fs, cwd);
await dotAI.writeAppConfig({ a: aValue });
// Invalidate queries
await queryClient.invalidateQueries({ queryKey: ['app-event'] });
await refetch();
toast({
title: hasApp ? 'App updated' : 'App published',
description: `"${formData.name}" has been ${hasApp ? 'updated' : 'published'} to Nostr.`,
});
onOpenChange(false);
} catch (error) {
console.error('Failed to publish app:', error);
toast({
title: 'Failed to publish',
description: error instanceof Error ? error.message : 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsSaving(false);
}
};
if (!user) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>App</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
You must be logged in with Nostr to manage your app.
</p>
</DialogContent>
</Dialog>
);
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{hasApp ? 'Edit App' : 'Publish App'}</DialogTitle>
<DialogDescription>
{hasApp
? 'Update your app\'s listing on Nostr.'
: 'Publish your project as a Nostr app.'}
</DialogDescription>
</DialogHeader>
{isLoading ? (
<div className="space-y-4">
<div className="flex items-start gap-4">
<Skeleton className="h-20 w-20 rounded-2xl flex-shrink-0" />
<div className="flex-1 space-y-2 pt-1">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
</div>
</div>
<Skeleton className="h-10 w-full" />
</div>
) : (
<div className="space-y-5">
{/* App Preview Card */}
<div className="flex items-start gap-4">
{/* Icon with upload */}
<div className="relative flex-shrink-0 group">
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleIconUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isSaving || isUploading}
className="relative block rounded-2xl overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none"
>
{formData.picture ? (
<>
<Avatar className="h-20 w-20 rounded-2xl">
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
<AvatarFallback className="rounded-2xl bg-muted" />
</Avatar>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
{isUploading ? (
<Loader2 className="h-5 w-5 text-white animate-spin" />
) : (
<Pencil className="h-4 w-4 text-white" />
)}
</div>
</>
) : (
<div className="h-20 w-20 rounded-2xl bg-muted flex items-center justify-center transition-colors group-hover:bg-muted-foreground">
{isUploading ? (
<Loader2 className="h-6 w-6 text-muted-foreground animate-spin group-hover:text-background" />
) : (
<Upload className="h-6 w-6 text-muted-foreground transition-colors group-hover:text-background" />
)}
</div>
)}
</button>
</div>
{/* Name & Description inline */}
<div className="flex-1 min-w-0 space-y-2">
<Input
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="App Name"
disabled={isSaving}
/>
<Textarea
value={formData.about}
onChange={e => updateField('about', e.target.value)}
placeholder="A short description of your app..."
rows={2}
disabled={isSaving}
className="resize-none"
/>
</div>
</div>
{/* Website */}
<div className="space-y-1.5">
<Label htmlFor="app-website" className="text-xs text-muted-foreground">Website</Label>
<Input
id="app-website"
value={formData.website}
onChange={e => updateField('website', e.target.value)}
placeholder={deployedUrl || 'https://myapp.example.com'}
disabled={isSaving}
/>
</div>
{/* Existing app coordinate info */}
{aTag && (
<div className="text-xs text-muted-foreground space-y-1">
<p className="font-medium">Nostr Coordinate</p>
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
</div>
)}
{/* Advanced Section */}
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
<CollapsibleTrigger asChild>
<button
type="button"
className="flex items-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2 border-t"
>
<ChevronDown className={`h-4 w-4 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
<span>Advanced</span>
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-4 pt-2">
{/* Hint to use AI */}
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
<span>Not sure? Ask Shakespeare to update your app.</span>
</div>
{/* Identifier (d-tag) */}
<div className="space-y-1.5">
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
<Input
id="app-dtag"
value={formData.dTag}
onChange={e => updateField('dTag', e.target.value)}
placeholder="my-app"
disabled={isSaving || hasApp}
/>
<p className="text-xs text-muted-foreground">
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
</p>
</div>
{/* Supported Kinds */}
<div className="space-y-1.5">
<Label className="text-xs">Supported Event Kinds</Label>
{formData.supportedKinds.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.supportedKinds.map(kind => (
<Badge key={kind} variant="secondary" className="gap-1">
{kind}
<button
onClick={() => removeKind(kind)}
disabled={isSaving}
className="hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newKind}
onChange={e => setNewKind(e.target.value)}
placeholder="Kind number (e.g. 1)"
disabled={isSaving}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault();
addKind();
}
}}
className="flex-1"
/>
<Button
variant="outline"
size="sm"
onClick={addKind}
disabled={isSaving || !newKind.trim()}
className="h-9"
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
{/* Web Handlers */}
<div className="space-y-1.5">
<Label className="text-xs">Web Handlers</Label>
{formData.webHandlers.length > 0 && (
<div className="space-y-1.5">
{formData.webHandlers.map((handler, index) => (
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="truncate flex-1">{handler.url}</span>
{handler.type && (
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
)}
<button
onClick={() => removeHandler(index)}
disabled={isSaving}
className="hover:text-destructive flex-shrink-0"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newHandlerUrl}
onChange={e => setNewHandlerUrl(e.target.value)}
placeholder="https://app.example.com/e/<bech32>"
disabled={isSaving}
className="flex-1"
/>
<Input
value={newHandlerType}
onChange={e => setNewHandlerType(e.target.value)}
placeholder="nevent"
disabled={isSaving}
className="w-24"
/>
<Button
variant="outline"
size="sm"
onClick={addHandler}
disabled={isSaving || !newHandlerUrl.trim()}
className="h-9"
>
<Plus className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
</p>
</div>
</div>
</CollapsibleContent>
</Collapsible>
{/* Save Button */}
<Button
onClick={handleSave}
disabled={isSaving || !formData.name.trim()}
className="w-full gap-2"
>
{isSaving ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Save className="h-4 w-4" />
)}
{isSaving
? (hasApp ? 'Updating...' : 'Publishing...')
: (hasApp ? 'Update App' : 'Publish App')}
</Button>
</div>
)}
</DialogContent>
</Dialog>
);
}
+2
View File
@@ -60,6 +60,8 @@ const AppConfigSchema = z.object({
sentryDsn: z.string(),
sentryEnabled: z.boolean(),
systemPrompt: z.string(),
plausibleDomain: z.string(),
plausibleEndpoint: z.string(),
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
+2 -2
View File
@@ -9,7 +9,7 @@ import { getSentryInstance } from '@/lib/sentry';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
onError?: (error: Error, info: { componentStack: string | null }) => void;
onError?: (error: Error, info: { componentStack?: string | null }) => void;
/** Whether to report errors to Sentry (default: true) */
reportToSentry?: boolean;
}
@@ -91,7 +91,7 @@ export function ErrorBoundary({
onError,
reportToSentry = true,
}: ErrorBoundaryProps) {
const handleError = (error: Error, info: { componentStack: string | null }) => {
const handleError = (error: Error, info: { componentStack?: string | null }) => {
// Log error details for debugging
console.error('ErrorBoundary caught an error:', error, info);
+2 -2
View File
@@ -33,10 +33,10 @@ export function ExternalFavicon({
const parsedUrl = new URL(url);
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.|enclave\.)/, '');
// Normalize the URL to ensure it has a protocol
return faviconUrl(config.faviconUrl, parsedUrl);
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
} catch {
return;
}
+73
View File
@@ -0,0 +1,73 @@
import { useEffect, useState } from 'react';
import {
AlertDialog,
AlertDialogContent,
AlertDialogDescription,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
/**
* Detects if IndexedDB is unavailable (which happens in iOS lockdown mode)
* and displays a blocking alert dialog informing the user.
*/
export function LockdownModeDetector() {
const [isLockdownMode, setIsLockdownMode] = useState(false);
useEffect(() => {
// Check if IndexedDB is available
const checkIndexedDB = async () => {
try {
// Check if IndexedDB exists
if (!window.indexedDB) {
setIsLockdownMode(true);
return;
}
// Try to open a test database to verify IndexedDB actually works
// In iOS lockdown mode, indexedDB exists but throws errors when used
const testDBName = '_shakespeare_lockdown_test';
const request = window.indexedDB.open(testDBName, 1);
request.onerror = () => {
setIsLockdownMode(true);
};
request.onsuccess = () => {
// IndexedDB is working, clean up test database
request.result.close();
window.indexedDB.deleteDatabase(testDBName);
};
} catch {
// Any error means IndexedDB is not available
setIsLockdownMode(true);
}
};
checkIndexedDB();
}, []);
return (
<AlertDialog open={isLockdownMode}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-left">🔒 Lockdown Mode Detected</AlertDialogTitle>
<AlertDialogDescription className="space-y-3 text-left">
<p>
Shakespeare requires IndexedDB to function, which is unavailable in iOS Lockdown Mode.
</p>
<p>
To use Shakespeare, please disable Lockdown Mode in your device settings:
</p>
<ol className="list-decimal list-inside space-y-1 text-left ml-4">
<li>Open Settings</li>
<li>Go to Privacy &amp; Security</li>
<li>Tap Lockdown Mode</li>
<li>Turn off Lockdown Mode</li>
</ol>
</AlertDialogDescription>
</AlertDialogHeader>
</AlertDialogContent>
</AlertDialog>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { ReactNode, useEffect, useRef } from 'react';
import { useAppContext } from '@/hooks/useAppContext';
interface PlausibleProviderProps {
children: ReactNode;
}
/**
* Reactively initializes Plausible Analytics from AppConfig.
* Plausible's `init()` can only be called once, so we guard with a ref.
*/
export function PlausibleProvider({ children }: PlausibleProviderProps) {
const { config } = useAppContext();
const initializedRef = useRef(false);
useEffect(() => {
if (initializedRef.current || !config.plausibleDomain) return;
initializedRef.current = true;
import('@plausible-analytics/tracker').then(({ init }) => {
init({
domain: config.plausibleDomain,
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
});
}).catch(console.error);
}, [config.plausibleDomain, config.plausibleEndpoint]);
return <>{children}</>;
}
+1
View File
@@ -327,6 +327,7 @@ export function ProjectSidebar({
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
title={(onClose && isMobile) ? t('closeSidebar') : t('hidePaneButtonTooltip')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
+13 -3
View File
@@ -14,6 +14,7 @@ import {
ChevronDown,
Trash2,
Star,
AppWindow,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
@@ -27,7 +28,7 @@ interface ProjectTitleMenuProps {
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
isAILoading: boolean;
onApp: () => void;
isAnyLoading: boolean;
className?: string;
}
@@ -40,7 +41,7 @@ export function ProjectTitleMenu({
onDuplicate,
onDelete,
onProjectDetails,
isAILoading,
onApp,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
@@ -100,6 +101,15 @@ export function ProjectTitleMenu({
Project Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={onApp}
disabled={isAnyLoading}
className="gap-2"
>
<AppWindow className="h-4 w-4" />
App
</DropdownMenuItem>
<DropdownMenuItem
onClick={onGitHistory}
disabled={isAnyLoading}
@@ -111,7 +121,7 @@ export function ProjectTitleMenu({
<DropdownMenuItem
onClick={onNewChat}
disabled={isAILoading}
disabled={isAnyLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
+23 -29
View File
@@ -17,6 +17,7 @@ import {
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { UrlListEditor } from '@/components/UrlListEditor';
interface ProviderConfigDialogProps {
open: boolean;
@@ -138,34 +139,22 @@ export function ProviderConfigDialog({
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-relays">
Relay URLs (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id="provider-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={localProvider.relayUrls?.join(', ') || ''}
onChange={(e) => setLocalProvider({
...localProvider,
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-blossom">
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id="provider-blossom"
placeholder="https://blossom.primal.net/"
value={localProvider.blossomServers?.join(', ') || ''}
onChange={(e) => setLocalProvider({
...localProvider,
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
<UrlListEditor
label="Relay URLs"
items={localProvider.relayUrls ?? []}
onChange={(urls) => setLocalProvider({ ...localProvider, relayUrls: urls })}
protocol="wss"
placeholder="relay.ditto.pub"
required
/>
<UrlListEditor
label="Blossom Servers"
items={localProvider.blossomServers ?? []}
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
protocol="https"
placeholder="blossom.primal.net"
required
/>
</>
) : (
<>
@@ -212,6 +201,8 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
}
}}
/>
@@ -227,7 +218,8 @@ export function ProviderConfigDialog({
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
'Base URL'
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
'Base URL'
}
value={localProvider.baseURL || ''}
onChange={(e) => {
@@ -239,6 +231,8 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
}
}}
/>
+8
View File
@@ -45,6 +45,8 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -87,6 +89,8 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -130,6 +134,8 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -176,6 +182,8 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
+164 -31
View File
@@ -1,13 +1,20 @@
import { useState, useCallback, memo } from 'react';
import { useState, useCallback, memo, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
export interface SlashCommand {
name: string;
description: string;
action: () => void;
}
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
@@ -29,6 +36,7 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
slashCommands?: SlashCommand[];
}
export const ChatInput = memo(function ChatInput({
@@ -52,10 +60,15 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
slashCommands = [],
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [showSlashCommands, setShowSlashCommands] = useState(false);
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -78,16 +91,110 @@ export const ChatInput = memo(function ChatInput({
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const executeSlashCommand = useCallback((command: SlashCommand) => {
setInput('');
setShowSlashCommands(false);
setSelectedCommandIndex(0);
command.action();
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
// Handle arrow key navigation when slash commands are showing
if (showSlashCommands && filteredCommands.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev < filteredCommands.length - 1 ? prev + 1 : 0
);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev > 0 ? prev - 1 : filteredCommands.length - 1
);
return;
}
// If slash commands are showing and user presses Enter or Tab, select the highlighted command
if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {
e.preventDefault();
executeSlashCommand(filteredCommands[selectedCommandIndex]);
return;
}
// If slash commands are showing and user presses Escape, close the popover
if (e.key === 'Escape') {
e.preventDefault();
setShowSlashCommands(false);
setSelectedCommandIndex(0);
return;
}
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
}, [handleSend, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
const value = e.target.value;
setInput(value);
// Check if slash command autocomplete should be shown
if (value.startsWith('/') && !value.includes(' ') && slashCommands.length > 0) {
const query = value.slice(1).toLowerCase();
const filtered = slashCommands.filter(cmd =>
cmd.name.toLowerCase().includes(query)
);
setFilteredCommands(filtered);
setShowSlashCommands(filtered.length > 0);
setSelectedCommandIndex(0); // Reset selection when filtering
} else {
setShowSlashCommands(false);
setSelectedCommandIndex(0);
}
}, [slashCommands]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// Call parent's drop handler for visual state management
onDrop(e);
// Extract files from the drop event
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
}, [onDrop]);
// Close popover when clicking outside
useEffect(() => {
if (!showSlashCommands) return;
const handleClickOutside = (e: MouseEvent) => {
// Check if click is outside the popover and textarea
const target = e.target as Node;
if (textareaRef.current && !textareaRef.current.contains(target)) {
setShowSlashCommands(false);
}
};
// Use a slight delay to avoid closing immediately on focus
const timeoutId = setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('click', handleClickOutside);
};
}, [showSlashCommands]);
return (
<div className="border-t p-4">
@@ -99,35 +206,61 @@ export const ChatInput = memo(function ChatInput({
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
<div className="relative">
<Textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{showSlashCommands && filteredCommands.length > 0 && (
<div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border bg-popover p-0 text-popover-foreground shadow-md z-50">
<Command value={filteredCommands[selectedCommandIndex]?.name}>
<CommandList>
<CommandGroup>
{filteredCommands.map((command) => (
<CommandItem
key={command.name}
value={command.name}
onSelect={() => executeSlashCommand(command)}
className="cursor-pointer"
>
<div className="flex flex-col gap-1">
<div className="font-medium">/{command.name}</div>
<div className="text-xs text-muted-foreground">{command.description}</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</div>
)}
</div>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
+118 -23
View File
@@ -18,9 +18,11 @@ import { useMCPTools } from '@/hooks/useMCPTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { ReadTool } from '@/lib/tools/ReadTool';
import { WriteTool } from '@/lib/tools/WriteTool';
import { EditTool } from '@/lib/tools/EditTool';
import { GlobTool } from '@/lib/tools/GlobTool';
import { GrepTool } from '@/lib/tools/GrepTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
@@ -33,13 +35,21 @@ import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool';
import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
import { NostrEncodeTool } from '@/lib/tools/NostrEncodeTool';
import { NostrDecodeTool } from '@/lib/tools/NostrDecodeTool';
import { BlossomUploadTool } from '@/lib/tools/BlossomUploadTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { SkillTool } from '@/lib/tools/SkillTool';
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
import { AppTool } from '@/lib/tools/AppTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
@@ -47,11 +57,13 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { AIMessage } from '@/lib/SessionManager';
import { getAllSkills } from '@/lib/skills';
// Clean interfaces now handled by proper hooks
@@ -91,12 +103,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const queryClient = useQueryClient();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const scrolledProjectsRef = useRef(new Set<string>());
const shouldScrollToBottomRef = useRef(false);
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
const [showToolsDialog, setShowToolsDialog] = useState(false);
const [availableSkills, setAvailableSkills] = useState<Array<{ name: string; description: string; path: string; plugin: string }>>([]);
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
@@ -167,16 +182,34 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
}, [queryClient, cwd]);
// Load available skills
useEffect(() => {
const loadSkills = async () => {
const skills = await getAllSkills(fs, pluginsPath, cwd);
setAvailableSkills(skills);
};
loadSkills().catch(err => {
console.error('Failed to load skills:', err);
setAvailableSkills([]);
});
}, [fs, pluginsPath, cwd]);
// Fetch MCP tools
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
// Separate built-in tools from MCP tools for clarity
const builtInTools = useMemo(() => {
const tools: Record<string, Tool<unknown>> = {
// File operation tools (OpenCode-compatible API)
read: new ReadTool(fs, cwd, { projectsPath }),
write: new WriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
edit: new EditTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
glob: new GlobTool(fs, cwd),
grep: new GrepTool(fs, cwd),
// Other tools
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
@@ -188,9 +221,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
nostr_publish_events: new NostrPublishEventsTool(),
nostr_encode: new NostrEncodeTool(),
nostr_decode: new NostrDecodeTool(),
blossom_upload: new BlossomUploadTool(fs, cwd, user?.signer),
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath, cwd),
skill: new SkillTool(fs, availableSkills),
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
websearch: new WebSearchTool(),
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
app: new AppTool(
fs,
cwd,
user?.signer,
user?.pubkey,
config.relayMetadata.relays.filter(r => r.write).map(r => r.url),
),
};
// Add generate_image tool if imageModel is configured
@@ -242,7 +289,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, config.relayMetadata, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
@@ -489,30 +536,46 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
// Auto-scroll if:
// 1. User just sent a message (shouldScrollToBottomRef is true), OR
// 2. User was already near the bottom
if (shouldScrollToBottomRef.current || isNearBottom) {
// Double requestAnimationFrame ensures scroll happens after layout and paint
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
});
});
shouldScrollToBottomRef.current = false; // Reset the flag
}
}
}, [messages, streamingMessage, isLoading]);
// Remove project from scrolled set when loading starts (so it can scroll again after loading)
useEffect(() => {
if (isLoadingHistory) {
scrolledProjectsRef.current.delete(projectId);
}
}, [projectId, isLoadingHistory]);
// 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);
if (projectId && !scrolledProjectsRef.current.has(projectId) && !isLoadingHistory && messages.length > 0) {
// Use double RAF to ensure DOM is fully rendered after isLoadingHistory becomes false
requestAnimationFrame(() => {
requestAnimationFrame(() => {
scrollToBottom();
scrolledProjectsRef.current.add(projectId);
});
});
}
}, [projectId, scrolledProjects, scrollToBottom]);
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
// Drag and drop handlers
const handleDragEnter = useCallback((e: React.DragEvent) => {
@@ -577,6 +640,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// Mark that we should scroll to bottom when the message is added
shouldScrollToBottomRef.current = true;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
@@ -599,6 +665,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [onFirstInteraction]);
// Slash commands
const slashCommands: SlashCommand[] = [
{
name: 'new',
description: 'Start a new chat session',
action: () => {
internalStartNewSession();
onNewChat();
},
},
{
name: 'tools',
description: "View the current session's available tools",
action: () => setShowToolsDialog(true),
},
];
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
startNewSession: () => {
@@ -618,6 +701,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
projectId={projectId}
/>
)}
{/* Show tool call in "calling" state if streaming tool call is in progress */}
@@ -633,6 +717,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="calling"
projectId={projectId}
/>
) : (
<>
@@ -669,6 +754,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="waiting"
projectId={projectId}
/>
);
}
@@ -800,6 +886,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
message={message}
toolCall={toolCall}
projectId={projectId}
/>
);
})}
@@ -872,6 +959,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
slashCommands={slashCommands}
/>
{/* Onboarding Dialog */}
@@ -879,6 +967,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
{/* Tools Dialog */}
<ToolsDialog
open={showToolsDialog}
onOpenChange={setShowToolsDialog}
tools={tools}
/>
</div>
);
});
+282 -146
View File
@@ -10,17 +10,14 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer, RefreshCw } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BranchSwitcher } from '@/components/BranchSwitcher';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { type DeviceMode } from '@/components/ui/device-toggle';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -77,14 +74,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [buildError, setBuildError] = useState<string | null>(null);
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const [isLogsOpen, setIsLogsOpen] = useState(false);
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframePanelRef = useRef<ImperativePanelHandle>(null);
const logsPanelRef = useRef<ImperativePanelHandle>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
@@ -177,19 +178,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [projectId, projectsManager]);
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
}
}, 10);
}
}, [projectId, previewDomain]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
@@ -440,6 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setBuildError(null);
// Reset navigation history and state
setCurrentPath('/');
@@ -464,13 +454,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframeLegacy();
refreshIframe();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
}, [projectId, checkForBuiltProject, refreshIframe]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -500,106 +490,48 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
};
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedAll, setCopiedAll] = useState(false);
const [copiedBuildError, setCopiedBuildError] = useState(false);
const messages = isOpen ? getConsoleMessages() : [];
const messages = isLogsOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const messageCount = messages.length;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 gap-2 relative"
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
sideOffset={4}
>
{/* Messages */}
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
<div className="py-2 px-1 space-y-0">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</div>
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
);
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const copyAllMessagesToClipboard = async () => {
try {
const allMessages = messages.map(msg => msg.message).join('\n');
await navigator.clipboard.writeText(allMessages);
setCopiedAll(true);
setTimeout(() => setCopiedAll(false), 2000);
} catch (error) {
console.error('Failed to copy all messages to clipboard:', error);
}
};
const messageCount = messages.length;
// Programmatically resize panels when isLogsOpen changes
useEffect(() => {
if (isLogsOpen) {
// Open logs panel to 40% and resize iframe to 60%
logsPanelRef.current?.resize(40);
iframePanelRef.current?.resize(60);
} else {
// Close logs panel and expand iframe to 100%
logsPanelRef.current?.resize(0);
iframePanelRef.current?.resize(100);
}
}, [isLogsOpen]);
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
@@ -656,7 +588,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title="Build project"
title={t('buildButtonTooltip')}
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -671,45 +603,249 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
title={t('codeButtonTooltip')}
>
<Code className="h-4 w-4" />
<span className="hidden lg:inline">Code</span>
</Button>
)}
<ConsoleDropdown />
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(!isLogsOpen)}
className={cn("h-8 gap-2 relative", isLogsOpen && "bg-muted")}
title={t('logsButtonTooltip')}
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</div>
</div>
{/* Content area */}
<div className="flex-1 flex items-center justify-center bg-muted/30">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
<div className="flex-1 bg-muted/30 min-h-0 overflow-hidden">
<ResizablePanelGroup direction="vertical" className="h-full">
<ResizablePanel
ref={iframePanelRef}
defaultSize={isLogsOpen ? 60 : 100}
minSize={30}
className="min-h-0"
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
<div className="h-full flex items-center justify-center min-h-0">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted p-4">
<div className="text-center space-y-4 max-w-2xl w-full">
<div>
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
</div>
{buildError && (
<div className="bg-destructive/10 border border-destructive/20 rounded-lg overflow-hidden text-left">
<div className="px-4 py-2 bg-destructive/20 border-b border-destructive/20 flex items-center justify-between">
<p className="font-semibold text-destructive text-sm">Build Failed</p>
<Button
variant="ghost"
size="sm"
onClick={async () => {
try {
await navigator.clipboard.writeText(buildError);
setCopiedBuildError(true);
setTimeout(() => setCopiedBuildError(false), 2000);
} catch (error) {
console.error('Failed to copy error to clipboard:', error);
}
}}
className="h-7 px-2 text-xs hover:bg-destructive/10"
>
{copiedBuildError ? (
<>
<Check className="h-3 w-3 mr-1.5" />
Copied
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
Copy
</>
)}
</Button>
</div>
<ScrollArea className="max-h-48">
<div className="overflow-x-auto">
<pre className="p-4 text-xs font-mono text-destructive whitespace-pre leading-relaxed">{buildError}</pre>
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
)}
<Button
variant="outline"
onClick={() => {
setBuildError(null);
buildProject(undefined, {
onSuccess: () => {
setBuildError(null);
},
onError: (error) => {
console.error('Build failed:', error);
setBuildError(error instanceof Error ? error.message : String(error));
}
});
}}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Building...
</>
) : buildError ? (
<>
<RefreshCw className="h-4 w-4" />
Retry
</>
) : (
<>
<Hammer className="h-4 w-4" />
Build
</>
)}
</Button>
</div>
</div>
)}
</div>
</div>
)}
</ResizablePanel>
<ResizableHandle withHandle className={cn(!isLogsOpen && "hidden")} />
<ResizablePanel
ref={logsPanelRef}
defaultSize={isLogsOpen ? 40 : 0}
minSize={0}
maxSize={isLogsOpen ? undefined : 0}
className="min-h-0 min-w-0"
collapsible
collapsedSize={0}
>
{/* Logs Panel */}
<div className="h-full flex flex-col bg-background border-t overflow-hidden min-h-0 w-full min-w-0">
{/* Logs Header */}
<div className="h-12 px-4 border-b flex items-center justify-between flex-shrink-0">
<div className="flex items-center gap-2">
{hasConsoleErrors && (
<span className="h-2 w-2 rounded-full bg-red-500" />
)}
</div>
<div className="flex items-center gap-2">
{messageCount > 0 && (
<Button
variant="ghost"
size="sm"
onClick={copyAllMessagesToClipboard}
className="h-7 px-2 text-xs"
>
{copiedAll ? (
<>
<Check className="h-3 w-3 mr-1.5 text-success" />
{t('copied')}
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
{t('copyAll')}
</>
)}
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(false)}
className="h-7 w-7 p-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Logs Content */}
<div className="flex-1 min-h-0 overflow-hidden w-full">
<ScrollArea className="h-full w-full">
<div className="p-2 space-y-0 w-full min-w-0 max-w-full">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer w-full max-w-full"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div
className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words w-full min-w-0 max-w-full",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}
style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}
>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</ScrollArea>
</div>
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
{/* Build loading overlay */}
@@ -0,0 +1,59 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import OpenAI from 'openai';
interface ToolsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
}
export function ToolsDialog({ open, onOpenChange, tools }: ToolsDialogProps) {
const toolEntries = Object.entries(tools);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle>Available Tools</DialogTitle>
<DialogDescription>
The current session's full list of available tools ({toolEntries.length} tools)
</DialogDescription>
</DialogHeader>
<ScrollArea className="h-[60vh] w-full pr-4">
<Accordion type="single" collapsible className="w-full space-y-2">
{toolEntries.map(([name, tool]) => {
const func = 'function' in tool ? tool.function : undefined;
return (
<AccordionItem key={name} value={name} className="border rounded-lg px-4">
<AccordionTrigger className="text-sm font-mono hover:no-underline py-3 outline-none focus:outline-none focus-visible:outline-none">
{name}
</AccordionTrigger>
<AccordionContent className="pt-2 pb-4">
<div className="space-y-3 text-sm">
<div>
<div className="font-semibold mb-1">Description:</div>
<div className="text-muted-foreground whitespace-pre-wrap">
{func?.description || 'No description available'}
</div>
</div>
{func?.parameters && (
<div>
<div className="font-semibold mb-1">Parameters:</div>
<pre className="text-xs bg-muted p-3 rounded-md overflow-x-auto">
{JSON.stringify(func.parameters, null, 2)}
</pre>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</ScrollArea>
</DialogContent>
</Dialog>
);
}
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ToolCallDisplay } from './ToolCallDisplay';
describe('ToolCallDisplay', () => {
describe('path stripping', () => {
it('should strip project prefix from absolute paths for read tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/mysite/src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="write"
toolArgs={{ filePath: '/projects/mysite/src/App.tsx', content: 'code' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote src/App.tsx')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for edit tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="edit"
toolArgs={{
filePath: '/projects/mysite/src/components/Header.tsx',
oldString: 'old',
newString: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/components/Header.tsx')).toBeInTheDocument();
});
it('should handle paths without project prefix', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: 'src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should handle legacy text_editor_view tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_view"
toolArgs={{ path: '/projects/mysite/README.md' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed README.md')).toBeInTheDocument();
});
it('should handle legacy text_editor_write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_write"
toolArgs={{ path: '/projects/mysite/package.json', file_text: '{}' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote package.json')).toBeInTheDocument();
});
it('should handle legacy text_editor_str_replace tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_str_replace"
toolArgs={{
path: '/projects/mysite/src/utils.ts',
old_str: 'old',
new_str: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/utils.ts')).toBeInTheDocument();
});
it('should handle different projects with same relative path', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/another-project/src/index.ts' }}
state="completed"
result="File content"
projectId="another-project"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
});
});
+339 -66
View File
@@ -26,12 +26,16 @@ import {
Settings,
TriangleAlert,
X,
Search,
Clipboard,
AppWindow,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ImageModelDialog } from '@/components/ImageModelDialog';
import { ImageLightbox } from '@/components/ImageLightbox';
import { useFSPaths } from '@/hooks/useFSPaths';
interface ToolInfo {
icon: LucideIcon;
@@ -45,6 +49,7 @@ interface ToolCallDisplayProps {
toolArgs: Record<string, unknown>;
state: 'calling' | 'waiting' | 'completed';
result?: string; // The tool result content (only for completed state)
projectId: string; // Current project ID for path display
}
// Component to show image generation errors inline
@@ -77,21 +82,95 @@ function ImageGenerationError() {
);
}
/**
* Strip project path prefix from absolute paths
* e.g., /projects/mysite/src/index.ts -> src/index.ts
*/
function stripProjectPrefix(path: string, projectId?: string, projectsPath = '/projects'): string {
if (!projectId) return path;
const projectPrefix = `${projectsPath}/${projectId}/`;
if (path === `${projectsPath}/${projectId}`) {
return '.';
} else if (path.startsWith(projectPrefix)) {
return path.slice(projectPrefix.length);
}
return path;
}
/**
* Get tool information including icon, title, and calling title
*/
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
switch (toolName) {
case 'shell':
return {
icon: Terminal,
title: args.command ? String(args.command) : 'Shell Command',
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
title: args.command ? String(args.command) : 'Shell command',
callingTitle: args.command ? String(args.command) : 'Running shell command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell command failed',
};
// New tools (OpenCode-compatible names)
case 'read': {
const rawPath = args.filePath ? String(args.filePath) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const offset = typeof args.offset === 'number' ? args.offset : 0;
const limit = typeof args.limit === 'number' ? args.limit : undefined;
const lineInfo = (typeof offset === 'number' && typeof limit === 'number')
? ` (lines ${(offset || 0) + 1}-${limit ? offset + limit : ''})`
: '';
return {
icon: Eye,
title: `Viewed ${path}${lineInfo}`,
callingTitle: `Viewing ${path}${lineInfo}`,
errorTitle: `Failed to view ${path}${lineInfo}`,
};
}
case 'write': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
case 'edit': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'glob':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'File pattern search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching files',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
case 'grep':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'Content search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching content',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
// Legacy tools (kept for old chat history)
case 'text_editor_view': {
const path = args.path ? String(args.path) : 'File';
const rawPath = args.path ? String(args.path) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const hasLineRange = args.start_line || args.end_line;
const lineInfo = hasLineRange
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
@@ -104,21 +183,27 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
};
}
case 'text_editor_write':
case 'text_editor_write': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
case 'text_editor_str_replace':
case 'text_editor_str_replace': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File',
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'npm_add_package': {
const name = args.name ? String(args.name) : 'Package';
@@ -134,25 +219,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
title: args.name ? `Removed ${args.name}` : 'Removed package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to remove package',
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
errorTitle: 'Failed to Commit Changes',
title: args.message ? `Committed: ${args.message}` : 'Committed changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing changes',
errorTitle: 'Failed to commit changes',
};
case 'build_project':
return {
icon: Package,
title: 'Built Project',
callingTitle: 'Building Project',
errorTitle: 'Failed to Build Project',
title: 'Built project',
callingTitle: 'Building project',
errorTitle: 'Failed to build project',
};
case 'nostr_read_nip':
@@ -160,55 +245,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to read NIP',
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
title: args.identifier ? `Viewed ${String(args.identifier).slice(0, 16)}...` : 'Viewed event',
callingTitle: args.identifier ? `Viewing ${String(args.identifier).slice(0, 16)}...` : 'Viewing event',
errorTitle: args.identifier ? `Failed to view ${String(args.identifier).slice(0, 16)}...` : 'Failed to view event',
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
title: args.kind !== undefined ? `Viewed kind ${args.kind}` : 'Viewed kind',
callingTitle: args.kind !== undefined ? `Viewing kind ${args.kind}` : 'Viewing kind',
errorTitle: args.kind !== undefined ? `Failed to view kind ${args.kind}` : 'Failed to view kind',
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
title: args.tag ? `Viewed tag "${args.tag}"` : 'Viewed tag',
callingTitle: args.tag ? `Viewing tag "${args.tag}"` : 'Viewing tag',
errorTitle: args.tag ? `Failed to view tag "${args.tag}"` : 'Failed to view tag',
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
title: args.doc ? `Viewed protocol ${args.doc}` : 'Viewed protocol',
callingTitle: args.doc ? `Viewing protocol ${args.doc}` : 'Viewing protocol',
errorTitle: args.doc ? `Failed to view protocol ${args.doc}` : 'Failed to view protocol',
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index',
callingTitle: 'Reading NIPs Index',
errorTitle: 'Failed to Read NIPs Index',
title: 'Viewed NIPs index',
callingTitle: 'Viewing NIPs index',
errorTitle: 'Failed to view NIPs index',
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
title: args.range ? `Generated ${args.range} kind` : 'Generated kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to generate kind',
};
case 'nostr_publish_events': {
@@ -217,58 +302,136 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to publish Nostr event',
};
}
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to deploy project',
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console',
callingTitle: 'Reading Console',
errorTitle: 'Failed to Read Console',
title: 'Viewed console',
callingTitle: 'Viewing console',
errorTitle: 'Failed to view console',
};
case 'webfetch': {
const url = args.url ? String(args.url) : '';
return {
icon: Globe,
title: url ? `Viewed ${url}` : 'Viewed webpage',
callingTitle: url ? `Viewing ${url}` : 'Viewing webpage',
errorTitle: url ? `Failed to view ${url}` : 'Failed to view webpage',
};
}
case 'websearch': {
const query = args.query ? String(args.query) : '';
return {
icon: Search,
title: query ? `Searched "${query}"` : 'Web search',
callingTitle: query ? `Searching "${query}"` : 'Searching web',
errorTitle: query ? `Failed to search "${query}"` : 'Search failed',
};
}
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill',
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
callingTitle: args.name ? `Running skill: ${args.name}` : 'Running skill',
errorTitle: args.name ? `Skill failed: ${args.name}` : 'Skill failed',
};
case 'generate_image':
return {
icon: Image,
title: args.prompt ? String(args.prompt) : 'Generated Image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
errorTitle: 'Failed to Generate Image',
title: args.prompt ? String(args.prompt) : 'Generated image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating image',
errorTitle: 'Failed to generate image',
};
case 'view_available_models':
return {
icon: Eye,
title: 'Viewed Available Models',
callingTitle: 'Viewing Available Models',
errorTitle: 'Failed to View Available Models',
title: 'Viewed available models',
callingTitle: 'Viewing available models',
errorTitle: 'Failed to view available models',
};
case 'configure_image_generation':
return {
icon: Settings,
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
title: args.model ? `Configured image model: ${args.model}` : 'Configured image generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring image generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to configure image generation',
};
case 'todowrite':
case 'todoread': {
// Try to parse the result to get task counts for the title
let title = toolName === 'todowrite' ? 'Updated todo list' : 'Viewed todo list';
if (result) {
try {
const todos = JSON.parse(result);
if (Array.isArray(todos)) {
const activeTodos = todos.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completedTodos = todos.filter((x: { status: string }) => x.status === 'completed');
const inProgressTask = todos.find((x: { status: string }) => x.status === 'in_progress');
// Format: "[<completed>/<total>] <active-task>" if in_progress task exists
if (inProgressTask) {
const taskName = inProgressTask.content || 'Task';
const totalTasks = todos.length;
title = `[${completedTodos.length + 1}/${totalTasks}] ${taskName}`;
} else if (activeTodos.length === 0 && completedTodos.length > 0) {
// All tasks completed
title = `${completedTodos.length + 1} task${completedTodos.length !== 0 ? 's' : ''} completed`;
} else if (completedTodos.length === 0) {
// No completed tasks yet
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}`;
} else {
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}, ${completedTodos.length} completed`;
}
}
} catch {
// If parsing fails, use default title
}
}
return {
icon: Clipboard,
title,
callingTitle: toolName === 'todowrite' ? 'Updating todo list' : 'Viewing todo list',
errorTitle: toolName === 'todowrite' ? 'Failed to update todo list' : 'Failed to view todo list',
};
}
case 'app': {
const action = args.action as string | undefined;
if (action === 'view_app') {
return {
icon: AppWindow,
title: 'Viewed app',
callingTitle: 'Viewing app',
errorTitle: 'Failed to view app',
};
}
const name = args.name ? String(args.name) : 'app';
return {
icon: AppWindow,
title: `Updated ${name}`,
callingTitle: `Updating ${name}`,
errorTitle: `Failed to update ${name}`,
};
}
default: {
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
return {
@@ -299,12 +462,13 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
/**
* Unified component for displaying tool calls in all states
*/
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const [imageLoadError, setImageLoadError] = useState(false);
const { projectsPath } = useFSPaths();
const toolInfo = getToolInfo(toolName, toolArgs);
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath, result);
const IconComponent = toolInfo.icon;
// Check if this is an error result
@@ -342,19 +506,26 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
// Write tool expanded content (new and legacy)
if ((toolName === 'write' && typeof toolArgs.content === 'string') ||
(toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string')) {
const content = toolName === 'write' ? String(toolArgs.content) : String(toolArgs.file_text);
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{toolArgs.file_text}
{content}
</div>
</div>
);
}
if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') {
const oldLines = String(toolArgs.old_str).split('\n');
const newLines = String(toolArgs.new_str).split('\n');
// Edit tool expanded content (new and legacy)
if ((toolName === 'edit' && typeof toolArgs.oldString === 'string' && typeof toolArgs.newString === 'string') ||
(toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string')) {
const oldStr = toolName === 'edit' ? String(toolArgs.oldString) : String(toolArgs.old_str);
const newStr = toolName === 'edit' ? String(toolArgs.newString) : String(toolArgs.new_str);
const oldLines = oldStr.split('\n');
const newLines = newStr.split('\n');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
@@ -387,6 +558,56 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Read tool expanded content - parse and display file content nicely
if (toolName === 'read' || toolName === 'text_editor_view') {
// Parse the result to extract file content from <file> tags
const fileMatch = result.match(/<file>\n([\s\S]*?)\n\n\((.*?)\)\n<\/file>/);
if (fileMatch) {
const fileContent = fileMatch[1];
const footerMessage = fileMatch[2];
// Split content into lines and parse line numbers
const lines = fileContent.split('\n');
return (
<div className="mt-1 rounded border bg-background text-xs font-mono overflow-hidden">
<div className="max-h-96 overflow-y-auto">
<div>
{lines.map((line, idx) => {
// Parse line number and content (format: " 1| content")
const match = line.match(/^(\s*\d+)\|(.*)$/);
if (match) {
return (
<div key={idx} className="flex hover:bg-muted/30 transition-colors">
<div className="text-muted-foreground/60 select-none px-3 py-0.5 text-right min-w-[3rem] bg-muted/20">
{match[1].trim()}
</div>
<div className="flex-1 px-3 py-0.5 whitespace-pre-wrap break-words">
{match[2]}
</div>
</div>
);
}
// Fallback for lines that don't match expected format
return (
<div key={idx} className="px-3 py-0.5 whitespace-pre-wrap break-words">
{line}
</div>
);
})}
</div>
</div>
{footerMessage && (
<div className="px-3 py-1.5 bg-muted/30 border-t text-muted-foreground text-[10px]">
{footerMessage}
</div>
)}
</div>
);
}
// Fallback to default rendering if no <file> tags found
}
if (toolName === 'generate_image') {
// For generate_image, when expanded show the full prompt
return (
@@ -396,6 +617,58 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Todo tools expanded content
if (toolName === 'todowrite' || toolName === 'todoread') {
try {
const todos = JSON.parse(result);
if (!Array.isArray(todos)) {
throw new Error('Invalid todo format');
}
if (todos.length === 0) {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="text-muted-foreground italic">No todos found</div>
</div>
);
}
// Find the first in_progress task for bold styling
const firstInProgressIndex = todos.findIndex((x: { status: string }) => x.status === 'in_progress');
return (
<div className="mt-1 rounded border bg-muted/30 text-xs overflow-hidden">
<div className="px-3 py-2 space-y-1">
{todos.map((todo: { id: string; content: string; status: string; priority: string }, index: number) => {
const isChecked = todo.status === 'completed' || todo.status === 'cancelled';
const isFirstInProgress = index === firstInProgressIndex;
return (
<div key={todo.id} className="flex items-start gap-2 py-1">
<input
type="checkbox"
checked={isChecked}
readOnly
className="mt-0.5 h-4 w-4 rounded border-gray-300 cursor-default"
/>
<span className={cn(
"flex-1 text-foreground",
isChecked && "line-through text-muted-foreground",
isFirstInProgress && "font-bold"
)}>
{todo.content}
</span>
</div>
);
})}
</div>
</div>
);
} catch {
// If parsing fails, fall through to default rendering
}
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
+147
View File
@@ -0,0 +1,147 @@
import { useState, useRef, KeyboardEvent } from 'react';
import { X, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { cn } from '@/lib/utils';
interface UrlListEditorProps {
/** Label shown above the list */
label: string;
/** Current array of full URLs */
items: string[];
/** Called when the list changes */
onChange: (items: string[]) => void;
/** Controls auto-prefix on bare domain entry */
protocol: 'wss' | 'https';
/** Placeholder shown in the add input */
placeholder?: string;
/** Whether to show the required asterisk */
required?: boolean;
/** Additional CSS classes for the root element */
className?: string;
}
/**
* Normalize a bare domain or partial URL to a fully-qualified URL.
* If the value already has any protocol it is returned as-is.
*/
function normalizeEntry(value: string, protocol: 'wss' | 'https'): string {
const trimmed = value.trim();
if (!trimmed) return '';
if (/^wss?:\/\//i.test(trimmed) || /^https?:\/\//i.test(trimmed)) return trimmed;
return `${protocol}://${trimmed}`;
}
/**
* Convert a URL to an https:// form suitable for favicon lookup.
* wss:// → https://, ws:// → http://
*/
function toHttpsUrl(url: string): string {
return url.replace(/^wss:\/\//i, 'https://').replace(/^ws:\/\//i, 'http://');
}
/** Strip the protocol prefix for compact display */
function displayLabel(url: string): string {
return url.replace(/^wss?:\/\//i, '').replace(/^https?:\/\//i, '');
}
export function UrlListEditor({
label,
items,
onChange,
protocol,
placeholder,
required,
className,
}: UrlListEditorProps) {
const [inputValue, setInputValue] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const handleAdd = () => {
const normalized = normalizeEntry(inputValue, protocol);
if (!normalized) return;
// Silently ignore duplicates
if (items.includes(normalized)) {
setInputValue('');
return;
}
onChange([...items, normalized]);
setInputValue('');
inputRef.current?.focus();
};
const handleRemove = (index: number) => {
onChange(items.filter((_, i) => i !== index));
};
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAdd();
}
};
return (
<div className={cn('grid gap-2', className)}>
<Label>
{label}
{required && <span className="text-destructive ml-1">*</span>}
</Label>
{/* Scrollable list of existing items */}
{items.length > 0 && (
<div className="rounded-md border overflow-y-auto max-h-48">
{items.map((item, index) => (
<div
key={index}
className="flex items-center gap-2 px-3 py-2 hover:bg-muted border-b last:border-b-0"
>
<ExternalFavicon
url={toHttpsUrl(item)}
size={14}
className="shrink-0 opacity-70"
/>
<span className="flex-1 text-sm font-mono truncate">
{displayLabel(item)}
</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6 shrink-0 text-muted-foreground hover:text-destructive"
onClick={() => handleRemove(index)}
aria-label={`Remove ${item}`}
>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
{/* Add input */}
<div className="flex gap-2">
<Input
ref={inputRef}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={placeholder ?? (protocol === 'wss' ? 'relay.example.com' : 'server.example.com')}
className="font-mono text-sm"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleAdd}
disabled={!inputValue.trim()}
aria-label={`Add ${label}`}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
);
}
+70
View File
@@ -0,0 +1,70 @@
import { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { toast } from '@/hooks/useToast';
import { ToastAction } from '@/components/ui/toast';
import { parseChangelog } from '@/lib/changelog';
const STORAGE_KEY = 'shakespeare:app-version';
/** Fetch the first changelog item for the given version (or the latest entry). */
async function fetchChangelogExcerpt(version: string): Promise<string | undefined> {
try {
const res = await fetch('/CHANGELOG.md');
if (!res.ok) return undefined;
const markdown = await res.text();
const entries = parseChangelog(markdown);
// Try to find the entry matching the current version, otherwise use the first entry.
const entry = entries.find((e) => e.version === version) ?? entries[0];
if (!entry) return undefined;
// Return a truncated first item from the first section.
const item = entry.sections[0]?.items[0];
if (!item) return undefined;
if (item.length <= 60) return item;
return item.slice(0, 60).trimEnd() + '…';
} catch {
return undefined;
}
}
/** Compares the running app version against localStorage and shows a toast when the version changes. */
export function VersionCheck() {
useEffect(() => {
const currentVersion = import.meta.env.VERSION;
if (!currentVersion) return;
const storedVersion = localStorage.getItem(STORAGE_KEY);
localStorage.setItem(STORAGE_KEY, currentVersion);
if (storedVersion && storedVersion !== currentVersion) {
// Show the toast immediately, then enrich it with a changelog excerpt.
const { update, id } = toast({
title: `What's new in v${currentVersion}`,
action: (
<ToastAction altText="View changelog" asChild>
<Link to="/changelog">See all</Link>
</ToastAction>
),
});
fetchChangelogExcerpt(currentVersion).then((excerpt) => {
if (excerpt) {
update({
id,
title: `What's new in v${currentVersion}`,
description: excerpt,
action: (
<ToastAction altText="View changelog" asChild>
<Link to="/changelog">See all</Link>
</ToastAction>
),
});
}
});
}
}, []);
return null;
}
@@ -63,10 +63,10 @@ export function CloudflareDeployForm({
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
const [subdomainResponse, workersResponse] = await Promise.all([
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: subdomainUrl }) : subdomainUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: workersUrl }) : workersUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
]);
+1 -1
View File
@@ -56,7 +56,7 @@ export function DenoDeployForm({
try {
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
+3
View File
@@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { DeploySteps } from './DeploySteps';
import { useTranslation } from 'react-i18next';
interface DeployButtonProps {
projectId: string;
@@ -14,6 +15,7 @@ interface DeployButtonProps {
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
const [open, setOpen] = useState(false);
const { t } = useTranslation();
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -24,6 +26,7 @@ export function DeployButton({ projectId, projectName, className, disabled }: De
className={cn("size-8 p-0 group", className)}
aria-label="Deploy project"
disabled={disabled}
title={t('deployButtonTooltip')}
>
<Rocket className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
</Button>
+319 -17
View File
@@ -13,6 +13,9 @@ import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useGit } from '@/hooks/useGit';
import { NostrURI } from '@/lib/NostrURI';
import { Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
@@ -23,6 +26,7 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
@@ -31,6 +35,10 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
import { readNsiteVfsConfig, writeNsiteVfsConfig } from '@/lib/nsiteConfig';
import type { NsiteVfsConfig } from '@/lib/nsiteConfig';
import { projectNameToDTag } from '@/lib/utils/nsite';
/**
* Normalize a URL string to ensure it has a protocol
@@ -42,6 +50,23 @@ function normalizeUrl(url: string): string {
return `https://${url}`;
}
async function resolveNsiteSourceUrl(remoteUrl: string | null): Promise<string | undefined> {
if (!remoteUrl) {
return undefined;
}
if (/^https?:\/\//i.test(remoteUrl)) {
return remoteUrl;
}
if (remoteUrl.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(remoteUrl);
return nostrURI.toString();
}
return undefined;
}
/**
* Render provider icon using favicon or fallback
*/
@@ -80,7 +105,9 @@ interface ShakespeareFormData {
}
interface NsiteFormData {
nsec: string;
siteTitle: string;
siteDescription: string;
dTag: string;
}
interface NetlifyFormData {
@@ -101,6 +128,14 @@ interface DenoDeployFormData {
projectName: string;
}
interface RailwayFormData {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -110,6 +145,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const { git } = useGit();
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
const [isDeploying, setIsDeploying] = useState(false);
@@ -117,12 +154,46 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [error, setError] = useState<string | null>(null);
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
const [nsiteVfsConfigLoading, setNsiteVfsConfigLoading] = useState(true);
// When a .nsite/config.json already exists, hide the full form and show a summary instead.
// The user can click "Edit" to expand it.
const [nsiteShowFullForm, setNsiteShowFullForm] = useState(false);
useEffect(() => {
if (!projectId) {
setNsiteVfsConfigLoading(false);
return;
}
const projectPath = `${projectsPath}/${projectId}`;
readNsiteVfsConfig(fs, projectPath)
.then((cfg) => {
setNsiteVfsConfig(cfg);
// If a config already exists, seed the form from it and stay in summary mode.
// If not, show the full form so the user can configure for the first time.
if (cfg) {
setNsiteForm({
siteTitle: cfg.title ?? '',
siteDescription: cfg.description ?? '',
dTag: (cfg.id != null && cfg.id !== '') ? cfg.id : '',
});
setNsiteShowFullForm(false);
} else {
setNsiteShowFullForm(true);
}
})
.finally(() => setNsiteVfsConfigLoading(false));
}, [fs, projectsPath, projectId]);
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
subdomain: projectId,
});
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
nsec: '',
siteTitle: '',
siteDescription: '',
dTag: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
@@ -138,6 +209,13 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
const [railwayForm, setRailwayForm] = useState<RailwayFormData>({
workspaceId: '',
projectId: '',
environmentId: '',
serviceId: '',
projectName: projectName || projectId,
});
// Load project settings when component mounts
useEffect(() => {
@@ -183,17 +261,25 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider;
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
if (!user) {
throw new Error('You must be logged in to deploy to nsite.');
}
const sourceUrl = await resolveNsiteSourceUrl(
await git.getRemoteURL(projectPath, 'origin')
);
adapter = new NsiteAdapter({
fs,
nostr,
nsec: nsiteForm.nsec,
signer: user.signer,
gateway: nsiteProvider.gateway,
relayUrls: nsiteProvider.relayUrls,
blossomServers: nsiteProvider.blossomServers,
siteTitle: nsiteForm.siteTitle || undefined,
siteDescription: nsiteForm.siteDescription || undefined,
sourceUrl,
siteIdentifier: nsiteForm.dTag || undefined,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider;
@@ -242,6 +328,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
baseDomain: cloudflareProvider.baseDomain,
projectName: cloudflareForm.projectName || undefined,
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
esmUrl: config.esmUrl,
});
} else if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider;
@@ -261,6 +348,23 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'railway') {
const railwayProvider = selectedProvider;
if (!railwayProvider.apiKey) {
throw new Error('Railway API token is required');
}
adapter = new RailwayAdapter({
fs,
apiKey: railwayProvider.apiKey,
baseURL: railwayProvider.baseURL,
workspaceId: railwayForm.workspaceId || undefined,
projectId: railwayForm.projectId || undefined,
environmentId: railwayForm.environmentId || undefined,
serviceId: railwayForm.serviceId || undefined,
projectName: railwayForm.projectName || undefined,
corsProxy: railwayProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -284,9 +388,28 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
type: 'nsite',
url: result.url,
data: {
nsec: nsiteForm.nsec,
siteTitle: nsiteForm.siteTitle || undefined,
siteDescription: nsiteForm.siteDescription || undefined,
dTag: nsiteForm.dTag || undefined,
},
});
// Write .nsite/config.json for nsyte CLI interoperability.
// This file is safe to commit — it never contains the nsec.
const nsiteProvider = selectedProvider;
const newNsiteVfsConfig: NsiteVfsConfig = {
relays: nsiteProvider.relayUrls,
servers: nsiteProvider.blossomServers,
id: nsiteForm.dTag || undefined,
title: nsiteForm.siteTitle || undefined,
description: nsiteForm.siteDescription || undefined,
fallback: '/index.html',
gatewayHostnames: [nsiteProvider.gateway],
};
await writeNsiteVfsConfig(fs, projectPath, newNsiteVfsConfig);
// Update in-memory state so summary view reflects new values immediately
setNsiteVfsConfig(newNsiteVfsConfig);
setNsiteShowFullForm(false);
} else if (selectedProvider.type === 'netlify') {
await updateProjectSettings(selectedProviderId, {
type: 'netlify',
@@ -320,9 +443,67 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'railway') {
await updateProjectSettings(selectedProviderId, {
type: 'railway',
url: result.url,
data: {
workspaceId: railwayForm.workspaceId || undefined,
projectId: result.metadata?.projectId as string | undefined,
environmentId: result.metadata?.environmentId as string | undefined,
serviceId: result.metadata?.serviceId as string | undefined,
},
});
}
setDeployResult(result);
// Update repository announcement with deployment URL if using Nostr git
try {
const projectPath = `${projectsPath}/${projectId}`;
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
const nostrURI = await NostrURI.parse(remoteUrl);
// Query for existing repository announcement
const existingRepos = await nostr.query(
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
{ signal: AbortSignal.timeout(1500) }
);
if (existingRepos.length > 0) {
let changed = false;
let hasWebTag = false;
const repoEvent = structuredClone(existingRepos[0]);
for (const tag of repoEvent.tags) {
if (tag[0] === 'web') {
if (tag[1] !== result.url) {
tag[1] = result.url;
changed = true;
hasWebTag = true;
}
}
}
if (!hasWebTag) {
repoEvent.tags.push(['web', result.url]);
changed = true;
}
// Publish updated repo event if deployment URL changed
if (changed) {
// Publish the updated event
await publishEvent(repoEvent);
}
}
}
} catch (err) {
// Silently fail - updating web tag is not critical for deployment
console.warn('Failed to update repository announcement with deployment URL:', err);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Deployment failed');
} finally {
@@ -336,11 +517,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ nsec: '' });
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
// Return to summary mode so next open shows the compact view (if config exists)
setNsiteShowFullForm(false);
onClose();
};
@@ -352,8 +536,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
setNsiteForm(prev => ({ ...prev, siteTitle }));
// Derive the dTag from the title so the user never has to think about it.
// Falls back to projectName when the title is blank.
projectNameToDTag(siteTitle || projectName).then(dTag => {
setNsiteForm(prev => ({ ...prev, dTag }));
});
}, [projectName]);
const handleNsiteSiteDescriptionChange = useCallback((siteDescription: string) => {
setNsiteForm(prev => ({ ...prev, siteDescription }));
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
@@ -372,6 +565,16 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setDenoDeployForm({ projectName });
}, []);
const handleRailwayConfigChange = useCallback((config: {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}) => {
setRailwayForm(config);
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -392,15 +595,72 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
}
if (selectedProvider.type === 'nsite') {
// While the .nsite/config.json load is still in flight, render nothing to avoid flicker
if (nsiteVfsConfigLoading) return null;
// Summary view: shown when .nsite/config.json already exists and user hasn't clicked Edit
if (nsiteVfsConfig && !nsiteShowFullForm) {
const relayCount = nsiteVfsConfig.relays?.length ?? 0;
const serverCount = nsiteVfsConfig.servers?.length ?? 0;
return (
<div className="space-y-3">
<div className="rounded-md border bg-muted/30 p-3 space-y-2 text-sm">
{nsiteVfsConfig.title && (
<div className="flex justify-between">
<span className="text-muted-foreground">Title</span>
<span className="font-medium">{nsiteVfsConfig.title}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Relays</span>
<span className="font-medium">{relayCount} configured</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Blossom servers</span>
<span className="font-medium">{serverCount} configured</span>
</div>
</div>
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
onClick={() => setNsiteShowFullForm(true)}
>
Edit site settings
</button>
</div>
);
}
// Full config form: shown on first deploy or when user clicks "Edit site settings"
const savedConfig = projectSettings.providers[selectedProviderId];
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
const legacy = savedConfig?.type === 'nsite' ? savedConfig.data : undefined;
// .nsite/config.json wins; .git/shakespeare/deploy.json is the legacy fallback
const savedSiteTitle = nsiteVfsConfig?.title ?? legacy?.siteTitle;
const savedSiteDescription = nsiteVfsConfig?.description ?? legacy?.siteDescription;
return (
<NsiteDeployForm
gateway={selectedProvider.gateway}
savedNsec={savedNsec}
onNsecChange={handleNsiteNsecChange}
/>
<div className="space-y-3">
<NsiteDeployForm
key={selectedProviderId}
projectName={projectName || projectId}
savedNsec={legacy?.nsec}
savedSiteTitle={savedSiteTitle}
savedSiteDescription={savedSiteDescription}
onSiteTitleChange={handleNsiteSiteTitleChange}
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
/>
{nsiteVfsConfig && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
onClick={() => setNsiteShowFullForm(false)}
>
Back to summary
</button>
)}
</div>
);
}
@@ -477,6 +737,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
);
}
if (selectedProvider.type === 'railway') {
const railwayProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedWorkspaceId = savedConfig?.type === 'railway' ? savedConfig.data.workspaceId : undefined;
const savedProjectId = savedConfig?.type === 'railway' ? savedConfig.data.projectId : undefined;
const savedEnvironmentId = savedConfig?.type === 'railway' ? savedConfig.data.environmentId : undefined;
const savedServiceId = savedConfig?.type === 'railway' ? savedConfig.data.serviceId : undefined;
return (
<RailwayDeployForm
apiKey={railwayProvider.apiKey}
baseURL={railwayProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedWorkspaceId={savedWorkspaceId}
savedProjectId={savedProjectId}
savedEnvironmentId={savedEnvironmentId}
savedServiceId={savedServiceId}
onConfigChange={handleRailwayConfigChange}
corsProxy={railwayProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
};
@@ -636,6 +920,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
</Alert>
)}
{selectedProvider?.type === 'nsite' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to deploy to nsite.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
@@ -650,10 +950,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'nsite' && !user) ||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
}
className="w-full"
>
+1 -1
View File
@@ -53,7 +53,7 @@ export function NetlifyDeployForm({
try {
const url = `${baseURL}/sites`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
headers: {
+75 -79
View File
@@ -1,107 +1,103 @@
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { nip19 } from 'nostr-tools';
import { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { PasswordInput } from '@/components/ui/password-input';
import { RefreshCw } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription } from '@/components/ui/alert';
interface NsiteDeployFormProps {
gateway: string;
/** Human-readable project name — used to default the title */
projectName: string;
/** Persisted values from a previous deployment */
savedSiteTitle?: string;
savedSiteDescription?: string;
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
savedNsec?: string;
onNsecChange: (nsec: string) => void;
onSiteTitleChange: (title: string) => void;
onSiteDescriptionChange: (description: string) => void;
}
export function NsiteDeployForm({
gateway,
projectName,
savedSiteTitle,
savedSiteDescription,
savedNsec,
onNsecChange,
onSiteTitleChange,
onSiteDescriptionChange,
}: NsiteDeployFormProps) {
const [nsec, setNsec] = useState(savedNsec || '');
const [npub, setNpub] = useState('');
const initialized = useRef(false);
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
// On mount: sync all saved values to parent and set defaults.
// The component is keyed by selectedProviderId in DeploySteps, so this always
// runs with fresh props — no initialized guard needed.
const initializedRef = useRef(false);
const stableSyncToParent = useCallback(() => {
if (initializedRef.current) return;
initializedRef.current = true;
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
const initialTitle = savedSiteTitle ?? projectName;
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
onSiteTitleChange(initialTitle);
}, [savedSiteDescription, savedSiteTitle, siteTitle, projectName, onSiteDescriptionChange, onSiteTitleChange]);
// Initialize nsec on mount
useEffect(() => {
if (!initialized.current) {
initialized.current = true;
if (savedNsec) {
// If we have a saved nsec, notify parent immediately
onNsecChange(savedNsec);
} else if (!nsec) {
// Generate a new nsec if none exists
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
}
}
}, [savedNsec, nsec, onNsecChange]);
stableSyncToParent();
}, [stableSyncToParent]);
// Update npub when nsec changes
useEffect(() => {
if (nsec) {
try {
const decoded = nip19.decode(nsec);
if (decoded.type === 'nsec') {
const pk = getPublicKey(decoded.data);
const npubEncoded = nip19.npubEncode(pk);
setNpub(npubEncoded);
}
} catch {
setNpub('');
}
}
}, [nsec]);
const handleNsecChange = (value: string) => {
setNsec(value);
onNsecChange(value);
const handleSiteTitleChange = (value: string) => {
setSiteTitle(value);
onSiteTitleChange(value);
};
const handleGenerateNew = () => {
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
const handleSiteDescriptionChange = (value: string) => {
setSiteDescription(value);
onSiteDescriptionChange(value);
};
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
return (
<div className="space-y-4">
{/* Migration notice */}
{savedNsec && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Site identity is changing.</strong> This project was previously deployed with a
dedicated private key. Going forward, it will deploy under your Nostr identity. The old
site will remain at its original address until overwritten.
</AlertDescription>
</Alert>
)}
{/* Site title */}
<div className="space-y-2">
<Label>Site URL</Label>
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
{fullDomain}
</p>
<Label htmlFor="nsite-title">Site Title</Label>
<Input
id="nsite-title"
value={siteTitle}
onChange={(e) => handleSiteTitleChange(e.target.value)}
placeholder="My Nostr Site"
/>
<p className="text-xs text-muted-foreground">
Each site has a unique Nostr keypair
Shown by nsite gateways and directories. Included as a title tag in the manifest.
</p>
</div>
{/* Site description */}
<div className="space-y-2">
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
<div className="flex gap-2">
<PasswordInput
id="nsite-nsec"
value={nsec}
onChange={(e) => handleNsecChange(e.target.value)}
placeholder="nsec1..."
className="flex-1"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleGenerateNew}
title="Generate new key"
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
<Label htmlFor="nsite-description">Description <span className="text-muted-foreground font-normal">(optional)</span></Label>
<Textarea
id="nsite-description"
value={siteDescription}
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
placeholder="A short description of this site…"
rows={3}
/>
<p className="text-xs text-muted-foreground">
Keep this private key secure. It's used to sign site metadata.
Included as a description tag in the manifest.
</p>
</div>
</div>
+382
View File
@@ -0,0 +1,382 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface Workspace {
id: string;
name: string;
projects: {
edges: Array<{
node: Project;
}>;
};
}
interface Project {
id: string;
name: string;
environments: {
edges: Array<{
node: {
id: string;
name: string;
};
}>;
};
services: {
edges: Array<{
node: {
id: string;
name: string;
};
}>;
};
}
interface RailwayDeployFormProps {
apiKey: string;
baseURL?: string;
projectId: string;
projectName?: string;
savedWorkspaceId?: string;
savedProjectId?: string;
savedEnvironmentId?: string;
savedServiceId?: string;
onConfigChange: (config: {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}) => void;
corsProxy?: string;
}
export function RailwayDeployForm({
apiKey,
baseURL = 'https://backboard.railway.com',
projectId,
projectName,
savedWorkspaceId,
savedProjectId,
savedEnvironmentId,
savedServiceId,
onConfigChange,
corsProxy,
}: RailwayDeployFormProps) {
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>('');
const [selectedProjectId, setSelectedProjectId] = useState<string>('');
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string>('');
const [selectedServiceId, setSelectedServiceId] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchWorkspaces = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const query = `
query UserWorkspaces {
me {
workspaces {
id
name
projects(first: 500) {
edges {
node {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
}
}
}
}
`;
const url = `${baseURL}/graphql/v2`;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
if (!response.ok) {
throw new Error(`Failed to fetch workspaces: ${response.status} ${response.statusText}`);
}
const result = await response.json();
if (result.errors) {
throw new Error(`Railway API error: ${result.errors[0]?.message || 'Unknown error'}`);
}
const workspacesData: Workspace[] = result.data.me.workspaces;
setWorkspaces(workspacesData);
// Auto-select workspace if saved or if there's only one
if (savedWorkspaceId && workspacesData.some(w => w.id === savedWorkspaceId)) {
setSelectedWorkspaceId(savedWorkspaceId);
} else if (workspacesData.length === 1) {
setSelectedWorkspaceId(workspacesData[0].id);
}
// Auto-select project if saved
if (savedProjectId) {
setSelectedProjectId(savedProjectId);
}
// Auto-select environment if saved
if (savedEnvironmentId) {
setSelectedEnvironmentId(savedEnvironmentId);
}
// Auto-select service if saved
if (savedServiceId) {
setSelectedServiceId(savedServiceId);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch workspaces');
} finally {
setIsLoading(false);
}
}, [apiKey, baseURL, savedWorkspaceId, savedProjectId, savedEnvironmentId, savedServiceId, corsProxy]);
useEffect(() => {
fetchWorkspaces();
}, [fetchWorkspaces]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectId === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectId, newProjectName, projectName, projectId]);
// Notify parent of configuration changes
useEffect(() => {
if (!selectedWorkspaceId || !selectedProjectId) {
return;
}
if (selectedProjectId === 'new') {
// Creating new project - only require workspace and project name
onConfigChange({
workspaceId: selectedWorkspaceId,
projectId: '',
environmentId: '',
serviceId: '',
projectName: newProjectName,
});
} else {
// Existing project - require environment and service
if (!selectedEnvironmentId || !selectedServiceId) {
return;
}
onConfigChange({
workspaceId: selectedWorkspaceId,
projectId: selectedProjectId,
environmentId: selectedEnvironmentId,
serviceId: selectedServiceId === 'new' ? '' : selectedServiceId,
});
}
}, [selectedWorkspaceId, selectedProjectId, selectedEnvironmentId, selectedServiceId, newProjectName, onConfigChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Workspace</Label>
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
</div>
);
}
const selectedWorkspace = workspaces.find(w => w.id === selectedWorkspaceId);
const projects = selectedWorkspace?.projects.edges.map(e => e.node) || [];
const selectedProject = projects.find(p => p.id === selectedProjectId);
const environments = selectedProject?.environments.edges.map(e => e.node) || [];
const services = selectedProject?.services.edges.map(e => e.node) || [];
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Workspace Selection */}
<div className="space-y-2">
<Label htmlFor="railway-workspace">Workspace</Label>
<Select value={selectedWorkspaceId} onValueChange={setSelectedWorkspaceId}>
<SelectTrigger id="railway-workspace">
<SelectValue placeholder="Select a workspace..." />
</SelectTrigger>
<SelectContent>
{workspaces.map((workspace) => (
<SelectItem key={workspace.id} value={workspace.id}>
{workspace.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Project Selection */}
{selectedWorkspaceId && (
<div className="space-y-2">
<Label htmlFor="railway-project">Project</Label>
<Select
value={selectedProjectId}
onValueChange={(value) => {
setSelectedProjectId(value);
setSelectedEnvironmentId('');
setSelectedServiceId('');
}}
>
<SelectTrigger id="railway-project">
<SelectValue placeholder="Select a project or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new project
</div>
</SelectItem>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* New Project Name */}
{selectedProjectId === 'new' && (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Project Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
A new project with a production environment and web service will be created when you deploy
</p>
</div>
)}
{/* Environment Selection */}
{selectedProjectId && selectedProjectId !== 'new' && environments.length > 0 && (
<div className="space-y-2">
<Label htmlFor="railway-environment">Environment</Label>
<Select value={selectedEnvironmentId} onValueChange={setSelectedEnvironmentId}>
<SelectTrigger id="railway-environment">
<SelectValue placeholder="Select an environment..." />
</SelectTrigger>
<SelectContent>
{environments.map((env) => (
<SelectItem key={env.id} value={env.id}>
{env.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Service Selection */}
{selectedProjectId && selectedProjectId !== 'new' && selectedEnvironmentId && (
<div className="space-y-2">
<Label htmlFor="railway-service">Service</Label>
<Select value={selectedServiceId} onValueChange={setSelectedServiceId}>
<SelectTrigger id="railway-service">
<SelectValue placeholder="Select a service or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new service
</div>
</SelectItem>
{services.map((service) => (
<SelectItem key={service.id} value={service.id}>
{service.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Project Info */}
{selectedProject && selectedProjectId !== 'new' && (
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedProject.name}</p>
<p className="text-xs text-muted-foreground">
{environments.length} environment(s), {services.length} service(s)
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://railway.app/project/${selectedProject.id}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
);
}
+22 -11
View File
@@ -7,6 +7,7 @@ import { useGitSyncState } from '@/hooks/useGitSyncState';
import { useFSPaths } from '@/hooks/useFSPaths';
import { cn } from '@/lib/utils';
import { GitSyncSteps } from './GitSyncSteps';
import { useTranslation } from 'react-i18next';
interface GitSyncButtonProps {
projectId: string;
@@ -18,6 +19,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [syncSuccess, setSyncSuccess] = useState(false);
const [showWarningPopover, setShowWarningPopover] = useState(false);
const warningDismissed = useRef(false);
const { t } = useTranslation();
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError, getState } = useGitSyncState();
@@ -52,19 +54,28 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
prevIsGitActionOccurring.current = isGitActionOccurring;
}, [isGitActionOccurring, hasError]);
// Determine if the user has altered the project (made commits beyond the initial state).
// - Template projects (no clonedAtOid): altered when totalCommits > 1 (beyond the initial template commit)
// - Cloned projects (has clonedAtOid): altered when the latest commit differs from the clone point
const isProjectAltered = !isGitStatusLoading && gitStatus && (() => {
if (gitStatus.clonedAtOid) {
return gitStatus.latestCommit !== null && gitStatus.latestCommit.oid !== gitStatus.clonedAtOid;
}
return gitStatus.totalCommits > 1;
})();
// Check if we need to show the warning popover
const needsRemote = !isGitStatusLoading && gitStatus &&
!gitStatus.remotes.find(r => r.name === 'origin') &&
gitStatus.totalCommits > 1;
const needsRemote = isProjectAltered &&
!gitStatus?.remotes.find(r => r.name === 'origin');
// Show warning popover when purple indicator is visible (only if not dismissed)
useEffect(() => {
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
if (needsRemote && !warningDismissed.current) {
setShowWarningPopover(true);
} else {
setShowWarningPopover(false);
}
}, [gitStatus?.totalCommits, needsRemote]);
}, [needsRemote]);
// Handle button click - dismiss warning popover permanently
const handleButtonClick = () => {
@@ -94,19 +105,18 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
if (isGitStatusLoading || !gitStatus) return null;
const originRemote = gitStatus.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
const hasOrigin = !!gitStatus.remotes.find(r => r.name === 'origin');
const { remoteBranchExists, ahead, behind, totalCommits } = gitStatus;
const { remoteBranchExists, ahead, behind } = gitStatus;
// Yellow indicator: unsynced changes (ahead or behind remote) - third priority
const hasUnsyncedChanges = hasRemote && remoteBranchExists && (ahead > 0 || behind > 0);
const hasUnsyncedChanges = hasOrigin && remoteBranchExists && (ahead > 0 || behind > 0);
if (hasUnsyncedChanges) {
return <IndicatorDot color="yellow" />;
}
// Purple indicator: no remote configured, but has commits - lowest priority
const needsRemote = !hasRemote && totalCommits > 1;
// Purple indicator: project altered but no origin remote configured - lowest priority
const needsRemote = isProjectAltered && !hasOrigin;
if (needsRemote) {
return <IndicatorDot color="primary" />;
}
@@ -129,6 +139,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
onClick={handleButtonClick}
title={t('cloudSyncButtonTooltip')}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
@@ -2,7 +2,6 @@ import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useGit } from '@/hooks/useGit';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -20,6 +19,9 @@ import type { NostrEvent } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
import { useGitAutosync } from '@/hooks/useGitAutosync';
import { ArrowUp } from 'lucide-react';
import { ForcePushDialog } from './ForcePushDialog';
import { SyncStepError } from './SyncStepError';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
// Helper function to convert kebab-case to Title Case
function kebabToTitleCase(str: string): string {
@@ -41,7 +43,8 @@ export function ConfigureRepoStep({
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
const [isPushing, setIsPushing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [error, setError] = useState<Error | null>(null);
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
const { user } = useCurrentUser();
const { git } = useGit();
@@ -55,6 +58,7 @@ export function ConfigureRepoStep({
const { mutateAsync: publishEvent } = useNostrPublish();
const { fs } = useFS();
const { config } = useAppContext();
const { settings: projectDeploySettings } = useProjectDeploySettings(projectId);
// Auto-update repo name when repo identifier changes (unless manually edited)
useEffect(() => {
@@ -74,9 +78,10 @@ export function ConfigureRepoStep({
setIsRepoNameManuallyEdited(true);
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
// Shared push logic for both initial push and force push
const executePush = async (force: boolean = false) => {
// Store the URL we're trying to add so we can remove it on error
let remoteAdded = false;
try {
if (selectedProvider.id === 'nostr') {
@@ -166,6 +171,15 @@ export function ConfigureRepoStep({
tTags.push(template.name);
}
// Get deployment URL from project settings if available
let webUrls: string[] | undefined;
if (projectDeploySettings.currentProvider) {
const currentProviderConfig = projectDeploySettings.providers[projectDeploySettings.currentProvider];
if (currentProviderConfig?.url) {
webUrls = [currentProviderConfig.url];
}
}
// Create the repository announcement event
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: repoIdentifier,
@@ -173,6 +187,7 @@ export function ConfigureRepoStep({
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags,
webUrls,
});
// Publish the event
@@ -196,12 +211,14 @@ export function ConfigureRepoStep({
url: nostrURI.toString(),
force: true,
});
remoteAdded = true;
// Push to Nostr (the rest of the Nostr logic is handled internally by git.push)
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
force,
});
} else {
// Validate repository URL
@@ -216,12 +233,14 @@ export function ConfigureRepoStep({
url: repositoryUrl,
force: true, // Override if exists
});
remoteAdded = true;
// Push to remote
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
force,
});
}
@@ -238,8 +257,45 @@ export function ConfigureRepoStep({
// Show success state
onSuccess();
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to push';
setError(message);
const error = err instanceof Error ? err : new Error(force ? 'Failed to force push' : 'Failed to push');
// If we added the remote but push failed, remove it
if (remoteAdded) {
try {
await git.deleteRemote({ dir, remote: 'origin' });
} catch {
// Ignore errors when cleaning up remote
}
}
throw error; // Re-throw so caller can handle
}
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
try {
await executePush(false);
} catch (err) {
const error = err instanceof Error ? err : new Error('Failed to push');
setError(error);
} finally {
setIsPushing(false);
}
};
const handleForcePush = async () => {
setIsPushing(true);
setError(null);
setShowForcePushDialog(false);
try {
await executePush(true);
} catch (err) {
const error = err instanceof Error ? err : new Error('Failed to force push');
setError(error);
} finally {
setIsPushing(false);
}
@@ -343,9 +399,13 @@ export function ConfigureRepoStep({
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
)}
<div className="flex gap-2">
@@ -360,6 +420,13 @@ export function ConfigureRepoStep({
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
@@ -386,9 +453,13 @@ export function ConfigureRepoStep({
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
)}
<div className="flex gap-2">
@@ -407,6 +478,13 @@ export function ConfigureRepoStep({
)}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
+1 -1
View File
@@ -154,7 +154,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
if (url.protocol === 'nostr:') {
const nostrUri = await NostrURI.parse(url.href);
return ngitWebUrl(config.ngitWebUrl, nostrUri);
return ngitWebUrl({ template: config.ngitWebUrl, nostrURI: nostrUri });
}
return null;
+44 -10
View File
@@ -8,14 +8,16 @@ import { getSentryInstance } from '@/lib/sentry';
interface SyncStepErrorProps {
error: Error;
onDismiss: () => void;
onForcePull: () => void;
onForcePull?: () => void;
onForcePush: () => void;
onPull: () => void;
remoteUrl: URL;
onPull?: () => void;
remoteUrl?: URL;
remoteName: string;
/** Context for error messages - 'sync' for existing remotes, 'configure' for initial setup */
context?: 'sync' | 'configure';
}
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl, context = 'sync' }: SyncStepErrorProps) {
const renderForcePullButton = () => (
<Button
variant="outline"
@@ -104,17 +106,23 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
// PushRejectedError - remote has changes
if (error instanceof GitErrors.PushRejectedError) {
// Different message based on context
const message = context === 'configure'
? `The repository on ${remoteName} is not empty. You'll need to force push to overwrite it with your local project.`
: `Push rejected. The remote repository has changes you don't have locally. Try pulling first.`;
return (
<Alert variant="destructive">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
{message}
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{renderPullButton()}
{/* Only show Pull button in sync context (not during initial configure) */}
{context === 'sync' && onPull && renderPullButton()}
{renderForcePushButton()}
</div>
</div>
@@ -126,17 +134,43 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
if (error instanceof GitErrors.HttpError) {
let message: React.ReactNode = `HTTP Error: ${error.data.statusCode} ${error.data.statusMessage}`;
if (remoteUrl.protocol === 'nostr:') {
// Check if remoteUrl is a Nostr URL
if (remoteUrl?.protocol === 'nostr:') {
// This should never happen
getSentryInstance()?.captureException(error);
message = `There was an HTTP (${error.data.statusCode}) error communicating with Nostr Git servers.`
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
} else if (remoteUrl && remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
// Handle standard HTTP errors based on status code
switch (error.data.statusCode) {
case 401:
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
message = context === 'configure'
? <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
: <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
break;
case 403:
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
message = context === 'configure'
? <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>
: <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
break;
case 404:
if (context === 'configure') {
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
}
break;
}
} else {
// No remoteUrl available or it's a standard HTTP/HTTPS URL
switch (error.data.statusCode) {
case 401:
message = <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
break;
case 403:
message = <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>;
break;
case 404:
if (context === 'configure') {
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
}
break;
}
}
+1
View File
@@ -7,6 +7,7 @@ export interface AIProvider {
apiKey?: string;
nostr?: boolean;
proxy?: boolean;
openSecret?: string;
}
export interface MCPServer {
+4
View File
@@ -68,6 +68,10 @@ export interface AppConfig {
sentryEnabled: boolean;
/** System prompt EJS template */
systemPrompt?: string;
/** Plausible Analytics domain (empty string = disabled). */
plausibleDomain: string;
/** Plausible Analytics API endpoint (empty string = use default). */
plausibleEndpoint: string;
}
export interface AppContextType {
+8 -1
View File
@@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface RailwayProvider extends BaseDeployProvider {
type: 'railway';
apiKey: string;
baseURL?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
export interface DeploySettings {
providers: DeployProvider[];
+11 -5
View File
@@ -46,8 +46,10 @@ export function useAIChat({
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
const initSession = useCallback(async () => {
setIsLoadingHistory(true);
const initSession = useCallback(async (showLoading = true) => {
if (showLoading) {
setIsLoadingHistory(true);
}
try {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
@@ -59,7 +61,9 @@ export function useAIChat({
setLastInputTokens(session.lastInputTokens || 0);
setLastFinishReason(session.lastFinishReason ?? null);
} finally {
setIsLoadingHistory(false);
if (showLoading) {
setIsLoadingHistory(false);
}
}
}, [sessionManager, projectId, tools, customTools, maxSteps]);
@@ -129,7 +133,8 @@ export function useAIChat({
providerModel: string
) => {
try {
await initSession();
// Ensure session is loaded (without showing loading state)
await initSession(false);
await sessionManager.sendMessage(projectId, content, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
@@ -142,7 +147,8 @@ export function useAIChat({
const startGeneration = useCallback(async (providerModel: string) => {
try {
await initSession();
// Ensure session is loaded (without showing loading state)
await initSession(false);
await sessionManager.startGeneration(projectId, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
+104
View File
@@ -0,0 +1,104 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import type { NostrEvent } from '@nostrify/nostrify';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { DotAI } from '@/lib/DotAI';
interface UseAppEventOptions {
/** Project working directory (e.g. /projects/<id>) */
cwd: string;
}
/**
* Hook to fetch the kind 31990 app event associated with this project.
* Reads the stored "a" coordinate from .git/shakespeare/app.json,
* then queries relays for the matching event.
*/
export function useAppEvent({ cwd }: UseAppEventOptions) {
const { nostr } = useNostr();
const { fs } = useFS();
const { user } = useCurrentUser();
const [aTag, setATag] = useState<string | null>(null);
const [isLoadingConfig, setIsLoadingConfig] = useState(true);
// Read the stored "a" coordinate on mount
useEffect(() => {
const loadConfig = async () => {
try {
const dotAI = new DotAI(fs, cwd);
const config = await dotAI.readAppConfig();
setATag(config?.a ?? null);
} catch {
setATag(null);
} finally {
setIsLoadingConfig(false);
}
};
loadConfig();
}, [fs, cwd]);
// Parse the "a" coordinate into filter components
const parsed = aTag ? parseATag(aTag) : null;
const query = useQuery<NostrEvent | null>({
queryKey: ['app-event', aTag],
queryFn: async ({ signal }) => {
if (!parsed) return null;
const events = await nostr.query(
[{
kinds: [parsed.kind],
authors: [parsed.pubkey],
'#d': [parsed.dTag],
limit: 1,
}],
{ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) },
);
if (events.length === 0) return null;
// Return the most recent event
return events.reduce((latest, current) =>
current.created_at > latest.created_at ? current : latest,
);
},
enabled: !!parsed && !isLoadingConfig,
});
return {
/** The stored "a" coordinate (e.g. "31990:<pubkey>:<d-tag>") */
aTag,
/** Set the "a" coordinate (updates local state; caller must persist) */
setATag,
/** The fetched kind 31990 event, or null */
event: query.data ?? null,
/** Whether the config or event is still loading */
isLoading: isLoadingConfig || query.isLoading,
/** Whether there is an existing app event for this project */
hasApp: !!aTag,
/** The current user's pubkey */
userPubkey: user?.pubkey,
/** Refetch the event from relays */
refetch: query.refetch,
};
}
/** Parse a Nostr "a" coordinate string into its components */
function parseATag(a: string): { kind: number; pubkey: string; dTag: string } | null {
const parts = a.split(':');
if (parts.length < 3) return null;
const kind = parseInt(parts[0], 10);
if (isNaN(kind)) return null;
const pubkey = parts[1];
const dTag = parts.slice(2).join(':'); // d-tag may contain colons
if (!pubkey || dTag === undefined) return null;
return { kind, pubkey, dTag };
}
+4
View File
@@ -80,6 +80,8 @@ describe('useGenerateProjectInfo', () => {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
mockUseAppContext.mockReturnValue({
config,
@@ -242,6 +244,8 @@ describe('useGenerateProjectInfo', () => {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
mockUseAppContext.mockReturnValue({
config,
+2
View File
@@ -54,6 +54,8 @@ function createWrapper(corsProxy: string) {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
return createElement(
+1 -1
View File
@@ -30,7 +30,7 @@ export function useGitHubOAuth() {
redirectUri: window.location.origin + '/oauth/github',
usePKCE: true, // GitHub supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.github.com/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+16
View File
@@ -39,6 +39,7 @@ interface GitStatus {
ahead: number;
behind: number;
remoteBranchExists: boolean;
clonedAtOid: string | null;
}
export function useGitStatus(projectId: string | null) {
@@ -61,6 +62,7 @@ export function useGitStatus(projectId: string | null) {
ahead: 0,
behind: 0,
remoteBranchExists: false,
clonedAtOid: null,
};
}
@@ -83,6 +85,7 @@ export function useGitStatus(projectId: string | null) {
ahead: 0,
behind: 0,
remoteBranchExists: false,
clonedAtOid: null,
};
}
@@ -168,6 +171,17 @@ export function useGitStatus(projectId: string | null) {
console.warn('Could not get remotes:', error);
}
// Get clonedAt OID (set when project was cloned from an external repo)
let clonedAtOid: string | null = null;
try {
const value = await git.getConfig({ dir: cwd, path: 'shakespeare.clonedAt' });
if (typeof value === 'string' && value.length > 0) {
clonedAtOid = value;
}
} catch {
// Config key doesn't exist, that's fine
}
// Get git status to see what files have changed
const statusMatrix = await git.statusMatrix({
dir: cwd,
@@ -274,6 +288,7 @@ export function useGitStatus(projectId: string | null) {
ahead,
behind,
remoteBranchExists,
clonedAtOid,
};
} catch (error) {
console.error('Error checking git status:', error);
@@ -289,6 +304,7 @@ export function useGitStatus(projectId: string | null) {
ahead: 0,
behind: 0,
remoteBranchExists: false,
clonedAtOid: null,
};
}
},
+1 -1
View File
@@ -30,7 +30,7 @@ export function useNetlifyOAuth() {
redirectUri: window.location.origin + '/oauth/netlify',
usePKCE: false, // Netlify doesn't support PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.netlify.com/api/v1/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+4 -2
View File
@@ -5,12 +5,14 @@ import { useCurrentUser } from "./useCurrentUser";
import type { NostrEvent } from "@nostrify/nostrify";
export function useNostrPublish(): UseMutationResult<NostrEvent> {
type NostrEventInput = Pick<NostrEvent, 'kind' | 'content'> & Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
export function useNostrPublish(): UseMutationResult<NostrEvent, Error, NostrEventInput> {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
mutationFn: async (t: NostrEventInput) => {
if (user) {
const tags = t.tags ?? [];
+1 -1
View File
@@ -169,7 +169,7 @@ export function useOAuth(config: OAuthConfig) {
}
// Exchange code for access token
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
const tokenUrl = proxyUrl({ template: corsProxy, url: config.tokenUrl });
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
+2 -1
View File
@@ -1,7 +1,8 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPlugins, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPluginSkills } from '@/lib/skills';
import { useGit } from './useGit';
import { join } from 'path-browserify';
+21 -1
View File
@@ -15,7 +15,14 @@ const nsiteProjectConfigSchema = z.object({
type: z.literal('nsite'),
url: z.string(),
data: z.object({
nsec: z.string(),
/** Kept optional — only present on configs created before the signer migration */
nsec: z.string().optional(),
siteTitle: z.string().optional(),
siteDescription: z.string().optional(),
/** Named-site dTag identifier (kind 35128). */
dTag: z.string().optional(),
/** @deprecated — Shakespeare always deploys named sites now. Kept for backward compat. */
siteType: z.enum(['named', 'root']).optional(),
}),
});
@@ -52,6 +59,17 @@ const denoDeployProjectConfigSchema = z.object({
}),
});
const railwayProjectConfigSchema = z.object({
type: z.literal('railway'),
url: z.string(),
data: z.object({
workspaceId: z.string().optional(),
projectId: z.string().optional(),
environmentId: z.string().optional(),
serviceId: z.string().optional(),
}),
});
const projectProviderConfigSchema = z.discriminatedUnion('type', [
shakespeareProjectConfigSchema,
nsiteProjectConfigSchema,
@@ -59,6 +77,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
vercelProjectConfigSchema,
cloudflareProjectConfigSchema,
denoDeployProjectConfigSchema,
railwayProjectConfigSchema,
]);
const projectDeploySettingsSchema = z.object({
@@ -72,6 +91,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
export type RailwayProjectConfig = z.infer<typeof railwayProjectConfigSchema>;
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
+1
View File
@@ -15,6 +15,7 @@ export function useUploadFile() {
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
'https://blossom.ditto.pub/',
],
signer: user.signer,
});
+1 -1
View File
@@ -34,7 +34,7 @@ export function useVercelOAuth() {
redirectUri: window.location.origin + '/oauth/vercel',
usePKCE: false, // Vercel doesn't require PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.vercel.com/v2/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -200,7 +200,7 @@ export function useZaps(
const zapRequest = nip57.makeZapRequest({
event: actualTarget,
amount: zapAmount,
relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band'],
relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.ditto.pub'],
comment
});
+43
View File
@@ -393,4 +393,47 @@ export class DotAI {
console.warn(`Failed to write .git/ai/FINISH_REASON file: ${error}`);
}
}
/**
* Read app config from .git/shakespeare/app.json file.
* Stores the Nostr "a" coordinate for the project's kind 31990 app event.
* @returns App config object or null if not found or invalid
*/
async readAppConfig(): Promise<AppConfig | null> {
try {
const appPath = join(this.workingDir, ".git", "shakespeare", "app.json");
const content = await this.fs.readFile(appPath, "utf8");
const data = JSON.parse(content);
if (data && typeof data.a === 'string' && data.a.length > 0) {
return { a: data.a };
}
return null;
} catch {
return null;
}
}
/**
* Write app config to .git/shakespeare/app.json file.
* @param config App config with the Nostr "a" coordinate (e.g. "31990:<pubkey>:<d-tag>")
*/
async writeAppConfig(config: AppConfig): Promise<void> {
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
const appPath = join(shakespeareDir, "app.json");
try {
await this.fs.mkdir(shakespeareDir, { recursive: true });
await this.fs.writeFile(appPath, JSON.stringify(config, null, 2) + "\n");
} catch (error) {
console.warn(`Failed to write .git/shakespeare/app.json file: ${error}`);
}
}
}
/** App config stored in .git/shakespeare/app.json */
export interface AppConfig {
/** Nostr "a" coordinate for the kind 31990 event (e.g. "31990:<pubkey>:<d-tag>") */
a: string;
}
-371
View File
@@ -1,371 +0,0 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { KindGenerator } from './KindGenerator.ts';
const __dirname = dirname(fileURLToPath(import.meta.url));
describe('KindGenerator', () => {
it('should extract used kinds from real NIPs fixture', () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Check that some expected kinds are extracted from the real NIPs index
const expectedKinds = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
20,
21,
22,
30,
31,
32,
33,
40,
41,
42,
43,
44,
62,
64,
818,
1018,
1021,
1022,
1040,
1059,
1063,
1068,
1111,
1311,
1337,
1617,
1621,
1622,
1971,
1984,
1985,
1986,
1987,
2003,
2004,
2022,
4550,
7000,
7374,
7375,
7376,
9041,
9321,
9467,
9734,
9735,
9802,
10000,
10001,
10002,
10003,
10004,
10005,
10006,
10007,
10009,
10012,
10013,
10015,
10019,
10020,
10030,
10050,
10063,
10096,
10166,
13194,
17375,
21000,
22242,
23194,
23195,
24133,
24242,
27235,
30000,
30001,
30002,
30003,
30004,
30005,
30007,
30008,
30009,
30015,
30017,
30018,
30019,
30020,
30023,
30024,
30030,
30040,
30041,
30063,
30078,
30166,
30267,
30311,
30315,
30388,
30402,
30403,
30617,
30618,
30818,
30819,
31234,
31388,
31890,
31922,
31923,
31924,
31925,
31989,
31990,
32267,
34550,
38383,
39089,
39092,
39701,
];
for (const kind of expectedKinds) {
expect(usedKinds.has(kind)).toBe(true);
}
// Check that ranges are properly extracted
// `5000`-`5999` should add all numbers from 5000 to 5999
for (let i = 5000; i <= 5999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `6000`-`6999` should add all numbers from 6000 to 6999
for (let i = 6000; i <= 6999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `9000`-`9030` should add all numbers from 9000 to 9030
for (let i = 9000; i <= 9030; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `39000-9` should add all numbers from 39000 to 39009
for (let i = 39000; i <= 39009; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `1630`-`1633` should add all numbers from 1630 to 1633
for (let i = 1630; i <= 1633; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should extract used kinds from mock data', () => {
const mockNipsIndex = `
## Event Kinds
| kind | description | NIP |
| ------------- | ------------------------------- | -------------------------------------- |
| \`0\` | User Metadata | [01](01.md) |
| \`1\` | Short Text Note | [10](10.md) |
| \`3\` | Follows | [02](02.md) |
| \`1000\`-\`1999\` | Custom Range | [test](test.md) |
| \`30000\` | Addressable Event | [51](51.md) |
`;
const usedKinds = KindGenerator.extractUsedKinds(mockNipsIndex);
// Check individual kinds
expect(usedKinds.has(0)).toBe(true);
expect(usedKinds.has(1)).toBe(true);
expect(usedKinds.has(3)).toBe(true);
expect(usedKinds.has(30000)).toBe(true);
// Check range
for (let i = 1000; i <= 1999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should get kind range info correctly', () => {
const regularRange = KindGenerator.getKindRangeInfo('regular');
expect(regularRange.min).toBe(1000);
expect(regularRange.max).toBe(9999);
expect(regularRange.name).toBe('Regular Events');
const replaceableRange = KindGenerator.getKindRangeInfo('replaceable');
expect(replaceableRange.min).toBe(10000);
expect(replaceableRange.max).toBe(19999);
const ephemeralRange = KindGenerator.getKindRangeInfo('ephemeral');
expect(ephemeralRange.min).toBe(20000);
expect(ephemeralRange.max).toBe(29999);
const addressableRange = KindGenerator.getKindRangeInfo('addressable');
expect(addressableRange.min).toBe(30000);
expect(addressableRange.max).toBe(39999);
});
it('should generate available kinds in correct ranges', () => {
const usedKinds = new Set([1000, 1001, 1002, 10000, 10001, 30000, 30001]);
// Test regular range
const regularKind = KindGenerator.generateAvailableKind(
'regular',
usedKinds,
);
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
// Check new constraints
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
// Check buffer constraint - should not be within 2 of any used kind
for (const usedKind of usedKinds) {
const distance = Math.abs(regularKind - usedKind);
expect(distance > 2).toBe(true);
}
// Test replaceable range
const replaceableKind = KindGenerator.generateAvailableKind(
'replaceable',
usedKinds,
);
expect(replaceableKind >= 10000 && replaceableKind <= 19999).toBe(true);
expect(usedKinds.has(replaceableKind)).toBe(false);
expect(replaceableKind % 2 !== 0).toBe(true);
expect(replaceableKind % 5 !== 0).toBe(true);
// Test ephemeral range
const ephemeralKind = KindGenerator.generateAvailableKind(
'ephemeral',
usedKinds,
);
expect(ephemeralKind >= 20000 && ephemeralKind <= 29999).toBe(true);
expect(usedKinds.has(ephemeralKind)).toBe(false);
expect(ephemeralKind % 2 !== 0).toBe(true);
expect(ephemeralKind % 5 !== 0).toBe(true);
// Test addressable range
const addressableKind = KindGenerator.generateAvailableKind(
'addressable',
usedKinds,
);
expect(addressableKind >= 30000 && addressableKind <= 39999).toBe(true);
expect(usedKinds.has(addressableKind)).toBe(false);
expect(addressableKind % 2 !== 0).toBe(true);
expect(addressableKind % 5 !== 0).toBe(true);
});
it('should respect buffer constraints when generating kinds', () => {
// Test buffer constraint specifically
const usedKinds = new Set([1007, 1013, 1019]); // Use odd numbers that aren't multiples of 5
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should be in range
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
// Should be odd
expect(regularKind % 2 !== 0).toBe(true);
// Should not be multiple of 5
expect(regularKind % 5 !== 0).toBe(true);
// Should not be within buffer of used kinds
const forbiddenNumbers = new Set([
1005, 1006, 1007, 1008, 1009, // around 1007
1011, 1012, 1013, 1014, 1015, // around 1013
1017, 1018, 1019, 1020, 1021, // around 1019
]);
expect(forbiddenNumbers.has(regularKind)).toBe(false);
});
it('should handle edge cases with many used kinds', () => {
// Test with many used kinds to ensure we still find valid ones
const usedKinds = new Set<number>();
// Fill most even numbers and multiples of 5 in a small range
for (let i = 1000; i <= 1100; i++) {
if (i % 2 === 0 || i % 5 === 0) {
usedKinds.add(i);
}
}
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should still find a valid kind
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
});
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 = 50; // Reduced from 100 to 50 for performance
for (let i = 0; i < iterations; i++) {
const kind = KindGenerator.generateAvailableKind('regular', usedKinds);
results.set(kind, (results.get(kind) || 0) + 1);
// Verify constraints on each generated kind
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
expect(usedKinds.has(kind)).toBe(false);
}
// Check that we get good variety (at least 5 unique kinds in 50 iterations)
// Reduced expectations due to fewer iterations
expect(results.size).toBeGreaterThanOrEqual(5);
// 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(50);
// Check that all generated kinds follow our constraints
for (const [kind] of results) {
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
// Check buffer constraint
for (const usedKind of usedKinds) {
const distance = Math.abs(kind - usedKind);
expect(distance > 2).toBe(true);
}
}
});
});
+41 -27
View File
@@ -57,50 +57,52 @@ export class ProjectsManager {
* Returns the path to the cached template.
*
* @param templateUrl - Git repository URL of the template
* @param onUpdateError - Optional callback when template update fails (non-critical)
* @returns Path to the cached template directory
*/
async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise<string> {
async updateTemplate(templateUrl: string): Promise<string> {
// Generate a safe directory name from the template URL
const templateName = this.getTemplateNameFromUrl(templateUrl);
const templatePath = `${this.templatesDir}/${templateName}`;
try {
// Check if template already exists
await this.fs.stat(templatePath);
const templateExists = await this.fs.stat(templatePath).then(() => true, () => false);
if (templateExists) {
// Template exists, try to update it with force pull
try {
await this.forcePullTemplate(templatePath);
return templatePath;
} catch (updateError) {
// Update failed, but we can continue with the existing template
console.warn(`Failed to update template at ${templatePath}:`, updateError);
if (onUpdateError) {
onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError)));
}
}
} catch {
// Template doesn't exist, clone it shallowly
await this.fs.mkdir(templatePath, { recursive: true });
try {
await this.git.clone({
dir: templatePath,
url: templateUrl,
singleBranch: true,
depth: 1,
});
} catch (cloneError) {
// Clean up on clone failure
// Force pull failed (common with shallow clones when remote has new commits).
// Delete the stale cache and re-clone fresh below.
console.warn(`Force pull failed for template at ${templatePath}, re-cloning fresh:`, updateError);
try {
await this.deleteDirectory(templatePath);
} catch {
// Ignore cleanup errors
}
throw cloneError;
}
}
// Template doesn't exist (or was deleted after failed update), clone it fresh
await this.fs.mkdir(templatePath, { recursive: true });
try {
await this.git.clone({
dir: templatePath,
url: templateUrl,
singleBranch: true,
depth: 1,
});
} catch (cloneError) {
// Clean up on clone failure
try {
await this.deleteDirectory(templatePath);
} catch {
// Ignore cleanup errors
}
throw cloneError;
}
return templatePath;
}
@@ -224,7 +226,7 @@ export class ProjectsManager {
}
}
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, templateMetadata?: { name: string; description: string }): Promise<Project> {
async createProject(name: string, templateUrl: string, customId?: string, templateMetadata?: { name: string; description: string }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -235,7 +237,7 @@ export class ProjectsManager {
const projectPath = `${this.dir}/${id}`;
// Ensure template is cached and up-to-date
const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError);
const templatePath = await this.updateTemplate(templateUrl);
// Create project directory
await this.fs.mkdir(projectPath, { recursive: true });
@@ -522,6 +524,18 @@ export class ProjectsManager {
remote: fork ? 'upstream' : undefined, // Use 'upstream' for forks, otherwise defaults to 'origin'
});
// Store the HEAD commit OID at clone time so we can detect user modifications later
try {
const headOid = await this.git.resolveRef({ dir: projectPath, ref: 'HEAD' });
await this.git.setConfig({
dir: projectPath,
path: 'shakespeare.clonedAt',
value: headOid,
});
} catch (error) {
console.warn('Failed to store clonedAt commit OID:', error);
}
if (!fork) {
// Set up 'shakespeare.autosync' config for non-forked repositories
await this.git.setConfig({
+2
View File
@@ -58,6 +58,8 @@ const testConfig: AppConfig = {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
describe('SessionManager', () => {
+68 -2
View File
@@ -319,6 +319,31 @@ export class SessionManager {
imageModel: settings.imageModel,
});
// Strip image_url parts from all user messages except the last one.
// The model has already seen and responded to earlier images, so re-sending
// them on every turn just burns tokens. The VFS text path (e.g. "Added file: /tmp/…")
// is kept, so the model can `read` the file again if it needs to.
const evictSeenImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
// Find the index of the last user message
let lastUserIdx = -1;
for (let i = msgs.length - 1; i >= 0; i--) {
if (msgs[i].role === 'user') {
lastUserIdx = i;
break;
}
}
return msgs.map((msg, idx) => {
if (idx === lastUserIdx) return msg; // keep the latest user message intact
if (msg.role !== 'user' || typeof msg.content === 'string' || !Array.isArray(msg.content)) return msg;
const filtered = msg.content.filter(part => part.type !== 'image_url');
if (filtered.length === msg.content.length) return msg; // no images to strip
return { ...msg, content: filtered.length > 0 ? filtered : '' };
});
};
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
return msgs.map(msg => {
@@ -378,6 +403,10 @@ export class SessionManager {
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Evict images the model has already seen (all except the last user message).
// This is a send-time transformation only — session.messages stays intact for the UI.
messages = evictSeenImages(messages);
// Filter out unsupported image formats (keep only JPG/JPEG/PNG for API)
// This ensures the UI shows all image types, but API only receives supported formats
messages = filterSupportedImages(messages);
@@ -661,7 +690,7 @@ export class SessionManager {
console.error('AI generation error:', error);
// Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
if (error instanceof OpenAI.APIUserAbortError || (error instanceof Error && error.name === 'AbortError')) {
return; // User cancelled
}
@@ -720,13 +749,50 @@ export class SessionManager {
this.emit('finishReasonChanged', projectId, null);
}
/**
* Check if content exceeds size/line limits
*/
private exceedsLimits(content: string): boolean {
const MAX_SIZE_BYTES = 50 * 1024; // 50 KiB
const MAX_LINES = 2000;
const sizeBytes = new Blob([content]).size;
const lineCount = content.split('\n').length;
return sizeBytes > MAX_SIZE_BYTES || lineCount > MAX_LINES;
}
/**
* Save content to tmpDir and return the file path
*/
private async saveToTmpFile(projectId: string, content: string, toolCallId: string): Promise<string> {
const config = this.getConfig();
const timestamp = Date.now();
const filename = `tool-output-${toolCallId}-${timestamp}.txt`;
const filepath = `${config.fsPathTmp}/${filename}`;
await this.fs.writeFile(filepath, content, 'utf8');
return filepath;
}
/**
* Helper to add tool messages and update conversation
*/
private async addToolMessage(projectId: string, toolCallId: string, content: string): Promise<void> {
let finalContent = content;
// Check if content exceeds limits
if (this.exceedsLimits(content)) {
// Save full content to tmp file
const filepath = await this.saveToTmpFile(projectId, content, toolCallId);
// Create placeholder message
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse \`grep\` to search the full content or \`read\` with offset/limit to view specific sections.`;
}
const toolMessage: AIMessage = {
role: 'tool',
content,
content: finalContent,
tool_call_id: toolCallId
};
+9 -5
View File
@@ -12,15 +12,19 @@ import { proxyUrl } from './proxyUrl';
* If the provider has proxy enabled, requests will be proxied through the corsProxy.
*/
export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: string): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
const openai = new OpenAI({
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
};
const openai = new OpenAI({
...baseConfig,
fetch: async (input, init) => {
// OpenSecret auth
// https://docs.opensecret.cloud/docs/maple-ai/
if (provider.openSecret) {
const { createCustomFetch } = await import('@opensecret/react');
return createCustomFetch({ apiKey: provider.apiKey, apiUrl: provider.openSecret })(input, init);
}
let request = new Request(input, init);
// Add OpenRouter headers
@@ -47,7 +51,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
// If proxy is enabled and we have a CORS proxy URL, modify the request URL
if (provider.proxy && corsProxy) {
request = new Request(proxyUrl(corsProxy, request.url), request);
request = new Request(proxyUrl({ template: corsProxy, url: request.url }), request);
}
return fetch(request);
+16 -7
View File
@@ -6,6 +6,7 @@ export interface PresetProvider {
nostr?: boolean;
tosURL?: string;
proxy?: boolean;
openSecret?: string;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
@@ -16,13 +17,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://ai.shakespeare.diy/terms",
nostr: true,
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "opencode",
name: "OpenCode Zen",
@@ -31,6 +25,21 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://opencode.ai/legal/terms-of-service",
proxy: true,
},
{
id: "maple",
name: "Maple AI",
baseURL: "https://enclave.trymaple.ai/v1",
apiKeysURL: "https://trymaple.ai/",
tosURL: "https://opensecret.cloud/terms",
openSecret: "https://enclave.trymaple.ai",
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "ppq",
name: "PayPerQ",
+117
View File
@@ -0,0 +1,117 @@
import git from 'isomorphic-git';
import { DotAI } from './DotAI';
import { NostrURI } from './NostrURI';
import { readNsiteVfsConfig } from './nsiteConfig';
import type { JSRuntimeFS } from './JSRuntime';
/** Input for building a kind 31990 app event. */
export interface AppEventInput {
name: string;
about?: string;
picture?: string;
website?: string;
dTag: string;
supportedKinds?: string[];
webHandlers?: Array<{ url: string; type?: string }>;
}
/** The content and tags for a kind 31990 event, ready to be signed/published. */
export interface AppEventData {
content: string;
tags: string[][];
}
/**
* Build the content JSON and tags array for a kind 31990 app event.
*
* Optionally inspects the project's git origin remote. If it's a `nostr://`
* URI owned by the given pubkey, an `a` tag referencing the kind 30617 repo
* event is included.
*/
export async function buildAppEvent(
input: AppEventInput,
opts?: {
fs?: JSRuntimeFS;
cwd?: string;
pubkey?: string;
},
): Promise<AppEventData> {
// Build content (kind-0-style metadata JSON)
const content: Record<string, string> = {};
if (input.name.trim()) content.name = input.name.trim();
if (input.about?.trim()) content.about = input.about.trim();
if (input.picture?.trim()) content.picture = input.picture.trim();
if (input.website?.trim()) content.website = input.website.trim();
// Build tags
const tags: string[][] = [
['d', input.dTag.trim()],
];
// Add k tags for supported kinds
if (input.supportedKinds) {
for (const kind of input.supportedKinds) {
tags.push(['k', kind]);
}
}
// Add web handler tags
if (input.webHandlers) {
for (const handler of input.webHandlers) {
if (handler.url) {
const webTag = ['web', handler.url];
if (handler.type) {
webTag.push(handler.type);
}
tags.push(webTag);
}
}
}
// Add t-tags for categorization (shakespeare + template name)
if (opts?.fs && opts.cwd) {
tags.push(['t', 'shakespeare']);
try {
const dotAI = new DotAI(opts.fs, opts.cwd);
const template = await dotAI.readTemplate();
if (template) {
tags.push(['t', template.name.toLowerCase()]);
}
} catch {
// Template not found, skip
}
}
// If origin remote is a nostr:// URI owned by the given pubkey, add an "a" tag for the repo
if (opts?.fs && opts.cwd && opts.pubkey) {
try {
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
if (originUrl?.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(originUrl);
if (nostrURI.pubkey === opts.pubkey) {
tags.push(['a', `30617:${nostrURI.pubkey}:${nostrURI.identifier}`]);
}
}
} catch {
// No remote or parse error, skip
}
}
// If an nsite deployment exists, add an "a" tag referencing the kind 35128 site manifest event
if (opts?.fs && opts.cwd && opts.pubkey) {
try {
const nsiteConfig = await readNsiteVfsConfig(opts.fs, opts.cwd);
if (nsiteConfig?.id) {
tags.push(['a', `35128:${opts.pubkey}:${nsiteConfig.id}`]);
}
} catch {
// No nsite config found, skip
}
}
return {
content: JSON.stringify(content),
tags,
};
}
+21 -1
View File
@@ -158,7 +158,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
let current: string | undefined = base;
while (current && current.length) {
// Remove the last package from the path (handling scoped packages like @scope/name)
const next = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
const next: string = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
if (next === current) break;
current = next;
const candidate = `${current}/node_modules/${name}`;
@@ -226,6 +226,11 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
};
case "crypto":
return {
path: `${esmUrl}/crypto-browserify?target=${target ?? "esnext"}`,
namespace: "esm",
};
default:
return {
errors: [{ text: `Module not found: ${args.path}` }],
@@ -260,6 +265,19 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// not a URL; continue
}
// Check if this is a file: dependency
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Let fsPlugin handle file: dependencies
return;
}
// Determine importer lock path (breadcrumb)
const importerLockPath = getImporterLockPath(args.importer);
@@ -430,6 +448,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
if (contentType) {
if (contentType === "application/javascript") {
loader = "js";
} else if (contentType === "application/json") {
loader = "json";
} else if (contentType === "text/css") {
loader = "css";
} else if (contentType === "application/wasm") {
+94 -13
View File
@@ -10,14 +10,21 @@ interface TsConfig {
};
}
interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
interface FsPluginOptions {
fs: JSRuntimeFS;
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
}
export function fsPlugin(options: FsPluginOptions): Plugin {
const { fs, cwd, tsconfig } = options;
const { fs, cwd, tsconfig, packageJson } = options;
return {
name: "fs",
@@ -30,27 +37,66 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
});
build.onResolve({ filter: /.*/ }, async (args) => {
// Skip resolving paths from external URLs
// Skip resolving paths from external URLs (but not fs: namespace)
if (/^https?:\/\//.test(args.importer)) {
return;
}
let resolved: string;
let resolved: string | undefined;
// Handle absolute paths
if (args.path.startsWith("/")) {
resolved = args.path;
} else if (args.path.startsWith("@/")) {
}
// Handle @/ alias
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
}
// Handle relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
// Remove fs: prefix from importer if present
const importerPath = args.importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), args.path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (args.path.match(/^[^./]/)) {
// Check if this is a file: dependency
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Extract the file path (e.g., "file:./path" -> "./path")
const filePath = depVersion.slice(5); // Remove "file:" prefix
const packagePath = join(cwd, filePath);
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
const subpath = args.path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return; // Let esmPlugin handle this
}
}
// Handle tsconfig baseUrl
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
} else {
}
// Nothing matched, let other plugins handle it
else {
return;
}
// Security: prevent accessing files outside the project directory
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) {
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
if (!resolved) {
return;
}
// Vite query parameters https://vite.dev/guide/assets
@@ -114,8 +160,43 @@ async function tryFileVariants(
return basePath;
}
// If it's a directory, try index files
// If it's a directory, try package.json first, then index files
if (stat.isDirectory()) {
// Try to read package.json for entry point
try {
const packageJsonPath = join(basePath, "package.json");
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| 'index.js';
// Resolve the entry point
const entryPath = typeof entryPoint === 'string'
? join(basePath, entryPoint)
: join(basePath, 'index.js');
const entryStat = await statSafe(fs, entryPath);
if (entryStat.isFile()) {
return entryPath;
}
// Try with different extensions if the entry point doesn't exist
for (const ext of extensions) {
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
const entryExtStat = await statSafe(fs, entryWithExt);
if (entryExtStat.isFile()) {
return entryWithExt;
}
}
} catch {
// package.json doesn't exist or is invalid, fall through to index files
}
// Fall back to trying index files
for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile);
+60 -1
View File
@@ -130,7 +130,7 @@ describe('buildProject', () => {
});
vi.mocked(mockFS.readdir)
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
.mockImplementation(async (path: string, _options?: { withFileTypes?: boolean }) => {
if (path === '/test/project/public') {
return [
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
@@ -535,4 +535,63 @@ react@^18.0.0:
// Verify tsconfig.json was attempted to be read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8');
});
it('should support file: dependencies in package.json', async () => {
const packageJsonWithFileDeps = JSON.stringify({
name: "test-project",
dependencies: {
"@bitchat/capacitor-ble-mesh": "file:./capacitor-bitchat-mesh",
"react": "^18.2.0"
}
});
// Mock required files
vi.mocked(mockFS.readFile)
.mockImplementation(async (path: string) => {
if (path.endsWith('package.json')) {
return packageJsonWithFileDeps;
}
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 stat to indicate no 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,
esmUrl: 'https://esm.shakespeare.diy',
});
// Should successfully build with file: dependencies
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
+125 -57
View File
@@ -10,6 +10,7 @@ import { fsPlugin } from "./fsPlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { Plugin } from 'esbuild-wasm';
export interface BuildProjectOptions {
fs: JSRuntimeFS;
@@ -20,6 +21,115 @@ export interface BuildProjectOptions {
esmUrl: string;
}
export interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
export interface PackageLock {
packages: {
[key: string]: {
name?: string;
version: string;
dependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
} | undefined;
};
}
export interface TsConfig {
compilerOptions?: {
baseUrl?: string;
paths?: Record<string, string[]>;
};
}
export interface BuildContext {
packageJson: PackageJson;
packageLock: PackageLock;
tsconfig?: TsConfig;
}
/**
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
* Exported for use by deployment adapters that need to bundle workers
*/
export async function readBuildContext(
fs: JSRuntimeFS,
projectPath: string,
): Promise<BuildContext> {
// Read package.json
let packageJson: PackageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
// Try to read tsconfig.json
let tsconfig: TsConfig | undefined;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
// tsconfig.json is optional
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock: PackageLock;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
console.log(`Building with npm (package-lock.json)`);
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
console.log(`Building with yarn (yarn.lock)`);
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
console.log(`Building with package.json only (no lock file)`);
}
}
return { packageJson, packageLock, tsconfig };
}
/**
* Create the common esbuild plugins for both project and worker builds
* Exported for use by deployment adapters that need to bundle workers
*/
export function createPlugins(
fs: JSRuntimeFS,
projectPath: string,
context: BuildContext,
esmUrl: string,
target?: string,
): Plugin[] {
return [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
];
}
async function bundle(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
@@ -31,58 +141,8 @@ async function bundle(
"utf8",
);
// Read package.json
let packageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
// Try to read tsconfig.json
let tsconfig;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
// tsconfig.json is optional
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock;
let buildMode: string;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
buildMode = "npm (package-lock.json)";
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
console.log(`Building with ${buildMode}`);
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(fs, projectPath);
const doc = domParser.parseFromString(indexHtmlText, "text/html");
const entryPoints: string[] = [];
@@ -128,11 +188,7 @@ async function bundle(
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
define: {
"import.meta.env": JSON.stringify({}),
},
@@ -231,6 +287,18 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
// Public directory doesn't exist, which is fine
}
// Copy NIP.md if it exists in project root
try {
const nipMdPath = `${projectPath}/NIP.md`;
const nipMdStat = await fs.stat(nipMdPath);
if (nipMdStat.isFile()) {
const nipMdContent = await fs.readFile(nipMdPath);
await fs.writeFile(`${outputPath}/NIP.md`, nipMdContent);
}
} catch {
// NIP.md doesn't exist, which is fine
}
// Extract project ID from the project path
// Expected format: /projects/{projectId}
const projectId = projectPath.split('/').pop();
+7 -4
View File
@@ -1,7 +1,7 @@
import type OpenAI from 'openai';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { saveFileToTmp } from './fileUtils';
import { fileToUrl } from './imageUtils';
import { fileToUrl, resizeImageIfNeeded } from './imageUtils';
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
@@ -41,8 +41,11 @@ export async function buildMessageContent(
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
// Resize image if needed before processing
const processedFile = await resizeImageIfNeeded(file);
// Save file to VFS (always do this)
const savedPath = await saveFileToTmp(fs, file, tmpPath);
const savedPath = await saveFileToTmp(fs, processedFile, tmpPath);
// Always add text part with VFS path
const textPart: ContentPart = {
@@ -51,10 +54,10 @@ export async function buildMessageContent(
};
// For all image types, also add as image_url for UI display with base64 encoding
const isImage = file.type.startsWith('image/');
const isImage = processedFile.type.startsWith('image/');
if (isImage) {
try {
const imageUrl = await fileToUrl(file);
const imageUrl = await fileToUrl(processedFile);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
+81
View File
@@ -0,0 +1,81 @@
/** Category types from Keep a Changelog format. */
type ChangelogCategory = 'Added' | 'Changed' | 'Deprecated' | 'Removed' | 'Fixed' | 'Security';
/** A single version entry in the changelog. */
interface ChangelogEntry {
version: string;
date: string;
sections: {
category: ChangelogCategory;
items: string[];
}[];
}
/** Apply basic typographic transformations to a changelog item string. */
function prettify(text: string): string {
return text
.replace(/ -- /g, ' \u2014 ') // space-dash-dash-space → em dash
.replace(/(\w)--(\w)/g, '$1\u2013$2') // word--word → en dash
.replace(/ (\S+)$/, '\u00A0$1'); // prevent orphaned last word
}
/**
* Parse a Keep a Changelog formatted markdown string into structured data.
* @see https://keepachangelog.com/
*/
function parseChangelog(markdown: string): ChangelogEntry[] {
const entries: ChangelogEntry[] = [];
let current: ChangelogEntry | null = null;
let currentCategory: ChangelogCategory | null = null;
for (const line of markdown.split('\n')) {
// Match version heading: ## [X.Y.Z] - YYYY-MM-DD
const versionMatch = line.match(/^## \[([^\]]+)\]\s*-\s*(.+)$/);
if (versionMatch) {
current = { version: versionMatch[1], date: versionMatch[2].trim(), sections: [] };
entries.push(current);
currentCategory = null;
continue;
}
// Match category heading: ### Added, ### Changed, etc.
const categoryMatch = line.match(/^### (.+)$/);
if (categoryMatch && current) {
currentCategory = categoryMatch[1].trim() as ChangelogCategory;
current.sections.push({ category: currentCategory, items: [] });
continue;
}
// Match list item: - Description
const itemMatch = line.match(/^- (.+)$/);
if (itemMatch && current) {
const section = current.sections[current.sections.length - 1];
if (section) {
section.items.push(prettify(itemMatch[1]));
} else {
// Item without a category heading — treat as "Changed"
current.sections.push({ category: 'Changed', items: [prettify(itemMatch[1])] });
}
continue;
}
// Lines that don't start with "- " but aren't blank may be a continuation or
// freeform text after the version heading (e.g. "Initial release of Shakespeare").
const trimmed = line.trim();
if (trimmed && current && !trimmed.startsWith('#')) {
const section = current.sections[current.sections.length - 1];
if (section) {
// Append to last item or add new item
section.items.push(prettify(trimmed));
} else {
// Freeform text under version with no category — store in a generic section
current.sections.push({ category: 'Changed', items: [prettify(trimmed)] });
}
}
}
return entries;
}
export { parseChangelog };
export type { ChangelogEntry, ChangelogCategory };
+1 -1
View File
@@ -66,7 +66,7 @@ export class CurlCommand implements ShellCommand {
// Proxy the URL through configured CorsProxy
const originalUrl = url.toString();
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
const proxiedUrl = proxyUrl({ template: this.corsProxy, url: originalUrl });
// Prepare request
const requestInit: RequestInit = {
+1 -1
View File
@@ -80,7 +80,7 @@ export class MkdirCommand implements ShellCommand {
// Create the directory
await this.fs.mkdir(absolutePath);
} else {
return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`);
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ export class TouchCommand implements ShellCommand {
await this.fs.writeFile(absolutePath, '', 'utf8');
} else {
// Other error (permission, etc.)
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
return createErrorResult(`${this.name}: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
+10 -2
View File
@@ -37,6 +37,7 @@ const aiProviderSchema = z.object({
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
proxy: z.boolean().optional(),
openSecret: z.string().url().optional(),
});
const providerModelSchema = z.string().regex(
@@ -129,6 +130,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
baseDomain: z.string().optional(),
});
const railwayProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('railway'),
apiKey: z.string(),
baseURL: z.string().optional(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
@@ -136,6 +143,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
railwayProviderSchema,
]);
const deploySettingsSchema = z.object({
@@ -200,7 +208,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
};
} catch (error) {
if (error instanceof z.ZodError) {
console.error('AI settings parsing error:', error.errors);
console.error('AI settings parsing error:', error.issues);
}
return defaultSettings;
}
@@ -321,7 +329,7 @@ export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'
return deploySettingsSchema.parse(data);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('Deploy settings parsing error:', error.errors);
console.error('Deploy settings parsing error:', error.issues);
}
return defaultSettings;
}
+150 -23
View File
@@ -1,6 +1,10 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
import { parse as parseJsonc } from 'jsonc-parser';
import { join } from 'path-browserify';
import { readBuildContext, createPlugins } from '../build';
import { getEsbuild } from '../esbuild';
interface AssetManifest {
[path: string]: { hash: string; size: number };
@@ -24,6 +28,16 @@ interface WorkerScript {
has_assets: boolean;
}
interface WranglerConfig {
compatibility_date?: string;
main?: string;
assets?: {
directory?: string;
html_handling?: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none';
not_found_handling?: 'single-page-application' | '404-page' | 'none';
};
}
interface FileInfo {
hash: string;
content: Uint8Array;
@@ -49,6 +63,7 @@ export class CloudflareAdapter implements DeployAdapter {
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
private esmUrl: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
@@ -58,11 +73,15 @@ export class CloudflareAdapter implements DeployAdapter {
this.baseDomain = config.baseDomain || 'workers.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
this.esmUrl = config.esmUrl;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Try to read wrangler.jsonc configuration
const wranglerConfig = await this.readWranglerConfig(projectPath);
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
@@ -115,7 +134,7 @@ export class CloudflareAdapter implements DeployAdapter {
}
// Step 4: Deploy the worker with assets
const deployment = await this.deployWorker(scriptName, completionJwt);
const deployment = await this.deployWorker(scriptName, completionJwt, projectPath, wranglerConfig);
// Step 5: Enable the workers.dev subdomain for this script
await this.enableWorkersDevSubdomain(scriptName);
@@ -140,7 +159,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async getWorkersSubdomain(): Promise<string> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -160,7 +179,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -185,7 +204,7 @@ export class CloudflareAdapter implements DeployAdapter {
manifest: AssetManifest
): Promise<InitializeAssetsResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -211,7 +230,7 @@ export class CloudflareAdapter implements DeployAdapter {
hashToFile: Map<string, { path: string; info: FileInfo }>
): Promise<UploadResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const formData = new FormData();
@@ -249,37 +268,105 @@ export class CloudflareAdapter implements DeployAdapter {
return data.result || {};
}
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
const esbuild = await getEsbuild();
// Create a minimal worker script that serves static assets
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
const workerScript = `
export default {
async fetch(request, env) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(this.fs, projectPath);
// Resolve the entry point path
const entryPointPath = entryPoint.startsWith('/')
? entryPoint
: join(projectPath, entryPoint);
// Build the worker with dependencies bundled
const results = await esbuild.build({
entryPoints: [entryPointPath],
bundle: true,
write: false,
format: "esm",
target: "esnext",
outdir: "/",
metafile: true,
sourcemap: false, // Workers typically don't need sourcemaps
plugins: createPlugins(this.fs, projectPath, context, this.esmUrl),
define: {
"import.meta.env": JSON.stringify({}),
},
});
if (results.outputFiles.length === 0) {
throw new Error(`Failed to bundle worker: no output files generated`);
}
// Return the bundled worker code as a string
return results.outputFiles[0].text;
}
};
`;
private async deployWorker(
scriptName: string,
assetsJwt: string,
projectPath: string,
wranglerConfig?: WranglerConfig
): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Determine the main module name from wrangler.jsonc or try defaults
let mainModuleName = 'worker.js';
let workerScript = this.getDefaultWorkerScript();
if (wranglerConfig?.main) {
// Use explicitly configured main module
const configuredModule = wranglerConfig.main;
try {
const workerExists = await this.fileExists(join(projectPath, configuredModule));
if (workerExists) {
mainModuleName = configuredModule;
workerScript = await this.bundleWorker(configuredModule, projectPath);
} else {
throw new Error(`Configured worker file not found: ${configuredModule}`);
}
} catch (error) {
console.warn(`Failed to bundle configured worker script, using default:`, error);
// Keep default values
}
} else {
// Try default worker files in order: worker.ts -> worker.mjs -> worker.js
const defaultWorkerFiles = ['worker.ts', 'worker.mjs', 'worker.js'];
for (const filename of defaultWorkerFiles) {
try {
const workerExists = await this.fileExists(join(projectPath, filename));
if (workerExists) {
mainModuleName = filename;
workerScript = await this.bundleWorker(filename, projectPath);
break; // Successfully bundled, stop searching
}
} catch (error) {
console.warn(`Failed to bundle ${filename}:`, error);
// Continue to next file
}
}
// If no custom worker found, use default values already set
}
const formData = new FormData();
// Add the worker script as the main module
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
formData.append('worker.js', scriptBlob, 'worker.js');
formData.append(mainModuleName, scriptBlob, mainModuleName);
// Add metadata with assets configuration
const metadata = {
main_module: 'worker.js',
compatibility_date: new Date().toISOString().split('T')[0],
main_module: mainModuleName,
compatibility_date: wranglerConfig?.compatibility_date || new Date().toISOString().split('T')[0],
assets: {
jwt: assetsJwt,
config: {
html_handling: 'auto-trailing-slash',
not_found_handling: 'single-page-application',
html_handling: wranglerConfig?.assets?.html_handling || 'auto-trailing-slash',
not_found_handling: wranglerConfig?.assets?.not_found_handling || 'single-page-application',
},
},
};
@@ -303,6 +390,27 @@ export default {
return data.result;
}
private async readWranglerConfig(projectPath: string): Promise<WranglerConfig | undefined> {
// Try wrangler.jsonc first, then wrangler.json
const configPaths = [
join(projectPath, 'wrangler.jsonc'),
join(projectPath, 'wrangler.json'),
];
for (const configPath of configPaths) {
try {
const configContent = await this.fs.readFile(configPath, 'utf8');
// Parse JSONC (JSON with comments) using jsonc-parser
return parseJsonc(configContent) as WranglerConfig;
} catch {
// Continue to next path
}
}
// No wrangler config found, return undefined
return undefined;
}
private async collectFiles(
dirPath: string,
relativePath: string,
@@ -403,4 +511,23 @@ export default {
};
return mimeTypes[ext] || 'application/octet-stream';
}
private async fileExists(path: string): Promise<boolean> {
try {
const stat = await this.fs.stat(path);
return stat.isFile();
} catch {
return false;
}
}
private getDefaultWorkerScript(): string {
return `export default {
async fetch(request) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
}
};`;
}
}
+3 -3
View File
@@ -96,7 +96,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async findProject(projectName: string): Promise<Project | null> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -116,7 +116,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async createProject(projectName: string): Promise<Project> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -143,7 +143,7 @@ export class DenoDeployAdapter implements DeployAdapter {
domain: string
): Promise<Deployment> {
const url = `${this.baseURL}/projects/${projectId}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Create a minimal server script that serves static files
// For static sites, we use a simple file server entry point
+198 -29
View File
@@ -11,11 +11,13 @@ interface NetlifySite {
admin_url: string;
}
interface NetlifyBuildResponse {
interface NetlifyDeployResponse {
id: string;
deploy_id: string;
state: string;
error?: string;
required?: string[];
required_functions?: string[];
}
/**
@@ -65,31 +67,47 @@ export class NetlifyAdapter implements DeployAdapter {
siteUrl = site.url;
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(distPath, zip);
// Collect files and their SHA1 hashes
const files: Record<string, string> = {};
const fileContents = new Map<string, Uint8Array>();
await this.collectFiles(distPath, '', files, fileContents);
// Ensure _redirects file exists for SPA routing
await this.ensureRedirectsFile(distPath, zip);
await this.ensureRedirectsInFiles(distPath, files, fileContents);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Collect functions and their SHA256 hashes
const functions: Record<string, string> = {};
const functionZips = new Map<string, Blob>();
const functionsPath = `${projectPath}/netlify/functions`;
await this.collectFunctions(functionsPath, functions, functionZips);
// Deploy to Netlify
await this.triggerDeploy(activeSiteId, zipBlob);
// Create deploy with file and function digests
const deployResponse = await this.createDeployWithDigest(activeSiteId, files, functions);
// Upload required files
if (deployResponse.required && deployResponse.required.length > 0) {
await this.uploadFiles(deployResponse.id, files, fileContents, deployResponse.required);
}
// Upload required functions
if (deployResponse.required_functions && deployResponse.required_functions.length > 0) {
await this.uploadFunctions(deployResponse.id, functions, functionZips, deployResponse.required_functions);
}
return {
url: siteUrl,
metadata: {
siteId: activeSiteId,
deployId: deployResponse.id,
provider: 'netlify',
functionsDeployed: Object.keys(functions).length,
},
};
}
private async createSite(name: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -113,7 +131,7 @@ export class NetlifyAdapter implements DeployAdapter {
private async getSite(siteId: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites/${siteId}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -130,45 +148,57 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json();
}
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
private async createDeployWithDigest(
siteId: string,
files: Record<string, string>,
functions: Record<string, string>
): Promise<NetlifyDeployResponse> {
const url = `${this.baseURL}/sites/${siteId}/deploys`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const body: { files: Record<string, string>; functions?: Record<string, string> } = { files };
if (Object.keys(functions).length > 0) {
body.functions = functions;
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/zip',
'Content-Type': 'application/json',
},
body: zipBlob,
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
throw new Error(`Failed to create Netlify deploy: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
private async collectFiles(
dirPath: string,
relativePath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
await this.collectFiles(fullPath, relPath, files, fileContents);
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
const sha1 = await this.calculateSHA1(fileContent);
files[`/${relPath}`] = sha1;
fileContents.set(sha1, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
@@ -181,9 +211,13 @@ export class NetlifyAdapter implements DeployAdapter {
/**
* Ensures _redirects file exists in the deployment for SPA routing
* If not present in dist directory, adds it to the ZIP with default content
* If not present in dist directory, adds it to the files manifest
*/
private async ensureRedirectsFile(distPath: string, zip: JSZip): Promise<void> {
private async ensureRedirectsInFiles(
distPath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
const redirectsPath = `${distPath}/_redirects`;
try {
@@ -192,11 +226,146 @@ export class NetlifyAdapter implements DeployAdapter {
if (!stat.isFile()) {
throw new Error('_redirects is not a file');
}
// File exists, no need to add it (already added by addDirectoryToZip)
// File exists, already collected by collectFiles
} catch {
// File doesn't exist, add default _redirects to ZIP
// File doesn't exist, add default _redirects
const defaultRedirects = '/* /index.html 200';
zip.file('_redirects', defaultRedirects);
const content = new TextEncoder().encode(defaultRedirects);
const sha1 = await this.calculateSHA1(content);
files['/_redirects'] = sha1;
fileContents.set(sha1, content);
}
}
private async collectFunctions(
functionsPath: string,
functions: Record<string, string>,
functionZips: Map<string, Blob>
): Promise<void> {
try {
// Check if functions directory exists
const stat = await this.fs.stat(functionsPath);
if (!stat.isDirectory()) {
return;
}
const entries = await this.fs.readdir(functionsPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile()) {
const fullPath = `${functionsPath}/${entry.name}`;
// Only process .mjs files (ES modules)
// Note: .js and .ts files require bundling which is not supported in this adapter
if (entry.name.endsWith('.mjs')) {
try {
const functionContent = await this.fs.readFile(fullPath);
// Create a zip for this function
const zip = new JSZip();
zip.file(entry.name, functionContent);
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Calculate SHA256 hash
const sha256 = await this.calculateSHA256FromBlob(zipBlob);
// Function name without extension
const functionName = entry.name.replace(/\.mjs$/, '');
functions[functionName] = sha256;
functionZips.set(sha256, zipBlob);
} catch (error) {
console.warn(`Failed to process function ${entry.name}:`, error);
}
}
}
}
} catch {
// Functions directory doesn't exist, skip
}
}
private async uploadFiles(
deployId: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>,
requiredShas: string[]
): Promise<void> {
const requiredSet = new Set(requiredShas);
for (const [filePath, sha1] of Object.entries(files)) {
if (requiredSet.has(sha1)) {
const content = fileContents.get(sha1);
if (!content) {
console.warn(`Content not found for ${filePath} (${sha1})`);
continue;
}
// Escape file path for URL
const encodedPath = filePath.split('/').map(encodeURIComponent).join('/');
const url = `${this.baseURL}/deploys/${deployId}/files${encodedPath}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/octet-stream',
},
body: content,
});
if (!response.ok) {
console.warn(`Failed to upload file ${filePath}: ${response.status} ${response.statusText}`);
}
}
}
}
private async uploadFunctions(
deployId: string,
functions: Record<string, string>,
functionZips: Map<string, Blob>,
requiredShas: string[]
): Promise<void> {
const requiredSet = new Set(requiredShas);
for (const [functionName, sha256] of Object.entries(functions)) {
if (requiredSet.has(sha256)) {
const zipBlob = functionZips.get(sha256);
if (!zipBlob) {
console.warn(`Zip not found for function ${functionName} (${sha256})`);
continue;
}
const url = `${this.baseURL}/deploys/${deployId}/functions/${encodeURIComponent(functionName)}?runtime=js`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/octet-stream',
},
body: zipBlob,
});
if (!response.ok) {
console.warn(`Failed to upload function ${functionName}: ${response.status} ${response.statusText}`);
}
}
}
}
private async calculateSHA1(data: Uint8Array): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
private async calculateSHA256FromBlob(blob: Blob): Promise<string> {
const arrayBuffer = await blob.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
}
+321 -113
View File
@@ -1,174 +1,382 @@
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
import { NSecSigner, NPool } from '@nostrify/nostrify';
import type { NostrEvent } from '@nostrify/nostrify';
import type { NostrSigner } from '@nostrify/nostrify';
import mime from 'mime';
import { nip19 } from 'nostr-tools';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
import { buildNsiteUrl } from '../utils/nsite';
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
const NSITE_ROOT_SITE_KIND = 15128;
/** nsite v2 named-site kind (addressable by pubkey+kind+d) */
const NSITE_NAMED_SITE_KIND = 35128;
/** BUD-02 Blossom authorization event kind */
const BLOSSOM_AUTH_KIND = 24242;
/** Max number of sha256 hashes covered by one batch auth event */
const UPLOAD_AUTH_BATCH_SIZE = 20;
/** Max concurrent uploads per Blossom server */
const UPLOAD_CONCURRENCY = 4;
/** Timeout for individual HTTP requests (ms) */
const FETCH_TIMEOUT_MS = 15_000;
interface FileEntry {
/** Absolute path in the manifest, e.g. "/index.html" */
path: string;
/** Raw file bytes as a concrete ArrayBuffer (for Web Crypto + File constructor compatibility) */
data: ArrayBuffer;
/** Lower-case hex SHA-256 of data */
sha256: string;
/** MIME type */
contentType: string;
}
/**
* Nsite Deploy Adapter
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
* Encode an ArrayBuffer / Uint8Array as a lower-case hex string.
*/
function encodeHex(bytes: Uint8Array): string {
return Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* Compute the SHA-256 of a Uint8Array and return the hex digest.
* The Uint8Array must already be backed by a concrete ArrayBuffer
* (use raw.slice() before calling this to ensure no SharedArrayBuffer).
*/
async function sha256Hex(data: Uint8Array): Promise<string> {
const buf = await crypto.subtle.digest('SHA-256', data.buffer as ArrayBuffer);
return encodeHex(new Uint8Array(buf));
}
/**
* Build a BUD-02 kind-24242 upload-auth event template covering multiple blobs.
* The signed event is base64-encoded and returned as the full Authorization header value.
*/
async function createBatchUploadAuth(
signer: NostrSigner,
sha256Hashes: string[],
): Promise<string> {
const now = Math.floor(Date.now() / 1000);
const template = {
kind: BLOSSOM_AUTH_KIND,
created_at: now,
tags: [
['t', 'upload'],
...sha256Hashes.map(h => ['x', h]),
['expiration', String(now + 3600)],
],
content: 'Upload blobs',
};
const signed = await signer.signEvent(template);
return `Nostr ${btoa(JSON.stringify(signed))}`;
}
/**
* Check whether a blob already exists on a Blossom server.
* Returns true if the server responds 2xx to a HEAD request.
*/
async function blobExistsOnServer(serverBase: string, sha256: string): Promise<boolean> {
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const resp = await fetch(`${serverBase}/${sha256}`, {
method: 'HEAD',
signal: controller.signal,
});
return resp.ok;
} finally {
clearTimeout(timer);
}
} catch {
return false;
}
}
/**
* Upload a single file to a single Blossom server using a pre-signed auth header.
* Skips the upload if the blob already exists on the server.
* Returns true on success or if already present.
*/
async function uploadToServer(
serverBase: string,
file: FileEntry,
authHeader: string,
): Promise<boolean> {
// Skip if already present
if (await blobExistsOnServer(serverBase, file.sha256)) {
return true;
}
const blob = new File([file.data], file.path.split('/').pop() || 'file', {
type: file.contentType,
});
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const resp = await fetch(`${serverBase}/upload`, {
method: 'PUT',
headers: {
Authorization: authHeader,
'Content-Type': file.contentType,
},
body: blob,
signal: controller.signal,
});
return resp.ok;
} finally {
clearTimeout(timer);
}
} catch {
return false;
}
}
/**
* Run an async task queue with a fixed concurrency limit.
*/
async function runConcurrent<T>(
items: T[],
limit: number,
fn: (item: T) => Promise<void>,
): Promise<void> {
let index = 0;
async function worker() {
while (index < items.length) {
const item = items[index++];
await fn(item);
}
}
const workers: Promise<void>[] = [];
for (let i = 0; i < Math.min(limit, items.length); i++) {
workers.push(worker());
}
await Promise.all(workers);
}
/**
* Nsite Deploy Adapter — v2 implementation
*
* Deploys a built project as a Nostr static site using the nsite v2 spec:
* - Uses the logged-in user's NostrSigner — no dedicated per-site keypair needed
* - Pre-hashes all files with SHA-256 (Web Crypto API)
* - Signs batched BUD-02 kind-24242 auth tokens (20 files per signing call)
* - HEAD-checks each file on each Blossom server before uploading
* - PUTs files to Blossom servers with pre-signed auth headers
* - Publishes a single kind-15128 (root) or kind-35128 (named) site manifest event
* containing all ["path", "/path", sha256] tags, ["server", url] Blossom hints,
* and ["relay", url] relay hints — no separate kind 10002 or kind 10063 published
*
* Named sites (kind 35128, siteIdentifier set):
* URL = https://{base36pubkey}{siteIdentifier}.{gateway}
* Root sites (kind 15128, no siteIdentifier):
* URL = https://{npub}.{gateway}
*/
export class NsiteAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private nostr: NsiteDeployConfig['nostr'];
private nsec: string;
private signer: NostrSigner;
private gateway: string;
private relayUrls: string[];
private blossomServers: string[];
private siteTitle?: string;
private siteDescription?: string;
private sourceUrl?: string;
private siteIdentifier?: string;
constructor(config: NsiteDeployConfig) {
this.fs = config.fs;
this.nostr = config.nostr;
this.nsec = config.nsec;
this.signer = config.signer;
this.gateway = config.gateway;
this.relayUrls = config.relayUrls;
this.blossomServers = config.blossomServers;
this.siteTitle = config.siteTitle;
this.siteDescription = config.siteDescription;
this.sourceUrl = config.sourceUrl;
this.siteIdentifier = config.siteIdentifier;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
// Verify build output exists
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Decode nsec to get the private key and create signer
const decoded = nip19.decode(this.nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec format');
}
const signer = new NSecSigner(decoded.data);
const pubkey = await signer.getPublicKey();
const pubkey = await this.signer.getPublicKey();
const npub = nip19.npubEncode(pubkey);
// Create a grouped Nostr client for the configured relays
// Create grouped relay client
const relayClient = this.nostr.group(this.relayUrls);
// Initialize Blossom uploader
const uploader = new BlossomUploader({
servers: this.blossomServers,
signer,
// ── Step 1: Walk dist/ and read + hash all files ──────────────────────────
const files: FileEntry[] = [];
await this.collectFiles(distPath, '', files);
if (files.length === 0) {
throw new Error('No files found in dist directory.');
}
// ── Step 2: Pre-sign batched BUD-02 auth tokens ───────────────────────────
// One kind-24242 event covers up to UPLOAD_AUTH_BATCH_SIZE sha256 hashes,
// dramatically reducing signer calls when using remote signers/bunkers.
const authTokenMap = new Map<string, string>();
for (let i = 0; i < files.length; i += UPLOAD_AUTH_BATCH_SIZE) {
const batch = files.slice(i, i + UPLOAD_AUTH_BATCH_SIZE);
const hashes = batch.map(f => f.sha256);
const authHeader = await createBatchUploadAuth(this.signer, hashes);
for (const hash of hashes) {
authTokenMap.set(hash, authHeader);
}
}
// ── Step 3: Upload files to each Blossom server ───────────────────────────
// All servers upload concurrently; within each server, files are uploaded
// with limited concurrency to avoid overwhelming the server.
// Track which files land on at least one server — a file missing from every
// server means the manifest would point to an unreachable blob.
const serverBases = this.blossomServers.map(s => s.replace(/\/$/, ''));
// uploadedSha256s: set of sha256 hashes confirmed present on ≥1 server
const uploadedSha256s = new Set<string>();
await Promise.all(
serverBases.map(serverBase =>
runConcurrent(files, UPLOAD_CONCURRENCY, async (file) => {
const authHeader = authTokenMap.get(file.sha256);
if (!authHeader) return;
const ok = await uploadToServer(serverBase, file, authHeader);
if (ok) {
uploadedSha256s.add(file.sha256);
}
}),
),
);
// Fail fast: any file unreachable on all servers means the deployed site
// would serve broken responses for those paths — abort before publishing.
const failedFiles = files.filter(f => !uploadedSha256s.has(f.sha256));
if (failedFiles.length > 0) {
const paths = failedFiles.map(f => f.path).join(', ');
throw new Error(
`Failed to upload ${failedFiles.length} file(s) to any Blossom server: ${paths}`,
);
}
// ── Step 4: Build the site manifest event ────────────────────────────────
// kind 35128 for named sites (has siteIdentifier / d tag)
// kind 15128 for root site (no d tag)
const isNamedSite = Boolean(this.siteIdentifier);
const manifestKind = isNamedSite ? NSITE_NAMED_SITE_KIND : NSITE_ROOT_SITE_KIND;
const pathTags: string[][] = files.map(f => ['path', f.path, f.sha256]);
// SPA fallback: map /404.html to the same blob as /index.html so that
// React Router (and other SPAs) work correctly — the nsite host server
// serves /404.html when a path is not found, acting as a client-side router fallback.
const indexFile = files.find(f => f.path === '/index.html');
if (indexFile && !files.some(f => f.path === '/404.html')) {
pathTags.push(['path', '/404.html', indexFile.sha256]);
}
const serverTags: string[][] = serverBases.map(url => ['server', url]);
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
const tags: string[][] = [];
// d tag must come first for addressable events (kind 35128)
if (isNamedSite && this.siteIdentifier) {
tags.push(['d', this.siteIdentifier]);
}
tags.push(...pathTags, ...serverTags, ...relayTags);
if (this.siteTitle) {
tags.push(['title', this.siteTitle]);
}
if (this.siteDescription) {
tags.push(['description', this.siteDescription]);
}
if (this.sourceUrl) {
tags.push(['source', this.sourceUrl]);
}
const manifestEvent = await this.signer.signEvent({
kind: manifestKind,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags,
});
// Collect all files and upload them
const fileEvents: NostrEvent[] = [];
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
// ── Step 5: Publish manifest ──────────────────────────────────────────────
// Relay and server hints are embedded as tags in the manifest itself —
// no separate kind 10002 or kind 10063 events are published.
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
// Publish file events and other metadata to the relays
await Promise.all([
this.publishRelayList(signer, relayClient),
this.publishServerList(signer, relayClient),
...fileEvents.map(event => relayClient.event(event, { signal: AbortSignal.timeout(5000) })),
]);
// Generate npub subdomain
const npub = nip19.npubEncode(pubkey);
const siteUrl = `https://${npub}.${this.gateway}`;
// Build the deployed URL
const siteUrl = buildNsiteUrl({
pubkeyHex: pubkey,
npub,
gateway: this.gateway,
siteIdentifier: this.siteIdentifier,
});
return {
url: siteUrl,
metadata: {
pubkey,
npub,
filesPublished: fileEvents.length,
filesPublished: files.length,
provider: 'nsite',
siteIdentifier: this.siteIdentifier,
manifestKind,
},
};
}
private async uploadDirectory(
/**
* Recursively walk a directory in the VFS, reading every file and computing its SHA-256.
* Populates the provided `files` array with fully resolved FileEntry objects.
*/
private async collectFiles(
dirPath: string,
relativePath: string,
uploader: BlossomUploader,
signer: NSecSigner,
fileEvents: NostrEvent[]
relativePrefix: string,
files: FileEntry[],
): Promise<void> {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
const relPath = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
await this.collectFiles(fullPath, relPath, files);
} else if (entry.isFile()) {
await this.uploadFile(fullPath, relPath, uploader, signer, fileEvents);
const raw = await this.fs.readFile(fullPath) as Uint8Array;
// raw.slice() copies bytes into a new Uint8Array backed by a concrete ArrayBuffer,
// avoiding the SharedArrayBuffer variant that Web Crypto and File refuse.
const sliced = raw.slice();
const data: ArrayBuffer = sliced.buffer as ArrayBuffer;
const sha256 = await sha256Hex(sliced);
const absolutePath = `/${relPath}`;
const contentType = mime.getType(fullPath) || 'application/octet-stream';
files.push({ path: absolutePath, data, sha256, contentType });
}
}
}
private async uploadFile(
filePath: string,
relativePath: string,
uploader: BlossomUploader,
signer: NSecSigner,
fileEvents: NostrEvent[]
): Promise<void> {
try {
// Read file content
const content = await this.fs.readFile(filePath);
// Convert to File object for upload
const file = new File([content], relativePath.split('/').pop() || 'file', {
type: mime.getType(filePath) || undefined,
});
// Upload to Blossom and get tags
const tags = await uploader.upload(file);
// Extract sha256 hash from tags
// Tags format: [['url', 'https://...'], ['x', 'sha256hash'], ['size', '1234'], ...]
const xTag = tags.find(([name]) => name === 'x');
if (!xTag || !xTag[1]) {
throw new Error(`Failed to get sha256 hash for ${relativePath}`);
}
const sha256 = xTag[1];
// Create absolute path (must start with /)
const absolutePath = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
// Create kind 34128 event
const event = await signer.signEvent({
kind: 34128,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags: [
['d', absolutePath],
['x', sha256],
],
});
fileEvents.push(event);
} catch (error) {
console.warn(`Failed to upload file ${filePath}:`, error);
throw error;
}
}
private async publishRelayList(signer: NSecSigner, relayClient: NPool): Promise<void> {
const relayListEvent = await signer.signEvent({
kind: 10002,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags: this.relayUrls.map(url => ['r', url]),
});
await relayClient.event(relayListEvent, { signal: AbortSignal.timeout(5000) });
}
private async publishServerList(signer: NSecSigner, relayClient: NPool): Promise<void> {
const serverListEvent = await signer.signEvent({
kind: 10063,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags: this.blossomServers.map(server => ['server', server]),
});
await relayClient.event(serverListEvent, { signal: AbortSignal.timeout(5000) });
}
}
+627
View File
@@ -0,0 +1,627 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, RailwayDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface Workspace {
id: string;
name: string;
team: {
id: string;
} | null;
projects: {
edges: Array<{
node: Project;
}>;
};
}
interface Project {
id: string;
name: string;
environments: {
edges: Array<{
node: Environment;
}>;
};
services: {
edges: Array<{
node: Service;
}>;
};
}
interface Environment {
id: string;
name: string;
}
interface Service {
id: string;
name: string;
}
interface DeploymentResponse {
deploymentId: string;
url: string;
logsUrl?: string;
deploymentDomain: string;
}
/**
* Railway Deploy Adapter
* Uses Railway GraphQL API and REST upload endpoint
*
* Implements the Railway deployment workflow:
* 1. Query for workspaces and projects (or use provided IDs)
* 2. Create project if needed
* 3. Create service if needed
* 4. Create tarball of entire source code (excluding common dev files)
* 5. Upload tarball to Railway via multipart/form-data
*/
export class RailwayAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string;
private workspaceId?: string;
private projectId?: string;
private environmentId?: string;
private serviceId?: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: RailwayDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://backboard.railway.com';
this.workspaceId = config.workspaceId;
this.projectId = config.projectId;
this.environmentId = config.environmentId;
this.serviceId = config.serviceId;
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Step 1: Ensure we have a workspace
if (!this.workspaceId) {
const workspaces = await this.getWorkspaces();
if (workspaces.length === 0) {
throw new Error('No workspaces found. Please create a workspace on Railway first.');
}
this.workspaceId = workspaces[0].id;
}
// Step 2: Get or create project
let activeProjectId = this.projectId;
let activeEnvironmentId = this.environmentId;
if (!activeProjectId) {
const project = await this.createProject(this.projectName || projectId);
activeProjectId = project.id;
// Get the default production environment
activeEnvironmentId = project.environments.edges[0]?.node.id;
} else if (!activeEnvironmentId) {
// If we have project ID but no environment, fetch the project to get the environment
const project = await this.getProject(activeProjectId);
activeEnvironmentId = project.environments.edges[0]?.node.id;
}
if (!activeEnvironmentId) {
throw new Error('No environment found for project');
}
// Step 3: Get or create service
let activeServiceId = this.serviceId;
if (!activeServiceId) {
const service = await this.createService(activeProjectId, projectId);
activeServiceId = service.id;
}
// Step 4: Create tarball of source code
const tarball = await this.createTarball(projectPath);
// Step 5: Upload to Railway
const deployment = await this.uploadDeployment(
activeProjectId,
activeEnvironmentId,
activeServiceId,
tarball
);
// Step 6: Wait for deployment to complete
await this.waitForDeployment(deployment.deploymentId);
// Step 7: Check for existing domains and create one if needed
const domain = await this.ensureServiceDomain(
activeProjectId,
activeEnvironmentId,
activeServiceId
);
return {
url: domain ? `https://${domain}` : deployment.url,
metadata: {
deploymentId: deployment.deploymentId,
projectId: activeProjectId,
environmentId: activeEnvironmentId,
serviceId: activeServiceId,
provider: 'railway',
deploymentDomain: domain || deployment.deploymentDomain,
},
};
}
private async graphqlRequest<T>(query: string, variables?: Record<string, unknown>): Promise<T> {
const url = `${this.baseURL}/graphql/v2`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Railway GraphQL request failed: ${response.status} ${response.statusText}. ${errorText}`);
}
const result = await response.json();
if (result.errors) {
const errorMessages = result.errors.map((e: { message: string }) => e.message).join(', ');
throw new Error(`Railway GraphQL error: ${errorMessages}`);
}
return result.data;
}
private async getWorkspaces(): Promise<Workspace[]> {
const query = `
query UserWorkspaces {
me {
workspaces {
id
name
team {
id
}
projects(first: 500) {
edges {
node {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ me: { workspaces: Workspace[] } }>(query);
return data.me.workspaces;
}
private async getProject(projectId: string): Promise<Project> {
const query = `
query GetProject($projectId: String!) {
project(id: $projectId) {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ project: Project }>(query, { projectId });
return data.project;
}
private async createProject(name: string): Promise<Project> {
const query = `
mutation ProjectCreate($name: String, $workspaceId: String) {
projectCreate(input: {
name: $name,
workspaceId: $workspaceId
}) {
id
name
environments {
edges {
node {
id
name
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ projectCreate: Project }>(query, {
name,
workspaceId: this.workspaceId,
});
return data.projectCreate;
}
private async createService(projectId: string, name: string): Promise<Service> {
const query = `
mutation ServiceCreate($input: ServiceCreateInput!) {
serviceCreate(input: $input) {
id
name
}
}
`;
const data = await this.graphqlRequest<{ serviceCreate: Service }>(query, {
input: {
name,
projectId,
source: {
image: null,
repo: null,
},
},
});
return data.serviceCreate;
}
private async createTarball(projectPath: string): Promise<Blob> {
// Import tar library dynamically (needs to be available in the project)
// For browser environment, we'll need to use a tar implementation
// Using a simpler approach: collect files and create a tar-like structure
// Collect all files excluding common dev files
const files = new Map<string, Uint8Array>();
await this.collectFilesForTarball(projectPath, '', files);
// Create a simple tar.gz equivalent using browser APIs
// Since we're in a browser environment, we'll create a structure that Railway can accept
const tarData = await this.createTarGzBlob(files);
return tarData;
}
private async collectFilesForTarball(
dirPath: string,
relativePath: string,
files: Map<string, Uint8Array>
): Promise<void> {
// Directories to exclude
const excludeDirs = new Set([
'.git',
'node_modules',
'dist',
'build',
'.next',
'.nuxt',
'.output',
'.vite',
'.cache',
'__pycache__',
'.pytest_cache',
'.venv',
'venv',
'env',
'.DS_Store',
'coverage',
'.nyc_output',
]);
// Files to exclude
const excludeFiles = new Set([
'.env',
'.env.local',
'.env.development',
'.env.production',
'.env.test',
'npm-debug.log',
'yarn-debug.log',
'yarn-error.log',
'.DS_Store',
]);
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
// Skip excluded directories and files
if (excludeDirs.has(entry.name) || excludeFiles.has(entry.name)) {
continue;
}
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFilesForTarball(fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
let bytes: Uint8Array;
if (typeof fileContent === 'string') {
bytes = new TextEncoder().encode(fileContent);
} else {
bytes = fileContent;
}
files.set(entryRelativePath, bytes);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private async createTarGzBlob(files: Map<string, Uint8Array>): Promise<Blob> {
// Create a simple tar structure
// TAR format: 512-byte header + file data (padded to 512 bytes)
const blocks: Uint8Array[] = [];
for (const [filePath, content] of files) {
// Create tar header (simplified)
const header = new Uint8Array(512);
const encoder = new TextEncoder();
// File name (offset 0, 100 bytes)
const nameBytes = encoder.encode(filePath);
header.set(nameBytes.slice(0, 100), 0);
// File mode (offset 100, 8 bytes) - "0000644\0"
header.set(encoder.encode('0000644\0'), 100);
// Owner UID (offset 108, 8 bytes) - "0000000\0"
header.set(encoder.encode('0000000\0'), 108);
// Group GID (offset 116, 8 bytes) - "0000000\0"
header.set(encoder.encode('0000000\0'), 116);
// File size in octal (offset 124, 12 bytes)
const sizeOctal = content.length.toString(8).padStart(11, '0') + '\0';
header.set(encoder.encode(sizeOctal), 124);
// Modification time (offset 136, 12 bytes)
const mtime = Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0';
header.set(encoder.encode(mtime), 136);
// Checksum (offset 148, 8 bytes) - calculate after setting type flag
header.set(encoder.encode(' '), 148);
// Type flag (offset 156, 1 byte) - '0' for regular file
header.set(encoder.encode('0'), 156);
// Calculate checksum
let checksum = 0;
for (let i = 0; i < 512; i++) {
checksum += header[i];
}
const checksumOctal = checksum.toString(8).padStart(6, '0') + '\0 ';
header.set(encoder.encode(checksumOctal), 148);
blocks.push(header);
// Add file content, padded to 512-byte boundary
const paddedSize = Math.ceil(content.length / 512) * 512;
const paddedContent = new Uint8Array(paddedSize);
paddedContent.set(content);
blocks.push(paddedContent);
}
// Add two empty 512-byte blocks to mark end of archive
blocks.push(new Uint8Array(512));
blocks.push(new Uint8Array(512));
// Combine all blocks
const totalSize = blocks.reduce((sum, block) => sum + block.length, 0);
const tarData = new Uint8Array(totalSize);
let offset = 0;
for (const block of blocks) {
tarData.set(block, offset);
offset += block.length;
}
// Compress with gzip (using CompressionStream API)
const stream = new Blob([tarData]).stream();
const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));
const compressedBlob = await new Response(compressedStream).blob();
return compressedBlob;
}
private async uploadDeployment(
projectId: string,
environmentId: string,
serviceId: string,
tarball: Blob
): Promise<DeploymentResponse> {
const url = `${this.baseURL}/project/${projectId}/environment/${environmentId}/up?serviceId=${serviceId}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Railway expects the raw tarball bytes with Content-Type: multipart/form-data
// NOT wrapped in FormData
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'multipart/form-data',
},
body: tarball,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to upload deployment to Railway: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async ensureServiceDomain(
projectId: string,
environmentId: string,
serviceId: string
): Promise<string | null> {
try {
// First, check if a domain already exists
const domainsQuery = `
query Domains($environmentId: String!, $projectId: String!, $serviceId: String!) {
domains(environmentId: $environmentId, projectId: $projectId, serviceId: $serviceId) {
serviceDomains {
id
domain
}
customDomains {
id
domain
}
}
}
`;
const domainsResult = await this.graphqlRequest<{
domains: {
serviceDomains: Array<{ id: string; domain: string }>;
customDomains: Array<{ id: string; domain: string }>;
};
}>(domainsQuery, {
environmentId,
projectId,
serviceId,
});
// If a domain already exists, return it
if (domainsResult.domains.serviceDomains.length > 0) {
return domainsResult.domains.serviceDomains[0].domain;
}
if (domainsResult.domains.customDomains.length > 0) {
return domainsResult.domains.customDomains[0].domain;
}
// No domain exists, create a Railway-provided domain
const createDomainMutation = `
mutation ServiceDomainCreate($environmentId: String!, $serviceId: String!) {
serviceDomainCreate(input: { environmentId: $environmentId, serviceId: $serviceId }) {
id
domain
}
}
`;
const createResult = await this.graphqlRequest<{
serviceDomainCreate: {
id: string;
domain: string;
};
}>(createDomainMutation, {
environmentId,
serviceId,
});
return createResult.serviceDomainCreate.domain;
} catch (error) {
console.warn('Failed to create/get service domain:', error);
// Return null to fall back to the dashboard URL
return null;
}
}
private async waitForDeployment(deploymentId: string): Promise<void> {
const query = `
query Deployment($id: String!) {
deployment(id: $id) {
id
status
}
}
`;
const maxAttempts = 180; // 15 minutes max (5 second intervals)
let attempts = 0;
while (attempts < maxAttempts) {
attempts++;
try {
const result = await this.graphqlRequest<{
deployment: {
id: string;
status: string;
};
}>(query, { id: deploymentId });
const status = result.deployment.status;
if (status === 'SUCCESS') {
return; // Deployment successful
}
if (status === 'FAILED') {
throw new Error('Deployment failed. Check the Railway dashboard for build logs.');
}
if (status === 'CRASHED') {
throw new Error('Deployment crashed. Check the Railway dashboard for logs.');
}
// Status is BUILDING, DEPLOYING, or other in-progress state
// Wait 5 seconds before checking again
await new Promise(resolve => setTimeout(resolve, 5000));
} catch (error) {
// If it's our thrown error, re-throw it
if (error instanceof Error && (error.message.includes('failed') || error.message.includes('crashed'))) {
throw error;
}
// Otherwise, wait and retry
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
throw new Error('Deployment timed out after 15 minutes. Check the Railway dashboard for status.');
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ export class ShakespeareAdapter implements DeployAdapter {
// Apply proxy if configured
if (this.corsProxy) {
request = new Request(proxyUrl(this.corsProxy, request.url), request);
request = new Request(proxyUrl({ template: this.corsProxy, url: request.url }), request);
}
// Deploy
+1 -1
View File
@@ -68,7 +68,7 @@ export class VercelAdapter implements DeployAdapter {
}
// Apply proxy if configured
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, apiUrl) : apiUrl;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: apiUrl }) : apiUrl;
// Deploy to Vercel
const response = await fetch(targetUrl, {
+1
View File
@@ -5,3 +5,4 @@ export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
export * from './RailwayAdapter';
+28 -2
View File
@@ -49,10 +49,23 @@ export interface VercelDeployConfig {
export interface NsiteDeployConfig {
fs: JSRuntimeFS;
nostr: NPool;
nsec: string;
/** Nostr signer for the logged-in user — used to sign auth events and the manifest */
signer: NostrSigner;
gateway: string;
relayUrls: string[];
blossomServers: string[];
/** Optional site title included as a ["title", ...] tag in the manifest */
siteTitle?: string;
/** Optional site description included as a ["description", ...] tag in the manifest */
siteDescription?: string;
/** Optional source repository location included as a ["source", ...] tag in the manifest */
sourceUrl?: string;
/**
* Optional named-site identifier (the `d` tag value).
* When set → publishes kind 35128 (named site), URL = {base36pubkey}{identifier}.{gateway}
* When absent → publishes kind 15128 (root site), URL = {npub}.{gateway}
*/
siteIdentifier?: string;
}
export interface CloudflareDeployConfig {
@@ -63,6 +76,7 @@ export interface CloudflareDeployConfig {
baseDomain?: string;
projectName?: string;
corsProxy?: string;
esmUrl: string;
}
export interface DenoDeployConfig {
@@ -75,9 +89,21 @@ export interface DenoDeployConfig {
corsProxy?: string;
}
export interface RailwayDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
baseURL?: string;
workspaceId?: string;
projectId?: string;
environmentId?: string;
serviceId?: string;
projectName?: string;
corsProxy?: string;
}
export interface PresetDeployProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
name: string;
description: string;
baseURL?: string;
+10
View File
@@ -60,4 +60,14 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
organizationIdURL: 'https://dash.deno.com/orgs',
proxy: true,
},
{
id: 'railway',
type: 'railway',
name: 'Railway',
description: 'Deploy to Railway',
baseURL: 'https://backboard.railway.com',
apiKeyLabel: 'API Token',
apiKeyURL: 'https://railway.app/account/tokens',
proxy: true,
},
];
+11 -5
View File
@@ -1,15 +1,21 @@
import UriTemplate from 'uri-templates';
export interface FaviconUrlOpts {
template: string;
url: string | URL;
}
/**
* Generate a favicon URL from a template and input URL
* @param template - URL template with placeholders like {hostname}, {origin}, etc.
* @param url - The URL to extract parts from
* @param opts - Options object
* @param opts.template - URL template with placeholders like {hostname}, {origin}, etc.
* @param opts.url - The URL to extract parts from
* @returns The hydrated favicon URL
*/
export function faviconUrl(template: string, url: string | URL): string {
const u = new URL(url);
export function faviconUrl(opts: FaviconUrlOpts): string {
const u = new URL(opts.url);
return UriTemplate(template).fill({
return UriTemplate(opts.template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+2 -2
View File
@@ -1107,7 +1107,7 @@ class GitHttp implements HttpClient {
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
this.proxy = proxy;
this.fetch = fetch ?? globalThis.fetch;
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
}
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
@@ -1115,7 +1115,7 @@ class GitHttp implements HttpClient {
const url = new URL(request.url);
const target = this.proxy
? proxyUrl(this.proxy, url)
? proxyUrl({ template: this.proxy, url })
: url.href;
const init: RequestInit = {
+140
View File
@@ -1,3 +1,143 @@
export interface ResizeOptions {
/** Maximum width or height in pixels (default: 2048) */
maxDimension?: number;
/** Maximum file size in bytes (default: 5MB) */
maxFileSize?: number;
/** JPEG quality 0-1 (default: 0.92) */
quality?: number;
}
/**
* Resizes an image file if it exceeds size or dimension limits.
*
* @param file - The image file to potentially resize
* @param opts - Resize options with defaults
* @returns Promise resolving to the original or resized File
*/
export async function resizeImageIfNeeded(file: File, opts: ResizeOptions = {}): Promise<File> {
const {
maxDimension = 2048,
maxFileSize = 5 * 1024 * 1024, // 5MB
quality = 0.92,
} = opts;
// Only process image files
if (!file.type.startsWith('image/')) {
return file;
}
// Check if resize is needed based on file size
const needsResize = file.size > maxFileSize;
if (!needsResize) {
// Still need to check dimensions
const dimensions = await getImageDimensions(file);
if (dimensions.width <= maxDimension && dimensions.height <= maxDimension) {
return file;
}
}
// Resize the image
return await resizeImage(file, maxDimension, quality);
}
/**
* Gets the dimensions of an image file.
*
* @param file - The image file
* @returns Promise resolving to width and height
*/
async function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(url);
resolve({ width: img.width, height: img.height });
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load image'));
};
img.src = url;
});
}
/**
* Resizes an image to fit within maxDimension while maintaining aspect ratio.
*
* @param file - The image file to resize
* @param maxDimension - Maximum width or height
* @param quality - JPEG quality 0-1
* @returns Promise resolving to resized File
*/
async function resizeImage(file: File, maxDimension: number, quality: number): Promise<File> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(url);
// Calculate new dimensions maintaining aspect ratio
let { width, height } = img;
if (width > maxDimension || height > maxDimension) {
if (width > height) {
height = (height / width) * maxDimension;
width = maxDimension;
} else {
width = (width / height) * maxDimension;
height = maxDimension;
}
}
// Create canvas and draw resized image
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('Failed to get canvas context'));
return;
}
ctx.drawImage(img, 0, 0, width, height);
// Convert canvas to blob
canvas.toBlob(
(blob) => {
if (!blob) {
reject(new Error('Failed to create blob from canvas'));
return;
}
// Create new File from blob with original name
const resizedFile = new File([blob], file.name, {
type: file.type || 'image/jpeg',
lastModified: Date.now(),
});
resolve(resizedFile);
},
file.type || 'image/jpeg',
quality
);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load image for resizing'));
};
img.src = url;
});
}
/**
* Converts a File to a base64-encoded data URL for API consumption.
*
+6 -6
View File
@@ -9,7 +9,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
});
@@ -20,7 +20,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/example\.com\/npub1/);
});
@@ -31,7 +31,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toBe(`https://example.com/${pubkey}`);
});
@@ -42,7 +42,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toBe('https://example.com/my-repo');
});
@@ -53,7 +53,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/example\.com\/npub1[^/]+\/my-repo$/);
});
@@ -65,7 +65,7 @@ describe('ngitWebUrl', () => {
const relay = 'wss://relay.example.com/';
const nostrURI = new NostrURI({ pubkey, identifier, relay });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
// The naddr should be longer when it includes relay information
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
+14 -8
View File
@@ -2,20 +2,26 @@ import UriTemplate from 'uri-templates';
import { nip19 } from 'nostr-tools';
import { NostrURI } from './NostrURI';
export interface NgitWebUrlOpts {
template: string;
nostrURI: NostrURI;
}
/**
* Generate a Nostr Git web URL from a template and Nostr URI
* @param template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @param opts - Options object
* @param opts.template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param opts.nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @returns The hydrated web URL
*/
export function ngitWebUrl(template: string, nostrURI: NostrURI): string {
const naddr = nostrURI.toNaddr();
const npub = nip19.npubEncode(nostrURI.pubkey);
export function ngitWebUrl(opts: NgitWebUrlOpts): string {
const naddr = opts.nostrURI.toNaddr();
const npub = nip19.npubEncode(opts.nostrURI.pubkey);
return UriTemplate(template).fill({
return UriTemplate(opts.template).fill({
naddr,
npub,
pubkey: nostrURI.pubkey,
identifier: nostrURI.identifier,
pubkey: opts.nostrURI.pubkey,
identifier: opts.nostrURI.identifier,
});
}
+124
View File
@@ -0,0 +1,124 @@
/**
* Utilities for reading and writing the `.nsite/config.json` file in a project's VFS directory.
*
* NOTE: The site private key (nsec) is NEVER stored here. It lives only in
* `.git/shakespeare/deploy.json` (never committed). This file is safe to commit to git.
*/
import { z } from 'zod';
import type { JSRuntimeFS } from './JSRuntime';
/** Path of the nsite config directory relative to a project root */
const NSITE_CONFIG_DIR = '.nsite';
/** Path of the nsite config file relative to a project root */
const NSITE_CONFIG_FILE = '.nsite/config.json';
/**
* Configuration for an nsite deployment, stored in `.nsite/config.json`.
* Unknown keys in an existing file are preserved on read and write.
*/
export interface NsiteVfsConfig {
/** Nostr relay WebSocket URLs (`wss://`) */
relays: string[];
/** Blossom server HTTPS URLs (`https://`) */
servers: string[];
/**
* Named-site d-tag identifier (kind 35128).
* `null` or absent → root site (kind 15128).
* Non-empty string → named site.
*/
id?: string | null;
/** Optional site title included in the manifest event */
title?: string;
/** Optional site description included in the manifest event */
description?: string;
/**
* HTML file served as the 404 fallback for client-side routing.
* Always `/index.html` for Shakespeare SPA projects.
*/
fallback?: string;
/** Gateway hostnames that serve this nsite */
gatewayHostnames?: string[];
}
const nsiteVfsConfigSchema = z
.object({
relays: z.array(z.string()),
servers: z.array(z.string()),
id: z.string().nullable().optional(),
title: z.string().optional(),
description: z.string().optional(),
fallback: z.string().optional(),
gatewayHostnames: z.array(z.string()).optional(),
})
.passthrough(); // preserve unknown keys in existing files
/**
* Read `.nsite/config.json` from the VFS for the given project path.
*
* Returns `null` if the file does not exist or cannot be parsed.
*/
export async function readNsiteVfsConfig(
fs: JSRuntimeFS,
projectPath: string,
): Promise<NsiteVfsConfig | null> {
const filePath = `${projectPath}/${NSITE_CONFIG_FILE}`;
try {
const raw = await fs.readFile(filePath, 'utf8');
const parsed = JSON.parse(raw as string);
const validated = nsiteVfsConfigSchema.parse(parsed);
return validated as NsiteVfsConfig;
} catch (err) {
if (err instanceof Error && err.message.includes('ENOENT')) {
// File doesn't exist yet — not an error
return null;
}
console.warn('[nsiteConfig] Failed to read .nsite/config.json:', err);
return null;
}
}
/**
* Write `.nsite/config.json` to the VFS for the given project path.
*
* Merges with any existing file content so that unknown keys are not lost.
* Creates the `.nsite/` directory if it does not exist.
*/
export async function writeNsiteVfsConfig(
fs: JSRuntimeFS,
projectPath: string,
config: NsiteVfsConfig,
): Promise<void> {
const dirPath = `${projectPath}/${NSITE_CONFIG_DIR}`;
const filePath = `${projectPath}/${NSITE_CONFIG_FILE}`;
// Read existing file to preserve unknown keys
let existing: Record<string, unknown> = {};
try {
const raw = await fs.readFile(filePath, 'utf8');
existing = JSON.parse(raw as string);
} catch {
// File doesn't exist or is invalid — start fresh
}
// Merge: known fields overwrite, unknown keys are preserved
const merged: Record<string, unknown> = { ...existing, ...config };
// Remove undefined values so the JSON stays clean
for (const key of Object.keys(merged)) {
if (merged[key] === undefined) {
delete merged[key];
}
}
// Ensure .nsite/ directory exists
try {
await fs.stat(dirPath);
} catch {
await fs.mkdir(dirPath, { recursive: true });
}
await fs.writeFile(filePath, JSON.stringify(merged, null, 2), 'utf8');
}
+1 -386
View File
@@ -1,14 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import {
getPlugins,
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './plugins';
import { getPlugins } from './plugins';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
@@ -164,24 +156,6 @@ describe('plugins', () => {
fs = new MockFS();
});
describe('isValidSkillName', () => {
it('should validate alphanumeric lowercase names with hyphens', () => {
expect(isValidSkillName('test')).toBe(true);
expect(isValidSkillName('test123')).toBe(true);
expect(isValidSkillName('abc')).toBe(true);
expect(isValidSkillName('test-name')).toBe(true);
expect(isValidSkillName('test-123')).toBe(true);
expect(isValidSkillName('condition-based-waiting')).toBe(true);
});
it('should reject invalid names', () => {
expect(isValidSkillName('Test')).toBe(false);
expect(isValidSkillName('test_name')).toBe(false);
expect(isValidSkillName('test name')).toBe(false);
expect(isValidSkillName('Test-Name')).toBe(false);
});
});
describe('getPlugins', () => {
it('should return empty array when plugins directory does not exist', async () => {
const plugins = await getPlugins(fs, '/plugins');
@@ -199,363 +173,4 @@ describe('plugins', () => {
expect(plugins).not.toContain('file.txt');
});
});
describe('getPluginSkills', () => {
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should return skills from all plugins', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: myskill
description: A test skill
---
# My Skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
});
});
it('should skip skills with invalid names', async () => {
const skillPath = '/plugins/testplugin/skills/InvalidSkill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: InvalidSkill
description: Has uppercase letters
---
Content`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should skip skills missing required frontmatter', async () => {
const skillPath = '/plugins/testplugin/skills/incomplete';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: incomplete
---
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
});
describe('getAllSkills', () => {
it('should combine plugin and project skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('plugin-skill');
expect(skills.map((s) => s.name)).toContain('project-skill');
});
it('should give precedence to project skills over plugin skills with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: same-name
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: same-name
description: Project version
---
Project content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('same-name');
expect(skills[0].description).toBe('Project version');
expect(skills[0].plugin).toBe('project');
});
it('should return only plugin skills when project has no skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', '/projects/emptyproject');
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('plugin-skill');
expect(skills[0].plugin).toBe('testplugin');
});
it('should return only project skills when there are no plugins', async () => {
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/empty-plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('project-skill');
expect(skills[0].plugin).toBe('project');
});
});
describe('findSkill', () => {
it('should find a plugin skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: findme
description: Find this skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should find a project skill by name', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: projectskill
description: A project skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'projectskill');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('projectskill');
expect(skill?.plugin).toBe('project');
});
it('should prefer project skill over plugin skill with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: samename
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: samename
description: Project version
---
Project content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'samename');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('samename');
expect(skill?.description).toBe('Project version');
expect(skill?.plugin).toBe('project');
});
it('should return null when skill not found in either plugins or project', async () => {
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
const content = `---
name: myskill
description: A test skill
---
# My Skill
This is the skill content.`;
await fs.writeFile(`${skillPath}/SKILL.md`, content);
const skill = {
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
};
const readContent = await readSkillContent(fs, skill);
expect(readContent).toBe(content);
});
});
describe('getProjectSkills', () => {
it('should get skills from project skills directory', async () => {
const projectPath = '/projects/myproject';
const skillPath1 = `${projectPath}/skills/skill1`;
const skillPath2 = `${projectPath}/skills/skill2`;
await fs.mkdir(skillPath1, { recursive: true });
await fs.mkdir(skillPath2, { recursive: true });
await fs.writeFile(
`${skillPath1}/SKILL.md`,
`---
name: project-skill-1
description: First project skill
---
Content`
);
await fs.writeFile(
`${skillPath2}/SKILL.md`,
`---
name: project-skill-2
description: Second project skill
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(2);
expect(skills[0].name).toBe('project-skill-1');
expect(skills[0].plugin).toBe('project');
expect(skills[1].name).toBe('project-skill-2');
expect(skills[1].plugin).toBe('project');
});
it('should return empty array when project has no skills directory', async () => {
const skills = await getProjectSkills(fs, '/projects/emptyproject');
expect(skills).toEqual([]);
});
it('should skip skills with invalid names', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/badskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: Invalid_Skill_Name
description: This has uppercase and underscores
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toEqual([]);
});
});
});
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more