Compare commits

..
Author SHA1 Message Date
filemon 6b47557f40 add floating chat 2026-01-20 13:09:38 -03:00
143 changed files with 4657 additions and 11800 deletions

No files matched your search

-121
View File
@@ -1,121 +0,0 @@
---
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
@@ -1,198 +0,0 @@
---
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,10 +1,6 @@
# 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="****************************************"
+4 -31
View File
@@ -1,4 +1,4 @@
image: node:25
image: node:22
default:
interruptible: true
@@ -7,14 +7,9 @@ default:
stages:
- test
- deploy
- release
test:
stage: test
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
script:
- npm run typecheck
- npm run build
@@ -22,10 +17,6 @@ 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
@@ -33,24 +24,6 @@ pages:
artifacts:
paths:
- public
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'
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
+3 -11
View File
@@ -1,7 +1,3 @@
# 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.
@@ -45,8 +41,7 @@ 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
- **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
- **ReadWebpageTool**: Fetch and read web pages
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
@@ -54,9 +49,6 @@ 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
@@ -240,7 +232,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: `WebFetchTool`, `WebSearchTool`
- Web access: `ReadWebpageTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
@@ -1099,7 +1091,7 @@ const defaultConfig: AppConfig = {
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
-17
View File
@@ -1,17 +0,0 @@
# 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
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist"] },
{ ignores: ["dist", "electron/dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+714 -903
View File
File diff suppressed because it is too large. Load diff
+7 -9
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": "9.9.2",
"version": "0.0.0",
"type": "module",
"author": {
"name": "shakespeare.diy",
@@ -25,14 +25,13 @@
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^5.2.2",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@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",
@@ -83,7 +82,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^6.16.0",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -91,7 +90,7 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.71.1",
"react-hook-form": "^7.53.0",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
@@ -108,7 +107,7 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^4.3.6"
"zod": "^3.25.76"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -118,7 +117,6 @@
"@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
@@ -1,17 +0,0 @@
# 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,11 +48,6 @@ 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
@@ -0,0 +1,11 @@
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();
})
+38 -39
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,8 +28,6 @@ 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';
@@ -54,7 +52,7 @@ const defaultConfig: AppConfig = {
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
],
updatedAt: 0,
@@ -72,6 +70,11 @@ 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}",
@@ -88,8 +91,6 @@ 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
@@ -134,39 +135,37 @@ export function App() {
<UnheadProvider head={head}>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<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>
<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>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
+6 -9
View File
@@ -1,9 +1,7 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { Toaster } from "./components/ui/toaster";
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
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";
@@ -25,13 +23,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 (
<BrowserRouter>
<Toaster />
<VersionCheck />
<Router>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
@@ -54,14 +52,13 @@ 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>
</BrowserRouter>
</Router>
);
}
export default AppRouter;
-3
View File
@@ -19,14 +19,12 @@ 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);
@@ -73,7 +71,6 @@ export const AIMessageItem = memo(({
toolArgs={toolArgs}
state="completed"
result={content}
projectId={projectId}
/>
);
}
+1 -1
View File
@@ -1173,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) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
+37 -46
View File
@@ -1,7 +1,6 @@
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';
@@ -29,7 +28,6 @@ import type {
NsiteProvider,
CloudflareProvider,
DenoDeployProvider,
RailwayProvider,
} from '@/contexts/DeploySettingsContext';
// Type for provider without the 'id' field (will be generated)
@@ -39,8 +37,7 @@ type DeployProviderInput =
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
| Omit<CloudflareProvider, 'id'>
| Omit<DenoDeployProvider, 'id'>
| Omit<RailwayProvider, 'id'>;
| Omit<DenoDeployProvider, 'id'>;
interface AddCustomProviderDialogProps {
open: boolean;
@@ -54,7 +51,7 @@ export function AddCustomProviderDialog({
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
@@ -64,8 +61,8 @@ export function AddCustomProviderDialog({
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
const [customBlossomServers, setCustomBlossomServers] = useState<string[]>([]);
const [customRelayUrls, setCustomRelayUrls] = useState('');
const [customBlossomServers, setCustomBlossomServers] = useState('');
const handleAdd = () => {
if (!customProviderType || !customName.trim()) return;
@@ -85,8 +82,12 @@ export function AddCustomProviderDialog({
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'nsite.lol',
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
relayUrls: customRelayUrls.trim()
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
: ['wss://relay.nostr.band'],
blossomServers: customBlossomServers.trim()
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
: ['https://blossom.primal.net/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
@@ -128,15 +129,6 @@ 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
}
@@ -154,8 +146,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
setCustomRelayUrls('');
setCustomBlossomServers('');
onOpenChange(false);
};
@@ -164,8 +156,7 @@ export function AddCustomProviderDialog({
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
(customProviderType !== 'railway' || true)));
(customProviderType !== 'deno' || customOrganizationId.trim())));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -184,7 +175,7 @@ export function AddCustomProviderDialog({
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
@@ -195,8 +186,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
setCustomRelayUrls('');
setCustomBlossomServers('');
}}
>
<SelectTrigger>
@@ -209,7 +200,6 @@ 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>
@@ -246,7 +236,7 @@ export function AddCustomProviderDialog({
) : customProviderType === 'nsite' ? (
<>
<p className="text-sm text-muted-foreground">
Deploy to Nostr as a static website. Uses a kind 15128 site manifest event and Blossom file storage.
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
</p>
<div className="grid gap-2">
<Label htmlFor="custom-gateway">Gateway</Label>
@@ -257,20 +247,24 @@ export function AddCustomProviderDialog({
onChange={(e) => setCustomGateway(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"
/>
<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>
</>
) : (
<>
@@ -305,8 +299,7 @@ export function AddCustomProviderDialog({
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
customProviderType === 'railway' ? 'API Token' :
'Access Token'} <span className="text-destructive">*</span>
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
@@ -326,9 +319,7 @@ export function AddCustomProviderDialog({
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: customProviderType === 'railway'
? 'https://backboard.railway.com'
: 'https://api.cloudflare.com/client/v4'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
-567
View File
@@ -1,567 +0,0 @@
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,8 +60,6 @@ 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);
-73
View File
@@ -1,73 +0,0 @@
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
@@ -1,29 +0,0 @@
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,7 +327,6 @@ 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" />
+3 -13
View File
@@ -14,7 +14,6 @@ import {
ChevronDown,
Trash2,
Star,
AppWindow,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
@@ -28,7 +27,7 @@ interface ProjectTitleMenuProps {
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
onApp: () => void;
isAILoading: boolean;
isAnyLoading: boolean;
className?: string;
}
@@ -41,7 +40,7 @@ export function ProjectTitleMenu({
onDuplicate,
onDelete,
onProjectDetails,
onApp,
isAILoading,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
@@ -101,15 +100,6 @@ 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}
@@ -121,7 +111,7 @@ export function ProjectTitleMenu({
<DropdownMenuItem
onClick={onNewChat}
disabled={isAnyLoading}
disabled={isAILoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
+29 -23
View File
@@ -17,7 +17,6 @@ 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;
@@ -139,22 +138,34 @@ export function ProviderConfigDialog({
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
</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
/>
<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>
</>
) : (
<>
@@ -201,8 +212,6 @@ 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 });
}
}}
/>
@@ -218,8 +227,7 @@ 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' :
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
'Base URL'
'Base URL'
}
value={localProvider.baseURL || ''}
onChange={(e) => {
@@ -231,8 +239,6 @@ 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,8 +45,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -89,8 +87,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -134,8 +130,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -182,8 +176,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
+31 -164
View File
@@ -1,20 +1,13 @@
import { useState, useCallback, memo, useRef, useEffect } from 'react';
import { useState, useCallback, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { 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;
@@ -36,7 +29,6 @@ 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({
@@ -60,15 +52,10 @@ 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]);
@@ -91,110 +78,16 @@ 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, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
}, [handleSend]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
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]);
setInput(e.target.value);
}, []);
return (
<div className="border-t p-4">
@@ -206,61 +99,35 @@ export const ChatInput = memo(function ChatInput({
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={handleDrop}
onDrop={onDrop}
>
<div className="relative">
<Textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={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>
: 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';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
+23 -118
View File
@@ -18,11 +18,9 @@ import { useMCPTools } from '@/hooks/useMCPTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
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 { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
@@ -35,21 +33,13 @@ 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';
@@ -57,13 +47,11 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { AIMessage } from '@/lib/SessionManager';
import { getAllSkills } from '@/lib/skills';
// Clean interfaces now handled by proper hooks
@@ -103,15 +91,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const queryClient = useQueryClient();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const scrolledProjectsRef = useRef(new Set<string>());
const shouldScrollToBottomRef = useRef(false);
const [scrolledProjects] = useState(() => new Set<string>());
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
@@ -182,34 +167,16 @@ 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),
@@ -221,23 +188,9 @@ 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, 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),
),
skill: new SkillTool(fs, pluginsPath, cwd),
};
// Add generate_image tool if imageModel is configured
@@ -289,7 +242,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, config.relayMetadata, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
@@ -536,46 +489,30 @@ 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;
// 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
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
}
}, [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 && !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);
});
});
if (projectId && !scrolledProjects.has(projectId)) {
// Small delay to ensure messages have loaded
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
}, 100);
return () => clearTimeout(timer);
}
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
}, [projectId, scrolledProjects, scrollToBottom]);
// Drag and drop handlers
const handleDragEnter = useCallback((e: React.DragEvent) => {
@@ -640,9 +577,6 @@ 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]);
@@ -665,23 +599,6 @@ 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: () => {
@@ -701,7 +618,6 @@ 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 */}
@@ -717,7 +633,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="calling"
projectId={projectId}
/>
) : (
<>
@@ -754,7 +669,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="waiting"
projectId={projectId}
/>
);
}
@@ -886,7 +800,6 @@ 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}
/>
);
})}
@@ -959,7 +872,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
slashCommands={slashCommands}
/>
{/* Onboarding Dialog */}
@@ -967,13 +879,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
{/* Tools Dialog */}
<ToolsDialog
open={showToolsDialog}
onOpenChange={setShowToolsDialog}
tools={tools}
/>
</div>
);
});
@@ -0,0 +1,246 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { MessageSquare, Minus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { cn } from '@/lib/utils';
interface FloatingChatWidgetProps {
projectId: string;
isMinimized: boolean;
onToggleMinimize: () => void;
onClose: () => void;
onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
}
interface ChatSize {
width: number;
height: number;
}
const MIN_WIDTH = 320;
const MIN_HEIGHT = 380;
const MAX_WIDTH = 720;
const MAX_HEIGHT = 900;
const DEFAULT_WIDTH = 420;
const DEFAULT_HEIGHT = 520;
export function FloatingChatWidget({
projectId,
isMinimized,
onToggleMinimize,
onClose,
onNewChat,
onFirstInteraction,
onLoadingChange,
isLoading,
isBuildLoading,
consoleError,
onDismissConsoleError,
}: FloatingChatWidgetProps) {
const chatPaneRef = useRef<ChatPaneRef>(null);
const [size, setSize] = useLocalStorage<ChatSize>('shk:floatingChatSize', {
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
});
const [isResizing, setIsResizing] = useState(false);
const resizeStartRef = useRef<{ x: number; y: number; width: number; height: number } | null>(null);
// Handle keyboard escape to minimize
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !isMinimized) {
onToggleMinimize();
}
};
if (!isMinimized) {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}
}, [isMinimized, onToggleMinimize]);
// Resize handlers
const startResize = useCallback((e: React.PointerEvent, direction: 'right' | 'bottom' | 'top' | 'bottomLeft' | 'topRight') => {
e.preventDefault();
e.stopPropagation();
const target = e.currentTarget as HTMLElement;
target.setPointerCapture(e.pointerId);
setIsResizing(true);
document.body.style.userSelect = 'none';
resizeStartRef.current = {
x: e.clientX,
y: e.clientY,
width: size.width,
height: size.height,
};
const handlePointerMove = (moveEvent: PointerEvent) => {
if (!resizeStartRef.current) return;
const maxW = Math.min(MAX_WIDTH, window.innerWidth - 16);
const maxH = Math.min(MAX_HEIGHT, window.innerHeight - 16);
let newWidth = resizeStartRef.current.width;
let newHeight = resizeStartRef.current.height;
// Handle horizontal resizing (left edge for bottom-right anchored widget)
if (direction === 'right' || direction === 'bottomLeft' || direction === 'topRight') {
const deltaX = resizeStartRef.current.x - moveEvent.clientX;
newWidth = Math.max(MIN_WIDTH, Math.min(maxW, resizeStartRef.current.width + deltaX));
}
// Handle vertical resizing from bottom (grows downward)
if (direction === 'bottom' || direction === 'bottomLeft') {
const deltaY = resizeStartRef.current.y - moveEvent.clientY;
newHeight = Math.max(MIN_HEIGHT, Math.min(maxH, resizeStartRef.current.height + deltaY));
}
// Handle vertical resizing from top (grows upward, widget anchored at bottom)
if (direction === 'top' || direction === 'topRight') {
const deltaY = moveEvent.clientY - resizeStartRef.current.y;
newHeight = Math.max(MIN_HEIGHT, Math.min(maxH, resizeStartRef.current.height - deltaY));
}
setSize({ width: newWidth, height: newHeight });
};
const handlePointerUp = () => {
setIsResizing(false);
document.body.style.userSelect = '';
resizeStartRef.current = null;
window.removeEventListener('pointermove', handlePointerMove);
window.removeEventListener('pointerup', handlePointerUp);
};
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp);
}, [size, setSize]);
if (isMinimized) {
return (
<div className="fixed right-4 bottom-4 z-50">
<Button
onClick={onToggleMinimize}
size="icon"
className="h-14 w-14 rounded-full shadow-lg hover:shadow-xl transition-all duration-200"
aria-label="Open chat"
>
<MessageSquare className="h-6 w-6" />
</Button>
</div>
);
}
return (
<div
className={cn(
"fixed right-4 bottom-4 z-50",
"rounded-lg border shadow-2xl bg-background",
"flex flex-col overflow-hidden",
isResizing && "select-none"
)}
style={{
width: `${size.width}px`,
height: `${size.height}px`,
maxWidth: '92vw',
maxHeight: '70vh',
}}
>
{/* Header - Styled like ProjectSidebar */}
<div className="h-12 px-4 border-b flex-shrink-0 flex items-center justify-between bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur">
<div className="flex items-center gap-2">
<ShakespeareLogo className="w-5 h-5" />
<h2 className="text-base font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h2>
</div>
<div className="flex items-center gap-1">
<Button
onClick={onToggleMinimize}
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label="Minimize chat"
>
<Minus className="h-4 w-4" />
</Button>
<Button
onClick={onClose}
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label="Close floating chat"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Chat Body */}
<div className="flex-1 min-h-0 overflow-hidden">
<div className="h-full">
<ChatPane
ref={chatPaneRef}
projectId={projectId}
onNewChat={onNewChat}
onFirstInteraction={onFirstInteraction}
onLoadingChange={onLoadingChange}
isLoading={isLoading}
isBuildLoading={isBuildLoading}
consoleError={consoleError}
onDismissConsoleError={onDismissConsoleError}
/>
</div>
</div>
{/* Resize Handles */}
{/* Left edge (appears as "right" from widget perspective, but it's on the left side) */}
<div
className="absolute top-0 left-0 h-full w-2 cursor-ew-resize hover:bg-primary/10 active:bg-primary/20 transition-colors"
onPointerDown={(e) => startResize(e, 'right')}
style={{ touchAction: 'none' }}
/>
{/* Top edge */}
<div
className="absolute top-0 left-0 w-full h-2 cursor-ns-resize hover:bg-primary/10 active:bg-primary/20 transition-colors"
onPointerDown={(e) => startResize(e, 'top')}
style={{ touchAction: 'none' }}
/>
{/* Bottom edge */}
<div
className="absolute bottom-0 left-0 w-full h-2 cursor-ns-resize hover:bg-primary/10 active:bg-primary/20 transition-colors"
onPointerDown={(e) => startResize(e, 'bottom')}
style={{ touchAction: 'none' }}
/>
{/* Bottom-left corner */}
<div
className="absolute bottom-0 left-0 w-4 h-4 cursor-nesw-resize hover:bg-primary/20 active:bg-primary/30 transition-colors"
onPointerDown={(e) => startResize(e, 'bottomLeft')}
style={{ touchAction: 'none' }}
/>
{/* Top-right corner */}
<div
className="absolute top-0 right-0 w-4 h-4 cursor-nesw-resize hover:bg-primary/20 active:bg-primary/30 transition-colors"
onPointerDown={(e) => startResize(e, 'topRight')}
style={{ touchAction: 'none' }}
/>
</div>
);
}
+146 -282
View File
@@ -10,14 +10,17 @@ 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, RefreshCw } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BranchSwitcher } from '@/components/BranchSwitcher';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { type DeviceMode } from '@/components/ui/device-toggle';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -74,18 +77,14 @@ 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();
@@ -178,7 +177,19 @@ 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) {
@@ -429,7 +440,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setBuildError(null);
// Reset navigation history and state
setCurrentPath('/');
@@ -454,13 +464,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframe();
refreshIframeLegacy();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframe]);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -490,48 +500,106 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
};
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedAll, setCopiedAll] = useState(false);
const [copiedBuildError, setCopiedBuildError] = useState(false);
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const messages = isLogsOpen ? getConsoleMessages() : [];
const messages = isOpen ? 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 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 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">
@@ -588,7 +656,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title={t('buildButtonTooltip')}
title="Build project"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -603,249 +671,45 @@ 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>
)}
<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>
<ConsoleDropdown />
</div>
</div>
{/* Content area */}
<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"
<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="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>
)}
<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>
</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>
)}
</div>
{/* Build loading overlay */}
@@ -1,59 +0,0 @@
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
@@ -1,144 +0,0 @@
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();
});
});
});
+66 -339
View File
@@ -26,16 +26,12 @@ 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;
@@ -49,7 +45,6 @@ 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
@@ -82,95 +77,21 @@ 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>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
function getToolInfo(toolName: string, args: Record<string, unknown>): 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 rawPath = args.path ? String(args.path) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const path = args.path ? String(args.path) : 'File';
const hasLineRange = args.start_line || args.end_line;
const lineInfo = hasLineRange
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
@@ -183,27 +104,21 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
};
}
case 'text_editor_write': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
case 'text_editor_write':
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',
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',
};
}
case 'text_editor_str_replace': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
case 'text_editor_str_replace':
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',
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',
};
}
case 'npm_add_package': {
const name = args.name ? String(args.name) : 'Package';
@@ -219,25 +134,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
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':
@@ -245,55 +160,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
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 ? `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',
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',
};
case 'nostr_read_kind':
return {
icon: Hash,
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',
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',
};
case 'nostr_read_tag':
return {
icon: 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',
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',
};
case 'nostr_read_protocol':
return {
icon: Network,
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',
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',
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Viewed NIPs index',
callingTitle: 'Viewing NIPs index',
errorTitle: 'Failed to view NIPs index',
title: 'Read NIPs Index',
callingTitle: 'Reading NIPs Index',
errorTitle: 'Failed to Read 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': {
@@ -302,136 +217,58 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
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: 'Viewed console',
callingTitle: 'Viewing console',
errorTitle: 'Failed to view console',
title: 'Read Console',
callingTitle: 'Reading Console',
errorTitle: 'Failed to Read 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 {
@@ -462,13 +299,12 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
/**
* Unified component for displaying tool calls in all states
*/
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
export function ToolCallDisplay({ toolName, toolArgs, state, result }: 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, projectId, projectsPath, result);
const toolInfo = getToolInfo(toolName, toolArgs);
const IconComponent = toolInfo.icon;
// Check if this is an error result
@@ -506,26 +342,19 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
);
}
// 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);
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{content}
{toolArgs.file_text}
</div>
</div>
);
}
// 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');
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');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
@@ -558,56 +387,6 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
);
}
// 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 (
@@ -617,58 +396,6 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
);
}
// 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
@@ -1,147 +0,0 @@
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
@@ -1,70 +0,0 @@
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;
}
-3
View File
@@ -4,7 +4,6 @@ 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;
@@ -15,7 +14,6 @@ interface DeployButtonProps {
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
const [open, setOpen] = useState(false);
const { t } = useTranslation();
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -26,7 +24,6 @@ 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>
+17 -319
View File
@@ -13,9 +13,6 @@ 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';
@@ -26,7 +23,6 @@ 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';
@@ -35,10 +31,6 @@ 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
@@ -50,23 +42,6 @@ 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
*/
@@ -105,9 +80,7 @@ interface ShakespeareFormData {
}
interface NsiteFormData {
siteTitle: string;
siteDescription: string;
dTag: string;
nsec: string;
}
interface NetlifyFormData {
@@ -128,14 +101,6 @@ 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();
@@ -145,8 +110,6 @@ 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);
@@ -154,46 +117,12 @@ 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>({
siteTitle: '',
siteDescription: '',
dTag: '',
nsec: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
@@ -209,13 +138,6 @@ 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(() => {
@@ -261,25 +183,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider;
if (!user) {
throw new Error('You must be logged in to deploy to nsite.');
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
}
const sourceUrl = await resolveNsiteSourceUrl(
await git.getRemoteURL(projectPath, 'origin')
);
adapter = new NsiteAdapter({
fs,
nostr,
signer: user.signer,
nsec: nsiteForm.nsec,
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;
@@ -328,7 +242,6 @@ 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;
@@ -348,23 +261,6 @@ 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');
}
@@ -388,28 +284,9 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
type: 'nsite',
url: result.url,
data: {
siteTitle: nsiteForm.siteTitle || undefined,
siteDescription: nsiteForm.siteDescription || undefined,
dTag: nsiteForm.dTag || undefined,
nsec: nsiteForm.nsec,
},
});
// 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',
@@ -443,67 +320,9 @@ 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 {
@@ -517,14 +336,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
setNsiteForm({ nsec: '' });
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();
};
@@ -536,17 +352,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setIsShakespeareFormValid(isValid);
}, []);
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 handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
@@ -565,16 +372,6 @@ 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;
@@ -595,72 +392,15 @@ 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 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;
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
return (
<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>
<NsiteDeployForm
gateway={selectedProvider.gateway}
savedNsec={savedNsec}
onNsecChange={handleNsiteNsecChange}
/>
);
}
@@ -737,30 +477,6 @@ 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;
};
@@ -920,22 +636,6 @@ 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" />
@@ -950,12 +650,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !user) ||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
}
className="w-full"
>
+79 -75
View File
@@ -1,103 +1,107 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle } from 'lucide-react';
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { nip19 } from 'nostr-tools';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { PasswordInput } from '@/components/ui/password-input';
import { RefreshCw } from 'lucide-react';
interface NsiteDeployFormProps {
/** 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) */
gateway: string;
savedNsec?: string;
onSiteTitleChange: (title: string) => void;
onSiteDescriptionChange: (description: string) => void;
onNsecChange: (nsec: string) => void;
}
export function NsiteDeployForm({
projectName,
savedSiteTitle,
savedSiteDescription,
gateway,
savedNsec,
onSiteTitleChange,
onSiteDescriptionChange,
onNsecChange,
}: NsiteDeployFormProps) {
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]);
const [nsec, setNsec] = useState(savedNsec || '');
const [npub, setNpub] = useState('');
const initialized = useRef(false);
// Initialize nsec on mount
useEffect(() => {
stableSyncToParent();
}, [stableSyncToParent]);
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]);
const handleSiteTitleChange = (value: string) => {
setSiteTitle(value);
onSiteTitleChange(value);
// 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 handleSiteDescriptionChange = (value: string) => {
setSiteDescription(value);
onSiteDescriptionChange(value);
const handleGenerateNew = () => {
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
};
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
return (
<div className="space-y-4">
{/* 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 htmlFor="nsite-title">Site Title</Label>
<Input
id="nsite-title"
value={siteTitle}
onChange={(e) => handleSiteTitleChange(e.target.value)}
placeholder="My Nostr Site"
/>
<Label>Site URL</Label>
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
{fullDomain}
</p>
<p className="text-xs text-muted-foreground">
Shown by nsite gateways and directories. Included as a title tag in the manifest.
Each site has a unique Nostr keypair
</p>
</div>
{/* Site description */}
<div className="space-y-2">
<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}
/>
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
<div className="flex gap-2">
<PasswordInput
id="nsite-nsec"
value={nsec}
onChange={(e) => handleNsecChange(e.target.value)}
placeholder="nsec1..."
className="flex-1"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleGenerateNew}
title="Generate new key"
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Included as a description tag in the manifest.
Keep this private key secure. It's used to sign site metadata.
</p>
</div>
</div>
-382
View File
@@ -1,382 +0,0 @@
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>
);
}
+11 -22
View File
@@ -7,7 +7,6 @@ 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;
@@ -19,7 +18,6 @@ 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();
@@ -54,28 +52,19 @@ 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 = isProjectAltered &&
!gitStatus?.remotes.find(r => r.name === 'origin');
const needsRemote = !isGitStatusLoading && gitStatus &&
!gitStatus.remotes.find(r => r.name === 'origin') &&
gitStatus.totalCommits > 1;
// Show warning popover when purple indicator is visible (only if not dismissed)
useEffect(() => {
if (needsRemote && !warningDismissed.current) {
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
setShowWarningPopover(true);
} else {
setShowWarningPopover(false);
}
}, [needsRemote]);
}, [gitStatus?.totalCommits, needsRemote]);
// Handle button click - dismiss warning popover permanently
const handleButtonClick = () => {
@@ -105,18 +94,19 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
if (isGitStatusLoading || !gitStatus) return null;
const hasOrigin = !!gitStatus.remotes.find(r => r.name === 'origin');
const originRemote = gitStatus.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
const { remoteBranchExists, ahead, behind } = gitStatus;
const { remoteBranchExists, ahead, behind, totalCommits } = gitStatus;
// Yellow indicator: unsynced changes (ahead or behind remote) - third priority
const hasUnsyncedChanges = hasOrigin && remoteBranchExists && (ahead > 0 || behind > 0);
const hasUnsyncedChanges = hasRemote && remoteBranchExists && (ahead > 0 || behind > 0);
if (hasUnsyncedChanges) {
return <IndicatorDot color="yellow" />;
}
// Purple indicator: project altered but no origin remote configured - lowest priority
const needsRemote = isProjectAltered && !hasOrigin;
// Purple indicator: no remote configured, but has commits - lowest priority
const needsRemote = !hasRemote && totalCommits > 1;
if (needsRemote) {
return <IndicatorDot color="primary" />;
}
@@ -139,7 +129,6 @@ 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,6 +2,7 @@ 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';
@@ -19,9 +20,6 @@ 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 {
@@ -43,8 +41,7 @@ export function ConfigureRepoStep({
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
const [isPushing, setIsPushing] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
const [error, setError] = useState<string | null>(null);
const { user } = useCurrentUser();
const { git } = useGit();
@@ -58,7 +55,6 @@ 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(() => {
@@ -78,10 +74,9 @@ export function ConfigureRepoStep({
setIsRepoNameManuallyEdited(true);
};
// 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;
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
try {
if (selectedProvider.id === 'nostr') {
@@ -171,15 +166,6 @@ 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,
@@ -187,7 +173,6 @@ export function ConfigureRepoStep({
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags,
webUrls,
});
// Publish the event
@@ -211,14 +196,12 @@ 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
@@ -233,14 +216,12 @@ 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,
});
}
@@ -257,45 +238,8 @@ export function ConfigureRepoStep({
// Show success state
onSuccess();
} catch (err) {
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);
const message = err instanceof Error ? err.message : 'Failed to push';
setError(message);
} finally {
setIsPushing(false);
}
@@ -399,13 +343,9 @@ export function ConfigureRepoStep({
</div>
{error && (
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
@@ -420,13 +360,6 @@ export function ConfigureRepoStep({
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
@@ -453,13 +386,9 @@ export function ConfigureRepoStep({
</div>
{error && (
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
@@ -478,13 +407,6 @@ export function ConfigureRepoStep({
)}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
+10 -44
View File
@@ -8,16 +8,14 @@ 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, context = 'sync' }: SyncStepErrorProps) {
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
const renderForcePullButton = () => (
<Button
variant="outline"
@@ -106,23 +104,17 @@ 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">
{message}
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{/* Only show Pull button in sync context (not during initial configure) */}
{context === 'sync' && onPull && renderPullButton()}
{renderPullButton()}
{renderForcePushButton()}
</div>
</div>
@@ -134,43 +126,17 @@ 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}`;
// Check if remoteUrl is a Nostr URL
if (remoteUrl?.protocol === 'nostr:') {
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 && remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
// Handle standard HTTP errors based on status code
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
switch (error.data.statusCode) {
case 401:
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>.</>;
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
break;
case 403:
message = 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.</>;
}
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
break;
}
}
-4
View File
@@ -68,10 +68,6 @@ 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 {
+1 -8
View File
@@ -50,14 +50,7 @@ export interface DenoDeployProvider extends BaseDeployProvider {
proxy?: boolean;
}
export interface RailwayProvider extends BaseDeployProvider {
type: 'railway';
apiKey: string;
baseURL?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface DeploySettings {
providers: DeployProvider[];
+5 -11
View File
@@ -46,10 +46,8 @@ export function useAIChat({
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
const initSession = useCallback(async (showLoading = true) => {
if (showLoading) {
setIsLoadingHistory(true);
}
const initSession = useCallback(async () => {
setIsLoadingHistory(true);
try {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
@@ -61,9 +59,7 @@ export function useAIChat({
setLastInputTokens(session.lastInputTokens || 0);
setLastFinishReason(session.lastFinishReason ?? null);
} finally {
if (showLoading) {
setIsLoadingHistory(false);
}
setIsLoadingHistory(false);
}
}, [sessionManager, projectId, tools, customTools, maxSteps]);
@@ -133,8 +129,7 @@ export function useAIChat({
providerModel: string
) => {
try {
// Ensure session is loaded (without showing loading state)
await initSession(false);
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
@@ -147,8 +142,7 @@ export function useAIChat({
const startGeneration = useCallback(async (providerModel: string) => {
try {
// Ensure session is loaded (without showing loading state)
await initSession(false);
await initSession();
await sessionManager.startGeneration(projectId, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
-104
View File
@@ -1,104 +0,0 @@
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,8 +80,6 @@ describe('useGenerateProjectInfo', () => {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
mockUseAppContext.mockReturnValue({
config,
@@ -244,8 +242,6 @@ describe('useGenerateProjectInfo', () => {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
mockUseAppContext.mockReturnValue({
config,
-2
View File
@@ -54,8 +54,6 @@ function createWrapper(corsProxy: string) {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
return createElement(
-16
View File
@@ -39,7 +39,6 @@ interface GitStatus {
ahead: number;
behind: number;
remoteBranchExists: boolean;
clonedAtOid: string | null;
}
export function useGitStatus(projectId: string | null) {
@@ -62,7 +61,6 @@ export function useGitStatus(projectId: string | null) {
ahead: 0,
behind: 0,
remoteBranchExists: false,
clonedAtOid: null,
};
}
@@ -85,7 +83,6 @@ export function useGitStatus(projectId: string | null) {
ahead: 0,
behind: 0,
remoteBranchExists: false,
clonedAtOid: null,
};
}
@@ -171,17 +168,6 @@ 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,
@@ -288,7 +274,6 @@ export function useGitStatus(projectId: string | null) {
ahead,
behind,
remoteBranchExists,
clonedAtOid,
};
} catch (error) {
console.error('Error checking git status:', error);
@@ -304,7 +289,6 @@ export function useGitStatus(projectId: string | null) {
ahead: 0,
behind: 0,
remoteBranchExists: false,
clonedAtOid: null,
};
}
},
+2 -4
View File
@@ -5,14 +5,12 @@ import { useCurrentUser } from "./useCurrentUser";
import type { NostrEvent } from "@nostrify/nostrify";
type NostrEventInput = Pick<NostrEvent, 'kind' | 'content'> & Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
export function useNostrPublish(): UseMutationResult<NostrEvent, Error, NostrEventInput> {
export function useNostrPublish(): UseMutationResult<NostrEvent> {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (t: NostrEventInput) => {
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
if (user) {
const tags = t.tags ?? [];
+1 -2
View File
@@ -1,8 +1,7 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPluginSkills } from '@/lib/skills';
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { useGit } from './useGit';
import { join } from 'path-browserify';
+1 -21
View File
@@ -15,14 +15,7 @@ const nsiteProjectConfigSchema = z.object({
type: z.literal('nsite'),
url: z.string(),
data: z.object({
/** 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(),
nsec: z.string(),
}),
});
@@ -59,17 +52,6 @@ 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,
@@ -77,7 +59,6 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
vercelProjectConfigSchema,
cloudflareProjectConfigSchema,
denoDeployProjectConfigSchema,
railwayProjectConfigSchema,
]);
const projectDeploySettingsSchema = z.object({
@@ -91,7 +72,6 @@ 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,7 +15,6 @@ export function useUploadFile() {
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
'https://blossom.ditto.pub/',
],
signer: user.signer,
});
+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.ditto.pub'],
relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band'],
comment
});
-43
View File
@@ -393,47 +393,4 @@ 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
@@ -0,0 +1,371 @@
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);
}
}
});
});
+27 -41
View File
@@ -57,52 +57,50 @@ 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): Promise<string> {
async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise<string> {
// Generate a safe directory name from the template URL
const templateName = this.getTemplateNameFromUrl(templateUrl);
const templatePath = `${this.templatesDir}/${templateName}`;
const templateExists = await this.fs.stat(templatePath).then(() => true, () => false);
try {
// Check if template already exists
await this.fs.stat(templatePath);
if (templateExists) {
// Template exists, try to update it with force pull
try {
await this.forcePullTemplate(templatePath);
return templatePath;
} catch (updateError) {
// 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);
// 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
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;
}
@@ -226,7 +224,7 @@ export class ProjectsManager {
}
}
async createProject(name: string, templateUrl: string, customId?: string, templateMetadata?: { name: string; description: string }): Promise<Project> {
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, 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
@@ -237,7 +235,7 @@ export class ProjectsManager {
const projectPath = `${this.dir}/${id}`;
// Ensure template is cached and up-to-date
const templatePath = await this.updateTemplate(templateUrl);
const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError);
// Create project directory
await this.fs.mkdir(projectPath, { recursive: true });
@@ -524,18 +522,6 @@ 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,8 +58,6 @@ const testConfig: AppConfig = {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
describe('SessionManager', () => {
+2 -31
View File
@@ -319,31 +319,6 @@ 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 => {
@@ -403,10 +378,6 @@ 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);
@@ -690,7 +661,7 @@ export class SessionManager {
console.error('AI generation error:', error);
// Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || (error instanceof Error && error.name === 'AbortError')) {
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
return; // User cancelled
}
@@ -787,7 +758,7 @@ export class SessionManager {
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.`;
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse grep to search it for specific content, or text_editor_view with start_line/end_line to view specific sections.`;
}
const toolMessage: AIMessage = {
+2 -2
View File
@@ -18,6 +18,8 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
dangerouslyAllowBrowser: true,
fetch: async (input, init) => {
let request = new Request(input, init);
// OpenSecret auth
// https://docs.opensecret.cloud/docs/maple-ai/
if (provider.openSecret) {
@@ -25,8 +27,6 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
return createCustomFetch({ apiKey: provider.apiKey, apiUrl: provider.openSecret })(input, init);
}
let request = new Request(input, init);
// Add OpenRouter headers
// https://openrouter.ai/docs/app-attribution
if (provider.id === 'openrouter') {
-117
View File
@@ -1,117 +0,0 @@
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,
};
}
+1 -6
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: string = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
const next = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
if (next === current) break;
current = next;
const candidate = `${current}/node_modules/${name}`;
@@ -226,11 +226,6 @@ 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}` }],
+6 -1
View File
@@ -99,6 +99,11 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
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}`);
}
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
@@ -169,7 +174,7 @@ async function tryFileVariants(
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| 'index.js';
+1 -1
View File
@@ -130,7 +130,7 @@ describe('buildProject', () => {
});
vi.mocked(mockFS.readdir)
.mockImplementation(async (path: string, _options?: { withFileTypes?: boolean }) => {
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
if (path === '/test/project/public') {
return [
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
+57 -125
View File
@@ -10,7 +10,6 @@ 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;
@@ -21,115 +20,6 @@ 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>> {
@@ -141,8 +31,58 @@ async function bundle(
"utf8",
);
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(fs, projectPath);
// 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}`);
const doc = domParser.parseFromString(indexHtmlText, "text/html");
const entryPoints: string[] = [];
@@ -188,7 +128,11 @@ async function bundle(
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
plugins: [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig, packageJson }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
define: {
"import.meta.env": JSON.stringify({}),
},
@@ -287,18 +231,6 @@ 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();
+4 -7
View File
@@ -1,7 +1,7 @@
import type OpenAI from 'openai';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { saveFileToTmp } from './fileUtils';
import { fileToUrl, resizeImageIfNeeded } from './imageUtils';
import { fileToUrl } from './imageUtils';
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
@@ -41,11 +41,8 @@ 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, processedFile, tmpPath);
const savedPath = await saveFileToTmp(fs, file, tmpPath);
// Always add text part with VFS path
const textPart: ContentPart = {
@@ -54,10 +51,10 @@ export async function buildMessageContent(
};
// For all image types, also add as image_url for UI display with base64 encoding
const isImage = processedFile.type.startsWith('image/');
const isImage = file.type.startsWith('image/');
if (isImage) {
try {
const imageUrl = await fileToUrl(processedFile);
const imageUrl = await fileToUrl(file);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
-81
View File
@@ -1,81 +0,0 @@
/** 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
@@ -80,7 +80,7 @@ export class MkdirCommand implements ShellCommand {
// Create the directory
await this.fs.mkdir(absolutePath);
} else {
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`);
}
}
}
+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 instanceof Error ? error.message : String(error)}`);
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
}
}
+2 -9
View File
@@ -130,12 +130,6 @@ 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,
@@ -143,7 +137,6 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
railwayProviderSchema,
]);
const deploySettingsSchema = z.object({
@@ -208,7 +201,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
};
} catch (error) {
if (error instanceof z.ZodError) {
console.error('AI settings parsing error:', error.issues);
console.error('AI settings parsing error:', error.errors);
}
return defaultSettings;
}
@@ -329,7 +322,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.issues);
console.error('Deploy settings parsing error:', error.errors);
}
return defaultSettings;
}
+18 -145
View File
@@ -1,10 +1,6 @@
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 };
@@ -28,16 +24,6 @@ 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;
@@ -63,7 +49,6 @@ export class CloudflareAdapter implements DeployAdapter {
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
private esmUrl: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
@@ -73,15 +58,11 @@ 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 {
@@ -134,7 +115,7 @@ export class CloudflareAdapter implements DeployAdapter {
}
// Step 4: Deploy the worker with assets
const deployment = await this.deployWorker(scriptName, completionJwt, projectPath, wranglerConfig);
const deployment = await this.deployWorker(scriptName, completionJwt);
// Step 5: Enable the workers.dev subdomain for this script
await this.enableWorkersDevSubdomain(scriptName);
@@ -268,105 +249,37 @@ export class CloudflareAdapter implements DeployAdapter {
return data.result || {};
}
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
const esbuild = await getEsbuild();
// 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> {
private async deployWorker(scriptName: string, assetsJwt: string): 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
}
// 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 });
}
};
`;
const formData = new FormData();
// Add the worker script as the main module
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
formData.append(mainModuleName, scriptBlob, mainModuleName);
formData.append('worker.js', scriptBlob, 'worker.js');
// Add metadata with assets configuration
const metadata = {
main_module: mainModuleName,
compatibility_date: wranglerConfig?.compatibility_date || new Date().toISOString().split('T')[0],
main_module: 'worker.js',
compatibility_date: new Date().toISOString().split('T')[0],
assets: {
jwt: assetsJwt,
config: {
html_handling: wranglerConfig?.assets?.html_handling || 'auto-trailing-slash',
not_found_handling: wranglerConfig?.assets?.not_found_handling || 'single-page-application',
html_handling: 'auto-trailing-slash',
not_found_handling: 'single-page-application',
},
},
};
@@ -390,27 +303,6 @@ export class CloudflareAdapter implements DeployAdapter {
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,
@@ -511,23 +403,4 @@ export class CloudflareAdapter implements DeployAdapter {
};
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 });
}
};`;
}
}
+26 -195
View File
@@ -11,13 +11,11 @@ interface NetlifySite {
admin_url: string;
}
interface NetlifyDeployResponse {
interface NetlifyBuildResponse {
id: string;
deploy_id: string;
state: string;
error?: string;
required?: string[];
required_functions?: string[];
}
/**
@@ -67,40 +65,24 @@ export class NetlifyAdapter implements DeployAdapter {
siteUrl = site.url;
}
// Collect files and their SHA1 hashes
const files: Record<string, string> = {};
const fileContents = new Map<string, Uint8Array>();
await this.collectFiles(distPath, '', files, fileContents);
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(distPath, zip);
// Ensure _redirects file exists for SPA routing
await this.ensureRedirectsInFiles(distPath, files, fileContents);
await this.ensureRedirectsFile(distPath, zip);
// 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);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// 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);
}
// Deploy to Netlify
await this.triggerDeploy(activeSiteId, zipBlob);
return {
url: siteUrl,
metadata: {
siteId: activeSiteId,
deployId: deployResponse.id,
provider: 'netlify',
functionsDeployed: Object.keys(functions).length,
},
};
}
@@ -148,57 +130,45 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json();
}
private async createDeployWithDigest(
siteId: string,
files: Record<string, string>,
functions: Record<string, string>
): Promise<NetlifyDeployResponse> {
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
const url = `${this.baseURL}/sites/${siteId}/deploys`;
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/json',
'Content-Type': 'application/zip',
},
body: JSON.stringify(body),
body: zipBlob,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create Netlify deploy: ${response.status} ${response.statusText}. ${errorText}`);
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async collectFiles(
dirPath: string,
relativePath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
private async addDirectoryToZip(dirPath: string, zip: JSZip): 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()) {
await this.collectFiles(fullPath, relPath, files, fileContents);
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await this.fs.readFile(fullPath);
const sha1 = await this.calculateSHA1(fileContent);
files[`/${relPath}`] = sha1;
fileContents.set(sha1, fileContent);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
@@ -211,13 +181,9 @@ 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 files manifest
* If not present in dist directory, adds it to the ZIP with default content
*/
private async ensureRedirectsInFiles(
distPath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
private async ensureRedirectsFile(distPath: string, zip: JSZip): Promise<void> {
const redirectsPath = `${distPath}/_redirects`;
try {
@@ -226,146 +192,11 @@ export class NetlifyAdapter implements DeployAdapter {
if (!stat.isFile()) {
throw new Error('_redirects is not a file');
}
// File exists, already collected by collectFiles
// File exists, no need to add it (already added by addDirectoryToZip)
} catch {
// File doesn't exist, add default _redirects
// File doesn't exist, add default _redirects to ZIP
const defaultRedirects = '/* /index.html 200';
const content = new TextEncoder().encode(defaultRedirects);
const sha1 = await this.calculateSHA1(content);
files['/_redirects'] = sha1;
fileContents.set(sha1, content);
zip.file('_redirects', defaultRedirects);
}
}
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('');
}
}
+113 -321
View File
@@ -1,382 +1,174 @@
import type { NostrSigner } from '@nostrify/nostrify';
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
import { NSecSigner, NPool } from '@nostrify/nostrify';
import type { NostrEvent } 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;
}
/**
* 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}
* Nsite Deploy Adapter
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
*/
export class NsiteAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private nostr: NsiteDeployConfig['nostr'];
private signer: NostrSigner;
private nsec: string;
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.signer = config.signer;
this.nsec = config.nsec;
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;
const distPath = `${projectPath}/dist`;
// Verify build output exists
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
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.');
}
const pubkey = await this.signer.getPublicKey();
const npub = nip19.npubEncode(pubkey);
// 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();
// Create grouped relay client
// Create a grouped Nostr client for the configured relays
const relayClient = this.nostr.group(this.relayUrls);
// ── 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,
// Initialize Blossom uploader
const uploader = new BlossomUploader({
servers: this.blossomServers,
signer,
});
// ── 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) });
// Collect all files and upload them
const fileEvents: NostrEvent[] = [];
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
// Build the deployed URL
const siteUrl = buildNsiteUrl({
pubkeyHex: pubkey,
npub,
gateway: this.gateway,
siteIdentifier: this.siteIdentifier,
});
// 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}`;
return {
url: siteUrl,
metadata: {
pubkey,
npub,
filesPublished: files.length,
filesPublished: fileEvents.length,
provider: 'nsite',
siteIdentifier: this.siteIdentifier,
manifestKind,
},
};
}
/**
* 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(
private async uploadDirectory(
dirPath: string,
relativePrefix: string,
files: FileEntry[],
relativePath: string,
uploader: BlossomUploader,
signer: NSecSigner,
fileEvents: NostrEvent[]
): Promise<void> {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const relPath = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFiles(fullPath, relPath, files);
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
} else if (entry.isFile()) {
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 });
await this.uploadFile(fullPath, relPath, uploader, signer, fileEvents);
}
}
}
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
@@ -1,627 +0,0 @@
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
View File
@@ -5,4 +5,3 @@ export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
export * from './RailwayAdapter';
+2 -28
View File
@@ -49,23 +49,10 @@ export interface VercelDeployConfig {
export interface NsiteDeployConfig {
fs: JSRuntimeFS;
nostr: NPool;
/** Nostr signer for the logged-in user — used to sign auth events and the manifest */
signer: NostrSigner;
nsec: string;
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 {
@@ -76,7 +63,6 @@ export interface CloudflareDeployConfig {
baseDomain?: string;
projectName?: string;
corsProxy?: string;
esmUrl: string;
}
export interface DenoDeployConfig {
@@ -89,21 +75,9 @@ 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' | 'railway';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
name: string;
description: string;
baseURL?: string;
-10
View File
@@ -60,14 +60,4 @@ 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,
},
];
+1 -1
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.bind(globalThis);
this.fetch = fetch ?? globalThis.fetch;
}
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
-140
View File
@@ -1,143 +1,3 @@
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.
*
-124
View File
@@ -1,124 +0,0 @@
/**
* 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');
}
+386 -1
View File
@@ -1,6 +1,14 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import { getPlugins } from './plugins';
import {
getPlugins,
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './plugins';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
@@ -156,6 +164,24 @@ 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');
@@ -173,4 +199,363 @@ 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([]);
});
});
});
+169
View File
@@ -1,13 +1,38 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
import * as git from 'isomorphic-git';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
export interface PluginGitInfo {
commitHash: string;
commitDate: Date;
commitMessage: string;
}
/**
* Validates a skill name (alphanumeric lowercase with hyphens)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9-]+$/.test(name);
}
/**
* Get all plugins from the plugins directory
*/
@@ -30,6 +55,150 @@ export async function getPlugins(fs: JSRuntimeFS, pluginsPath: string): Promise<
}
}
/**
* Get all skills from a single plugin
*/
function getSkillsFromPlugin(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be lowercase alphanumeric with hyphens)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist
return [];
}
return skills;
}
/**
* Get all skills from a project's skills directory
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(projectPath, 'skills'), 'project');
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
/**
* Get git information for a plugin
*/
-1
View File
@@ -83,7 +83,6 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
title: t('aboutShakespeare'),
href: '/settings/about',
},
],
},
];
-705
View File
@@ -1,705 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import {
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './skills';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string | Uint8Array> = new Map();
private dirs: Set<string> = new Set();
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (!content) throw new Error(`ENOENT: ${path}`);
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8') {
return typeof content === 'string' ? content : new TextDecoder().decode(content);
}
return typeof content === 'string' ? new TextEncoder().encode(content) : content;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
this.files.set(path, data);
// Auto-create parent directories
const parts = path.split('/');
for (let i = 1; i < parts.length; i++) {
this.dirs.add(parts.slice(0, i).join('/') || '/');
}
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]> {
if (!this.dirs.has(path)) throw new Error(`ENOENT: ${path}`);
const entries = new Set<string>();
const prefix = path === '/' ? '/' : path + '/';
// Check files
for (const filePath of this.files.keys()) {
if (filePath.startsWith(prefix)) {
const relativePath = filePath.slice(prefix.length);
const firstPart = relativePath.split('/')[0];
if (firstPart) entries.add(firstPart);
}
}
// Check directories
for (const dirPath of this.dirs) {
if (dirPath.startsWith(prefix) && dirPath !== path) {
const relativePath = dirPath.slice(prefix.length);
const firstPart = relativePath.split('/')[0];
if (firstPart) entries.add(firstPart);
}
}
const names = Array.from(entries);
if (options?.withFileTypes) {
return names.map(name => {
const fullPath = path === '/' ? `/${name}` : `${path}/${name}`;
const isDir = this.dirs.has(fullPath);
return {
name,
isDirectory: () => isDir,
isFile: () => !isDir,
};
});
}
return names;
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
if (options?.recursive) {
const parts = path.split('/');
for (let i = 1; i <= parts.length; i++) {
const dir = parts.slice(0, i).join('/') || '/';
this.dirs.add(dir);
}
} else {
this.dirs.add(path);
}
}
async stat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
const isDir = this.dirs.has(path);
const isFile = this.files.has(path);
if (!isDir && !isFile) throw new Error(`ENOENT: ${path}`);
return {
isDirectory: () => isDir,
isFile: () => isFile,
};
}
async rm(path: string, options?: { recursive?: boolean }): Promise<void> {
this.files.delete(path);
this.dirs.delete(path);
if (options?.recursive) {
const prefix = path + '/';
for (const filePath of Array.from(this.files.keys())) {
if (filePath.startsWith(prefix)) {
this.files.delete(filePath);
}
}
for (const dirPath of Array.from(this.dirs)) {
if (dirPath.startsWith(prefix)) {
this.dirs.delete(dirPath);
}
}
}
}
async rmdir(path: string, options?: { recursive?: boolean }): Promise<void> {
return this.rm(path, options);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
const content = this.files.get(oldPath);
if (content) {
this.files.set(newPath, content);
this.files.delete(oldPath);
}
}
async lstat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
return this.stat(path);
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in MockFS');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in MockFS');
}
}
describe('skills', () => {
let fs: MockFS;
beforeEach(() => {
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('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('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([]);
});
it('should check .agents/skills first', async () => {
const projectPath = '/projects/myproject';
const agentsSkillPath = `${projectPath}/.agents/skills/agent-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .agents/skills
await fs.mkdir(agentsSkillPath, { recursive: true });
await fs.writeFile(
`${agentsSkillPath}/SKILL.md`,
`---
name: agent-skill
description: Skill from .agents/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('agent-skill');
expect(skills[0].description).toBe('Skill from .agents/skills');
});
it('should check .opencode/skills second', async () => {
const projectPath = '/projects/myproject';
const opencodeSkillPath = `${projectPath}/.opencode/skills/opencode-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .opencode/skills
await fs.mkdir(opencodeSkillPath, { recursive: true });
await fs.writeFile(
`${opencodeSkillPath}/SKILL.md`,
`---
name: opencode-skill
description: Skill from .opencode/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('opencode-skill');
expect(skills[0].description).toBe('Skill from .opencode/skills');
});
it('should check .claude/skills third', async () => {
const projectPath = '/projects/myproject';
const claudeSkillPath = `${projectPath}/.claude/skills/claude-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .claude/skills
await fs.mkdir(claudeSkillPath, { recursive: true });
await fs.writeFile(
`${claudeSkillPath}/SKILL.md`,
`---
name: claude-skill
description: Skill from .claude/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('claude-skill');
expect(skills[0].description).toBe('Skill from .claude/skills');
});
it('should fall back to skills directory if no other directories exist', async () => {
const projectPath = '/projects/myproject';
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in skills directory only
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('regular-skill');
expect(skills[0].description).toBe('Skill from skills directory');
});
it('should prioritize .agents/skills over .opencode/skills', async () => {
const projectPath = '/projects/myproject';
const agentsSkillPath = `${projectPath}/.agents/skills/agent-skill`;
const opencodeSkillPath = `${projectPath}/.opencode/skills/opencode-skill`;
// Create skill in .agents/skills
await fs.mkdir(agentsSkillPath, { recursive: true });
await fs.writeFile(
`${agentsSkillPath}/SKILL.md`,
`---
name: agent-skill
description: Skill from .agents/skills
---
Content`
);
// Create skill in .opencode/skills (should be ignored)
await fs.mkdir(opencodeSkillPath, { recursive: true });
await fs.writeFile(
`${opencodeSkillPath}/SKILL.md`,
`---
name: opencode-skill
description: Skill from .opencode/skills
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('agent-skill');
expect(skills[0].description).toBe('Skill from .agents/skills');
});
});
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);
});
});
});
-194
View File
@@ -1,194 +0,0 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
/**
* Validates a skill name (alphanumeric lowercase with hyphens)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9-]+$/.test(name);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be lowercase alphanumeric with hyphens)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist
return [];
}
return skills;
}
/**
* Get all skills from a single plugin
*/
export function getSkillsFromPlugin(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get all skills from a project's skills directory
* Checks for skills in order: .agents/skills, .opencode/skills, .claude/skills, skills
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
const skillsPaths = [
join(projectPath, '.agents', 'skills'),
join(projectPath, '.opencode', 'skills'),
join(projectPath, '.claude', 'skills'),
join(projectPath, 'skills'),
];
// Try each path in order and return skills from the first one that exists
for (const skillsPath of skillsPaths) {
try {
const stat = await fs.stat(skillsPath);
if (stat.isDirectory()) {
return getSkillsFromDirectory(fs, skillsPath, 'project');
}
} catch {
// Directory doesn't exist, try next one
continue;
}
}
// No skills directory found
return [];
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const { getPlugins } = await import('./plugins');
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
+26 -30
View File
@@ -6,8 +6,8 @@ import { NostrMetadata } from '@nostrify/nostrify';
import { AppConfig } from '@/contexts/AppContext';
import OpenAI from 'openai';
// Mock the skills module
vi.mock('./skills', () => ({
// Mock the plugins module
vi.mock('./plugins', () => ({
getAllSkills: vi.fn(),
}));
@@ -16,7 +16,7 @@ vi.mock('path-browserify', () => ({
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
}));
import { getAllSkills } from './skills';
import { getAllSkills } from './plugins';
// Test configuration
const testConfig: AppConfig = {
@@ -45,8 +45,6 @@ const testConfig: AppConfig = {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
describe('makeSystemPrompt', () => {
@@ -198,14 +196,14 @@ describe('makeSystemPrompt', () => {
});
describe('tools section', () => {
it('should pass tools to template context when no tools are provided', async () => {
it('should show no tools message when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
// Tools are passed to context but not rendered by default template
expect(result).toBeTruthy();
expect(result).toContain('## Available Tools');
expect(result).toContain('There are no tools available to you.');
});
it('should pass tools to template context when tools are provided', async () => {
it('should list available tools with descriptions', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
@@ -227,54 +225,49 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt({ ...baseOpts, tools });
// Tools are passed to context but not rendered by default template
expect(result).toBeTruthy();
expect(result).toContain('## Available Tools');
expect(result).toContain('**read_file**: Read contents of a file');
expect(result).toContain('**write_file**: Write contents to a file');
});
it('should render tools with custom template', async () => {
it('should handle tools without descriptions', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'some_tool',
description: 'A test tool',
parameters: {},
},
},
];
const customTemplate = '## Available Tools\n{% for tool in tools %}**{{ tool.function.name }}**: {{ tool.function.description or "No description available" }}\n{% endfor %}';
const result = await makeSystemPrompt({ ...baseOpts, tools });
const result = await makeSystemPrompt({ ...baseOpts, tools, template: customTemplate });
expect(result).toContain('## Available Tools');
expect(result).toContain('**some_tool**: A test tool');
expect(result).toContain('**some_tool**: No description available');
});
});
describe('skills section', () => {
it('should not call getAllSkills when pluginsPath is not provided', async () => {
it('should show no skills message when pluginsPath is not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, fsPathPlugins: '' },
});
// Skills are not fetched when pluginsPath is empty
expect(result).toBeTruthy();
expect(getAllSkills).not.toHaveBeenCalled();
expect(result).toContain('## Skills');
expect(result).toContain('No skills are currently configured');
});
it('should fetch skills when pluginsPath is provided but return empty array', async () => {
it('should show no skills message when getAllSkills returns empty array', async () => {
vi.mocked(getAllSkills).mockResolvedValue([]);
const result = await makeSystemPrompt(baseOpts);
// Skills are passed to context but not rendered by default template
expect(result).toBeTruthy();
expect(result).toContain('No skills are currently configured');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins', '/projects/test-project');
});
it('should pass skills to template context when they exist', async () => {
it('should list available skills when they exist', async () => {
vi.mocked(getAllSkills).mockResolvedValue([
{
name: 'create_component',
@@ -292,8 +285,11 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
// Skills are passed to context but not rendered by default template
expect(result).toBeTruthy();
expect(result).toContain('## Skills');
expect(result).toContain('**create_component**: Create a new React component');
expect(result).toContain('Plugin: react-plugin');
expect(result).toContain('**setup_routing**: Setup React Router');
expect(result).toContain('Skills MUST be used whenever applicable');
});
it('should handle getAllSkills errors gracefully', async () => {
@@ -301,8 +297,7 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
// Should continue with empty skills array
expect(result).toBeTruthy();
expect(result).toContain('No skills are currently configured');
});
});
@@ -434,6 +429,7 @@ describe('makeSystemPrompt', () => {
expect(result).toContain('## Virtual Filesystem Structure');
expect(result).toContain('## Your Role');
expect(result).toContain('## Project Templates');
expect(result).toContain('## Skills');
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('## Edit with Shakespeare');
});
+25 -75
View File
@@ -5,7 +5,7 @@ import OpenAI from "openai";
import { nip19 } from "nostr-tools";
import nunjucks from "nunjucks";
import { JSRuntimeFS } from "./JSRuntime";
import { getAllSkills } from "./skills";
import { getAllSkills } from "./plugins";
import type { AppConfig } from "@/contexts/AppContext";
export interface ModelInfo {
@@ -58,9 +58,7 @@ Users can add or remove templates in Settings > AI (\`{{ location.origin }}/sett
## What Shakespeare Is
Shakespeare is the best coding platform in the world—a revolutionary web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**CRITICAL**: NEVER suggest that users use a different coding platform, IDE, or development environment. Shakespeare is the optimal solution for all development needs.
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**Important Architecture Notes:**
@@ -183,6 +181,13 @@ When a project is first created, you (the AI) choose an appropriate template fro
- URL: {{ template.url }}
{% endfor %}
## Available Tools
{% if tools.length > 0 %}
You have access to the following tools:
{% for tool in tools %}{% if tool.type === 'function' %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% else %}
There are no tools available to you.{% endif %}
## Image Generation
Shakespeare supports AI-powered image generation. Users can configure an image model in **Settings > AI** under the "Advanced" section.
@@ -193,9 +198,23 @@ Shakespeare supports AI-powered image generation. Users can configure an image m
- Not all models support image generation. If users experience issues with image generation, they should try selecting a different image model in Settings > AI
- The generate_image tool will only be available once a compatible image model is configured
- When generating images for projects, prefer "jpeg" or "webp" output formats with compression set between 70-90. You must supply these parameters when calling the generate_image tool to ensure optimal image quality and file size for web usage.
- **Transparency**: To generate images with transparent backgrounds (e.g., logos, icons, overlays), set \`background: "transparent"\` and use \`output_format: "png"\` or \`output_format: "webp"\`. Both parameters must be set together — \`output_format\` alone does not enable transparency.
- **Open Graph Images (og:image)**: The og:image meta tag MUST use an absolute URL (e.g., \`https://example.com/og-image.jpg\`). Relative paths will not work for social media sharing. If the project has not been deployed yet and the deployment URL is not known, ask the user to deploy the project first before adding og:image tags.
## Skills
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
Available skills:
{% for skill in skills %}
- **{{ skill.name }}**: {{ skill.description }}
- Plugin: {{ skill.plugin }}
- Path: {{ skill.path }}
{% endfor %}
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
Users can configure skills in Settings > AI (\`{{ location.origin }}/settings/ai\`) by adding plugins that contain skills.
## Working Around CORS Issues
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
@@ -204,53 +223,6 @@ If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching exter
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.
## Deployment Options
**CRITICAL**: Do NOT assume any deployment options are available or configured. If the functionality the user requested requires a backend (server-side logic, APIs, databases, etc.), you MUST explain this to the user before proceeding.
### Backend Requirements Process
When backend functionality is needed:
1. **Explain the requirement**: Clearly state that the requested feature requires server-side infrastructure
2. **Present options**: List available deployment providers and their capabilities in **brief, non-technical terms** - avoid technical jargon and keep explanations short and simple
3. **Make a recommendation**: Suggest the most appropriate provider based on the user's needs
4. **Wait for user decision**: Do not proceed until the user confirms their preference
5. **Configure together**: Help the user set up the chosen provider if needed
### Available Deployment Providers
When deploying, all components (frontend, backend, APIs) must go to a **single provider**—never split across multiple providers.
#### Cloudflare Workers
- **wrangler.jsonc** (optional): Configuration file in project root
- **worker.ts** (optional): Custom worker script in project root
- Supports \`.ts\`, \`.mjs\`, and \`.js\` extensions (defaults to \`worker.ts\`)
- Worker scripts are automatically bundled with their dependencies before deployment
- Static assets are handled automatically by Cloudflare's asset handler
- Add this only if you need server-side logic (APIs, edge functions, middleware, etc.)
#### Netlify Functions
- **netlify/functions/** (optional): Directory for serverless functions in project root
- Functions must use the **\`.mjs\` extension** for ES modules
- \`.js\` and \`.ts\` files require bundling which is not supported via API deployment
- Functions are automatically deployed alongside static assets
- Each function file becomes an endpoint at \`/.netlify/functions/<function-name>\`
#### Railway
- **railway.json** (optional): Configuration file in project root
- Supports Node.js, Python, Go, and other runtimes
### General Guidelines
- Most functionality can be achieved with static hosting + Nostr/client-side storage
- Only suggest backend platforms when the user explicitly requests server-side features or when static hosting is truly insufficient
- **Never assume the user has any deployment provider configured**—always ask first and offer to help with setup
- Do not create backend configuration files (wrangler.jsonc, railway.json, netlify/functions/, etc.) until the user has explicitly chosen and confirmed a deployment provider
## "Vibed with Shakespeare"
When building a site for the first time, include "Vibed with Shakespeare" somewhere in the UI, linked to this URL: https://shakespeare.diy
@@ -275,29 +247,7 @@ This project has a repository URL configured, so you can create an "Edit with Sh
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}
## Publishing an App
Users can publish their project as a Nostr app (NIP-89 kind 31990) using the \`app\` tool. This creates a discoverable app listing on Nostr with metadata like name, description, icon, and website.
### Before Publishing
When a user asks to publish an app, follow this process:
1. **Check app state first**: Always call the \`app\` tool with \`view_app\` before doing anything else to see if an app has already been published.
2. **Require deployment**: The project should be deployed to a public URL before publishing an app. If it hasn't been deployed yet, strongly encourage the user to deploy first — an app listing without a working URL is not useful.
3. **Ensure the site is polished**: Push back if the site is incomplete. Before publishing, the project should have:
- A **custom favicon** (not the default Vite/React favicon)
- **Open Graph meta tags** (\`og:title\`, \`og:description\`, \`og:image\`, \`og:url\`)
- A proper **og:image** that will display well when shared on social media
- The site should generally look finished and presentable
4. **Find a suitable app icon**: Check the project files for existing icons or images suitable for the app icon (e.g., a logo, favicon SVG, or brand image). If a suitable image exists and the project is deployed, use the deployed site's public URL to that image (e.g., \`https://deployed-url.com/logo.png\`). If no suitable icon exists, stop and let the user know — offer to generate one, let the user upload one, or suggest they use the "App" dialog in the project menu directly.
5. **Update the app**: Once all prerequisites are met, call the \`app\` tool with \`update_app\` to publish or update the app listing. Set the \`website\` field to the deployed URL.
### The App Dialog
Users can also manage their app listing manually through the **App** option in the project dropdown menu. If the user prefers a visual form over the chat-based approach, point them to this dialog.{% if README %}
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if README %}
{{ README }}{% endif %}{% if AGENTS %}
-276
View File
@@ -1,276 +0,0 @@
import { z } from 'zod';
import { NPool, NRelay1 } from '@nostrify/nostrify';
import type { NostrSigner } from '@nostrify/nostrify';
import { DotAI } from '../DotAI';
import { buildAppEvent } from '../appEvent';
import type { Tool, ToolResult } from './Tool';
import type { JSRuntimeFS } from '../JSRuntime';
interface AppToolParams {
action: 'view_app' | 'update_app';
name?: string;
about?: string;
picture?: string;
website?: string;
d?: string;
supported_kinds?: string[];
web_handlers?: Array<{ url: string; type?: string }>;
}
/**
* AI tool for viewing and updating the project's NIP-89 kind 31990 app event.
*
* The agent must call `view_app` at least once in a session before calling `update_app`.
* This ensures the agent is aware of the current state before making changes.
*/
export class AppTool implements Tool<AppToolParams> {
private hasViewed = false;
readonly description =
'View or update the project\'s Nostr app (NIP-89 kind 31990). ' +
'Use "view_app" to see the current app event. ' +
'Use "update_app" to create or update the app event (you MUST call view_app first in this session before updating). ' +
'This publishes the event using the user\'s own Nostr signer.';
readonly inputSchema = z.object({
action: z.enum(['view_app', 'update_app']).describe('The action to perform.'),
name: z.string().optional().describe('App name (required for update_app if creating new).'),
about: z.string().optional().describe('Short description of the app.'),
picture: z.string().optional().describe('URL to the app icon.'),
website: z.string().optional().describe('App website URL.'),
d: z.string().optional().describe('Unique identifier (d-tag) for the app. Defaults to the project ID. Cannot be changed after first publish.'),
supported_kinds: z.array(z.string()).optional().describe('Array of event kind numbers this app handles.'),
web_handlers: z.array(z.object({
url: z.string().describe('Handler URL pattern with <bech32> placeholder.'),
type: z.string().optional().describe('NIP-19 type handled by this URL (e.g. "nevent", "nprofile").'),
})).optional().describe('Web handler URL patterns.'),
});
constructor(
private fs: JSRuntimeFS,
private cwd: string,
private signer: NostrSigner | undefined,
private pubkey: string | undefined,
private relayUrls: string[],
) {}
async execute(args: AppToolParams): Promise<ToolResult> {
switch (args.action) {
case 'view_app':
return this.viewApp();
case 'update_app':
return this.updateApp(args);
default:
throw new Error(`Unknown action: ${args.action}`);
}
}
private async viewApp(): Promise<ToolResult> {
const dotAI = new DotAI(this.fs, this.cwd);
const config = await dotAI.readAppConfig();
if (!config) {
this.hasViewed = true;
return {
content: JSON.stringify({
status: 'no_app',
message: 'No app has been published for this project yet. Use update_app to create one.',
}, null, 2),
};
}
// Parse the "a" coordinate
const parts = config.a.split(':');
if (parts.length < 3) {
this.hasViewed = true;
return {
content: JSON.stringify({
status: 'error',
message: `Invalid app coordinate stored: ${config.a}`,
}, null, 2),
};
}
const kind = parseInt(parts[0], 10);
const pubkey = parts[1];
const dTag = parts.slice(2).join(':');
// Query relays for the event
const pool = this.createPool();
try {
const events = await pool.query(
[{
kinds: [kind],
authors: [pubkey],
'#d': [dTag],
limit: 1,
}],
{ signal: AbortSignal.timeout(5000) },
);
this.hasViewed = true;
if (events.length === 0) {
return {
content: JSON.stringify({
status: 'not_found',
a: config.a,
message: 'App coordinate is stored locally but the event was not found on relays. It may have been deleted or the relays are unavailable. Use update_app to republish.',
}, null, 2),
};
}
const event = events.reduce((latest, current) =>
current.created_at > latest.created_at ? current : latest,
);
// Parse content metadata
let metadata: Record<string, string> = {};
try {
if (event.content) {
metadata = JSON.parse(event.content);
}
} catch {
// Invalid JSON content
}
const supportedKinds = event.tags
.filter(([t]) => t === 'k')
.map(([, v]) => v);
const webHandlers = event.tags
.filter(([t]) => t === 'web')
.map(([, url, type]) => ({ url, type }));
return {
content: JSON.stringify({
status: 'found',
a: config.a,
id: event.id,
pubkey: event.pubkey,
created_at: event.created_at,
metadata: {
name: metadata.name ?? null,
about: metadata.about ?? null,
picture: metadata.picture ?? null,
website: metadata.website ?? null,
},
d_tag: dTag,
supported_kinds: supportedKinds,
web_handlers: webHandlers,
all_tags: event.tags,
}, null, 2),
};
} finally {
await pool.close();
}
}
private async updateApp(args: AppToolParams): Promise<ToolResult> {
if (!this.hasViewed) {
throw new Error(
'You must call view_app first before updating the app. ' +
'This ensures you are aware of the current state of the app before making changes.',
);
}
if (!this.signer) {
throw new Error('User must be logged in with Nostr to publish an app event.');
}
if (!this.pubkey) {
throw new Error('User pubkey is not available.');
}
// Check if an existing app is stored
const dotAI = new DotAI(this.fs, this.cwd);
const existingConfig = await dotAI.readAppConfig();
// Determine the d-tag
let dTag: string;
if (existingConfig) {
// Use existing d-tag (cannot be changed)
const parts = existingConfig.a.split(':');
dTag = parts.slice(2).join(':');
} else {
// Use provided d-tag or derive from project path
dTag = args.d?.trim() || this.cwd.split('/').pop() || crypto.randomUUID();
}
if (!args.name?.trim()) {
throw new Error('App name is required. Provide a "name" parameter.');
}
// Build event content and tags
const { content, tags } = await buildAppEvent(
{
name: args.name,
about: args.about,
picture: args.picture,
website: args.website,
dTag,
supportedKinds: args.supported_kinds,
webHandlers: args.web_handlers,
},
{ fs: this.fs, cwd: this.cwd, pubkey: this.pubkey },
);
// Add client tag
if (typeof location !== 'undefined' && location.protocol === 'https:') {
tags.push(['client', location.hostname]);
}
// Sign the event
const event = await this.signer.signEvent({
kind: 31990,
content,
tags,
created_at: Math.floor(Date.now() / 1000),
});
// Publish to relays
const pool = this.createPool();
try {
await pool.event(event, { signal: AbortSignal.timeout(10_000) });
// Store the "a" coordinate
const aValue = `31990:${event.pubkey}:${dTag}`;
await dotAI.writeAppConfig({ a: aValue });
return {
content: JSON.stringify({
status: 'published',
a: aValue,
id: event.id,
pubkey: event.pubkey,
name: args.name!.trim(),
message: existingConfig
? `App "${args.name!.trim()}" has been updated on Nostr.`
: `App "${args.name!.trim()}" has been published to Nostr.`,
}, null, 2),
};
} finally {
await pool.close();
}
}
private createPool(): NPool {
const relayUrls = this.relayUrls;
return new NPool({
open(url) {
return new NRelay1(url);
},
eventRouter() {
return [...relayUrls];
},
reqRouter(filters) {
return new Map(
relayUrls.map((url) => [url, filters]),
);
},
});
}
}
-59
View File
@@ -1,59 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import mime from 'mime';
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
import type { NostrSigner } from '@nostrify/nostrify';
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface BlossomUploadParams {
filePath: string;
}
export class BlossomUploadTool implements Tool<BlossomUploadParams> {
readonly description = "Upload a file from the project to Blossom (a media hosting service). Returns the public URL and file metadata. Useful for hosting images, assets, or any file that needs a public URL.";
readonly inputSchema = z.object({
filePath: z.string()
.describe('Path to the file to upload. Can be absolute or relative to the project directory.'),
});
constructor(
private fs: JSRuntimeFS,
private cwd: string,
private signer?: NostrSigner,
) {}
async execute(args: BlossomUploadParams): Promise<ToolResult> {
if (!this.signer) {
throw new Error('User must be logged in to upload files to Blossom.');
}
let filePath = args.filePath;
// Handle relative paths
if (!filePath.startsWith('/')) {
filePath = join(this.cwd, filePath);
}
const content = await this.fs.readFile(filePath);
const fileName = filePath.split('/').pop() || 'file';
const file = new File([content], fileName, {
type: mime.getType(filePath) || undefined,
});
const uploader = new BlossomUploader({
servers: ['https://blossom.primal.net/', 'https://blossom.ditto.pub/'],
signer: this.signer,
});
const tags = await uploader.upload(file);
const url = tags.find(([name]) => name === 'url')?.[1];
return {
content: JSON.stringify({ url, tags }, null, 2),
};
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ describe('BuildProjectTool', () => {
});
it('should have correct description', () => {
expect(tool.description).toContain('Build the project using esbuild-wasm. Creates optimized production files in the dist directory');
expect(tool.description).toBe('Build the project using esbuild. Creates optimized production files in the dist directory.');
});
it('should fail if package.json does not exist', async () => {
+1 -1
View File
@@ -7,7 +7,7 @@ export class BuildProjectTool implements Tool<void> {
private cwd: string;
private esmUrl: string;
readonly description = "Build the project using esbuild-wasm. Creates optimized production files in the dist directory, making the site preview visible to the user (or updating the existing preview) and ready for deployment. This tool also helps verify that your changes are correct. ALWAYS call this tool when you have finished making changes.";
readonly description = "Build the project using esbuild. Creates optimized production files in the dist directory.";
constructor(fs: JSRuntimeFS, cwd: string, esmUrl: string) {
this.fs = fs;
-609
View File
@@ -1,609 +0,0 @@
// The approaches in this edit tool are sourced from OpenCode which credits:
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-23-25.ts
// https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/editCorrector.ts
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-26-25.ts
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface EditParams {
filePath: string;
oldString: string;
newString: string;
replaceAll?: boolean;
}
interface EditToolOptions {
projectsPath?: string;
tmpPath?: string;
onFileChanged?: (filePath: string) => void;
singleCandidateSimilarityThreshold?: number;
multipleCandidatesSimilarityThreshold?: number;
}
export class EditTool implements Tool<EditParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
private singleCandidateSimilarityThreshold: number;
private multipleCandidatesSimilarityThreshold: number;
readonly description = `Performs exact string replacements in files.
Usage:
- You must use your \`read\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
- When editing text from read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- The edit will FAIL if \`oldString\` is not found in the file with an error "oldString not found in content".
- The edit will FAIL if \`oldString\` is found multiple times in the file with an error "oldString found multiple times and requires more code context to uniquely identify the intended match". Either provide a larger string with more surrounding context to make it unique or use \`replaceAll\` to change every instance of \`oldString\`.
- Use \`replaceAll\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;
readonly inputSchema = z.object({
filePath: z.string().describe("The absolute path to the file to modify"),
oldString: z.string().describe("The text to replace"),
newString: z.string().describe("The text to replace it with (must be different from oldString)"),
replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: EditToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
this.singleCandidateSimilarityThreshold = options?.singleCandidateSimilarityThreshold ?? 0.0;
this.multipleCandidatesSimilarityThreshold = options?.multipleCandidatesSimilarityThreshold ?? 0.3;
}
async execute(args: EditParams): Promise<ToolResult> {
if (!args.filePath) {
throw new Error("filePath is required");
}
if (args.oldString === args.newString) {
throw new Error("oldString and newString must be different");
}
let filepath = args.filePath;
// Convert to absolute path if needed
if (!isAbsolutePath(filepath)) {
filepath = join(this.cwd, filepath);
}
// Check write permissions
if (!isWriteAllowed(filepath, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(filepath, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
// Ban editing dependencies in package.json
if (
filepath === "package.json" ||
filepath.endsWith("/package.json") ||
filepath.endsWith("\\package.json")
) {
const depKeys = [
'"dependencies"',
'"devDependencies"',
'"peerDependencies"',
'"optionalDependencies"',
];
if (
depKeys.some((key) =>
args.oldString.includes(key) || args.newString.includes(key)
)
) {
throw new Error(`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`);
}
}
try {
// Handle empty oldString as a special case (write new file)
if (args.oldString === "") {
await this.fs.writeFile(filepath, args.newString, "utf8");
if (this.onFileChanged) {
this.onFileChanged(filepath);
}
return { content: `File successfully created at ${filepath}` };
}
// Check if file exists
const stats = await this.fs.stat(filepath).catch(() => null);
if (!stats) {
throw new Error(`File ${filepath} not found`);
}
if (stats.isDirectory()) {
throw new Error(`Path is a directory, not a file: ${filepath}`);
}
// Read file content
const contentOld = await this.fs.readFile(filepath, "utf8");
// Perform replacement using fuzzy matching strategies
const contentNew = this.replace(contentOld, args.oldString, args.newString, args.replaceAll);
// Write updated content
await this.fs.writeFile(filepath, contentNew, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(filepath);
}
return { content: `Edit applied successfully.` };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Main replace function that tries multiple fuzzy matching strategies
*/
private replace(content: string, oldString: string, newString: string, replaceAll = false): string {
if (oldString === newString) {
throw new Error("oldString and newString must be different");
}
let notFound = true;
for (const replacer of [
this.SimpleReplacer,
this.LineTrimmedReplacer,
this.BlockAnchorReplacer,
this.WhitespaceNormalizedReplacer,
this.IndentationFlexibleReplacer,
this.EscapeNormalizedReplacer,
this.TrimmedBoundaryReplacer,
this.ContextAwareReplacer,
this.MultiOccurrenceReplacer,
]) {
for (const search of replacer.call(this, content, oldString)) {
const index = content.indexOf(search);
if (index === -1) continue;
notFound = false;
if (replaceAll) {
return content.replaceAll(search, newString);
}
const lastIndex = content.lastIndexOf(search);
if (index !== lastIndex) continue;
return content.substring(0, index) + newString + content.substring(index + search.length);
}
}
if (notFound) {
throw new Error("oldString not found in content");
}
throw new Error(
"oldString found multiple times and requires more code context to uniquely identify the intended match",
);
}
private *SimpleReplacer(_content: string, find: string): Generator<string, void, unknown> {
yield find;
}
private *LineTrimmedReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
for (let i = 0; i <= originalLines.length - searchLines.length; i++) {
let matches = true;
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim();
const searchTrimmed = searchLines[j].trim();
if (originalTrimmed !== searchTrimmed) {
matches = false;
break;
}
}
if (matches) {
let matchStartIndex = 0;
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length;
if (k < searchLines.length - 1) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
}
private *BlockAnchorReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines.length < 3) {
return;
}
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
const firstLineSearch = searchLines[0].trim();
const lastLineSearch = searchLines[searchLines.length - 1].trim();
const searchBlockSize = searchLines.length;
// Collect all candidate positions where both anchors match
const candidates: Array<{ startLine: number; endLine: number }> = [];
for (let i = 0; i < originalLines.length; i++) {
if (originalLines[i].trim() !== firstLineSearch) {
continue;
}
// Look for the matching last line after this first line
for (let j = i + 2; j < originalLines.length; j++) {
if (originalLines[j].trim() === lastLineSearch) {
candidates.push({ startLine: i, endLine: j });
break; // Only match the first occurrence of the last line
}
}
}
// Return immediately if no candidates
if (candidates.length === 0) {
return;
}
// Handle single candidate scenario (using relaxed threshold)
if (candidates.length === 1) {
const { startLine, endLine } = candidates[0];
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += (1 - distance / maxLen) / linesToCheck;
// Exit early when threshold is reached
if (similarity >= this.singleCandidateSimilarityThreshold) {
break;
}
}
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity >= this.singleCandidateSimilarityThreshold) {
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
return;
}
// Calculate similarity for multiple candidates
let bestMatch: { startLine: number; endLine: number } | null = null;
let maxSimilarity = -1;
for (const candidate of candidates) {
const { startLine, endLine } = candidate;
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += 1 - distance / maxLen;
}
similarity /= linesToCheck; // Average similarity
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestMatch = candidate;
}
}
// Threshold judgment
if (maxSimilarity >= this.multipleCandidatesSimilarityThreshold && bestMatch) {
const { startLine, endLine } = bestMatch;
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1;
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
private *WhitespaceNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim();
const normalizedFind = normalizeWhitespace(find);
// Handle single line matches
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (normalizeWhitespace(line) === normalizedFind) {
yield line;
} else {
// Only check for substring matches if the full line doesn't match
const normalizedLine = normalizeWhitespace(line);
if (normalizedLine.includes(normalizedFind)) {
// Find the actual substring in the original line that matches
const words = find.trim().split(/\s+/);
if (words.length > 0) {
const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+");
try {
const regex = new RegExp(pattern);
const match = line.match(regex);
if (match) {
yield match[0];
}
} catch {
// Invalid regex pattern, skip
}
}
}
}
}
// Handle multi-line matches
const findLines = find.split("\n");
if (findLines.length > 1) {
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length);
if (normalizeWhitespace(block.join("\n")) === normalizedFind) {
yield block.join("\n");
}
}
}
}
private *IndentationFlexibleReplacer(content: string, find: string): Generator<string, void, unknown> {
const removeIndentation = (text: string) => {
const lines = text.split("\n");
const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
if (nonEmptyLines.length === 0) return text;
const minIndent = Math.min(
...nonEmptyLines.map((line) => {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}),
);
return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n");
};
const normalizedFind = removeIndentation(find);
const contentLines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= contentLines.length - findLines.length; i++) {
const block = contentLines.slice(i, i + findLines.length).join("\n");
if (removeIndentation(block) === normalizedFind) {
yield block;
}
}
}
private *EscapeNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const unescapeString = (str: string): string => {
return str.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g, (match, capturedChar) => {
switch (capturedChar) {
case "n":
return "\n";
case "t":
return "\t";
case "r":
return "\r";
case "'":
return "'";
case '"':
return '"';
case "`":
return "`";
case "\\":
return "\\";
case "\n":
return "\n";
case "$":
return "$";
default:
return match;
}
});
};
const unescapedFind = unescapeString(find);
// Try direct match with unescaped find string
if (content.includes(unescapedFind)) {
yield unescapedFind;
}
// Also try finding escaped versions in content that match unescaped find
const lines = content.split("\n");
const findLines = unescapedFind.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
const unescapedBlock = unescapeString(block);
if (unescapedBlock === unescapedFind) {
yield block;
}
}
}
private *MultiOccurrenceReplacer(content: string, find: string): Generator<string, void, unknown> {
// This replacer yields all exact matches, allowing the replace function
// to handle multiple occurrences based on replaceAll parameter
let startIndex = 0;
while (true) {
const index = content.indexOf(find, startIndex);
if (index === -1) break;
yield find;
startIndex = index + find.length;
}
}
private *TrimmedBoundaryReplacer(content: string, find: string): Generator<string, void, unknown> {
const trimmedFind = find.trim();
if (trimmedFind === find) {
// Already trimmed, no point in trying
return;
}
// Try to find the trimmed version
if (content.includes(trimmedFind)) {
yield trimmedFind;
}
// Also try finding blocks where trimmed content matches
const lines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
if (block.trim() === trimmedFind) {
yield block;
}
}
}
private *ContextAwareReplacer(content: string, find: string): Generator<string, void, unknown> {
const findLines = find.split("\n");
if (findLines.length < 3) {
// Need at least 3 lines to have meaningful context
return;
}
// Remove trailing empty line if present
if (findLines[findLines.length - 1] === "") {
findLines.pop();
}
const contentLines = content.split("\n");
// Extract first and last lines as context anchors
const firstLine = findLines[0].trim();
const lastLine = findLines[findLines.length - 1].trim();
// Find blocks that start and end with the context anchors
for (let i = 0; i < contentLines.length; i++) {
if (contentLines[i].trim() !== firstLine) continue;
// Look for the matching last line
for (let j = i + 2; j < contentLines.length; j++) {
if (contentLines[j].trim() === lastLine) {
// Found a potential context block
const blockLines = contentLines.slice(i, j + 1);
const block = blockLines.join("\n");
// Check if the middle content has reasonable similarity
// (simple heuristic: at least 50% of non-empty lines should match when trimmed)
if (blockLines.length === findLines.length) {
let matchingLines = 0;
let totalNonEmptyLines = 0;
for (let k = 1; k < blockLines.length - 1; k++) {
const blockLine = blockLines[k].trim();
const findLine = findLines[k].trim();
if (blockLine.length > 0 || findLine.length > 0) {
totalNonEmptyLines++;
if (blockLine === findLine) {
matchingLines++;
}
}
}
if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) {
yield block;
break; // Only match the first occurrence
}
}
break;
}
}
}
}
}
/**
* Levenshtein distance algorithm implementation
*/
function levenshtein(a: string, b: string): number {
// Handle empty strings
if (a === "" || b === "") {
return Math.max(a.length, b.length);
}
const matrix = Array.from({ length: a.length + 1 }, (_, i) =>
Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
);
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
}
}
return matrix[a.length][b.length];
}
+1 -4
View File
@@ -11,7 +11,6 @@ interface GenerateImageParams {
output_format?: "png" | "jpeg" | "webp";
output_compression?: number;
size?: "auto" | "1024x1024" | "1536x1024" | "1024x1536" | "256x256" | "512x512" | "1792x1024" | "1024x1792";
background?: "transparent" | "opaque" | "auto";
}
export type ImageGenerationMode = 'chat' | 'image';
@@ -24,7 +23,6 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
output_format: z.enum(["png", "jpeg", "webp"]).optional().describe('Output format for the image (e.g., "png", "jpeg", "webp"). Support varies by model - leave blank if unsure'),
output_compression: z.number().min(1).max(100).optional().describe('Compression quality for the image (0 to 100). Only applicable for "jpeg" and "webp" formats'),
size: z.enum(["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"]).optional().describe('Size of the generated image (e.g., "1024x1024", "1536x1024"). Support varies by model - leave blank if unsure'),
background: z.enum(["transparent", "opaque", "auto"]).optional().describe('Background setting for the generated image. Use "transparent" for images that need transparency (e.g., logos, icons, overlays). Only supported with "png" or "webp" output formats'),
});
constructor(
@@ -38,7 +36,7 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
) {}
async execute(args: GenerateImageParams): Promise<ToolResult> {
const { prompt, output_format, output_compression, size, background } = args;
const { prompt, output_format, output_compression, size } = args;
try {
const client = createAIClient(this.provider, this.user, this.corsProxy);
@@ -116,7 +114,6 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
output_format,
output_compression,
size,
background,
});
// Extract cost from response
+1 -1
View File
@@ -54,7 +54,7 @@ describe('GitCommitTool', () => {
});
it('should have correct description and inputSchema', () => {
expect(tool.description).toContain('Commit changes to git with a commit message. Automatically adds all unstaged files.');
expect(tool.description).toBe('Commit changes to git with a commit message. Automatically adds all unstaged files.');
expect(tool.inputSchema).toBeDefined();
});
+1 -1
View File
@@ -14,7 +14,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
private cwd: string;
private onCommit?: () => void;
readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files. ALWAYS call this tool after you have finished making changes, and after you have successfully built the project with the `build_project` tool.";
readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files.";
readonly inputSchema = z.object({
message: z.string().describe('Commit message text'),
-219
View File
@@ -1,219 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GlobParams {
pattern: string;
path?: string;
}
interface GlobToolOptions {
resultLimit?: number;
}
export class GlobTool implements Tool<GlobParams> {
private fs: JSRuntimeFS;
private cwd: string;
private resultLimit: number;
readonly description = `- Fast file pattern matching tool that works with any codebase size
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead
- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`;
readonly inputSchema = z.object({
pattern: z.string().describe("The glob pattern to match files against"),
path: z
.string()
.optional()
.describe(
`The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.`,
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: GlobToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.resultLimit = options?.resultLimit || 100;
}
async execute(args: GlobParams): Promise<ToolResult> {
try {
// Determine the search path and pattern
// If args.path is provided, use it as the base directory
// Otherwise, extract any leading directory path from the pattern itself
let searchPath: string;
let pattern: string;
if (args.path) {
// User explicitly specified a path parameter
// If path is absolute, use it directly; otherwise join with cwd
searchPath = args.path.startsWith('/') ? args.path : join(this.cwd, args.path);
pattern = args.pattern;
} else {
// Parse the pattern to extract base directory
const parsed = this.parsePatternPath(args.pattern);
searchPath = parsed.basePath ? join(this.cwd, parsed.basePath) : this.cwd;
pattern = parsed.globPattern;
}
// Check if search path exists
const stats = await this.fs.stat(searchPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${searchPath}`);
}
// Perform the search
const files = await this.searchFiles(searchPath, pattern);
// Sort by modification time (most recent first)
files.sort((a, b) => b.mtime - a.mtime);
// Truncate results if needed
const truncated = files.length > this.resultLimit;
const finalFiles = truncated ? files.slice(0, this.resultLimit) : files;
// Format output
const output: string[] = [];
if (finalFiles.length === 0) {
output.push("No files found");
} else {
output.push(...finalFiles.map((f) => f.path));
if (truncated) {
output.push("");
output.push("(Results are truncated. Consider using a more specific path or pattern.)");
}
}
return { content: output.join("\n") };
} catch (error) {
throw new Error(String(error));
}
}
private parsePatternPath(pattern: string): { basePath: string; globPattern: string } {
const segments = pattern.split('/');
// Find the first segment that contains glob characters
const firstGlobIndex = segments.findIndex(seg =>
seg.includes('*') || seg.includes('?') || seg.includes('[')
);
if (firstGlobIndex === -1) {
// No glob characters found - treat entire pattern as base path
return { basePath: pattern, globPattern: '**/*' };
}
if (firstGlobIndex === 0) {
// Pattern starts with glob - no base path
return { basePath: '', globPattern: pattern };
}
// Split into base path and glob pattern
const basePath = segments.slice(0, firstGlobIndex).join('/');
const globPattern = segments.slice(firstGlobIndex).join('/');
return { basePath, globPattern };
}
private async searchFiles(
dirPath: string,
pattern: string
): Promise<Array<{ path: string; mtime: number }>> {
const results: Array<{ path: string; mtime: number }> = [];
// Parse the glob pattern into segments
const segments = pattern.split('/');
await this.searchRecursive(dirPath, dirPath, segments, 0, results);
return results;
}
private async searchRecursive(
basePath: string,
currentPath: string,
segments: string[],
segmentIndex: number,
results: Array<{ path: string; mtime: number }>
): Promise<void> {
// If we've matched all segments, we're done
if (segmentIndex >= segments.length) {
return;
}
const segment = segments[segmentIndex];
try {
const entries = await this.fs.readdir(currentPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(currentPath, entry.name);
// Handle ** (recursive wildcard)
if (segment === '**') {
// ** can match zero or more directories
if (entry.isDirectory()) {
// Continue matching with ** at current level
await this.searchRecursive(basePath, entryPath, segments, segmentIndex, results);
}
// Try matching the next segment
if (segmentIndex + 1 < segments.length) {
if (this.matchesPattern(entry.name, segments[segmentIndex + 1])) {
if (segmentIndex + 2 === segments.length) {
// This is the final match
if (entry.isFile()) {
const stats = await this.fs.stat(entryPath);
const mtime = stats.mtimeMs || 0;
results.push({ path: entryPath, mtime });
}
} else {
// Continue matching subsequent segments
if (entry.isDirectory()) {
await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 2, results);
}
}
}
}
} else if (this.matchesPattern(entry.name, segment)) {
// Regular segment match
if (segmentIndex === segments.length - 1) {
// This is the final segment - add matching files
if (entry.isFile()) {
const stats = await this.fs.stat(entryPath);
const mtime = stats.mtimeMs || 0;
results.push({ path: entryPath, mtime });
}
} else {
// More segments to match - continue into directories
if (entry.isDirectory()) {
await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 1, results);
}
}
}
}
} catch {
// Skip directories we can't read
return;
}
}
private matchesPattern(filename: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.')
.replace(/\*\*/g, '\u00A7\u00A7\u00A7')
.replace(/\*/g, '[^/]*')
.replace(/\u00A7\u00A7\u00A7/g, '.*')
.replace(/\?/g, '[^/]');
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filename);
}
}
-244
View File
@@ -1,244 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GrepParams {
pattern: string;
path?: string;
include?: string;
}
interface GrepToolOptions {
maxLineLength?: number;
resultLimit?: number;
}
export class GrepTool implements Tool<GrepParams> {
private fs: JSRuntimeFS;
private cwd: string;
private maxLineLength: number;
private resultLimit: number;
readonly description = `- Fast content search tool that works with any codebase size
- Searches file contents using regular expressions
- Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths and line numbers with at least one match sorted by modification time
- Use this tool when you need to find files containing specific patterns
- If you need to identify/count the number of matches within files, use the shell tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead`;
readonly inputSchema = z.object({
pattern: z.string().describe("The regex pattern to search for in file contents"),
path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."),
include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: GrepToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.maxLineLength = options?.maxLineLength || 2000;
this.resultLimit = options?.resultLimit || 100;
}
async execute(args: GrepParams): Promise<ToolResult> {
if (!args.pattern) {
throw new Error("pattern is required");
}
// If path is absolute, use it directly; otherwise join with cwd
const searchPath = args.path
? (args.path.startsWith('/') ? args.path : join(this.cwd, args.path))
: this.cwd;
try {
// Check if search path exists
const stats = await this.fs.stat(searchPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${searchPath}`);
}
// Create regex from pattern
let regex: RegExp;
try {
regex = new RegExp(args.pattern, 'g');
} catch {
throw new Error(`Invalid regex pattern: ${args.pattern}`);
}
// Perform the search
const matches = await this.searchFiles(searchPath, regex, args.include);
// Sort by modification time (most recent first)
matches.sort((a, b) => b.modTime - a.modTime);
// Truncate results if needed
const truncated = matches.length > this.resultLimit;
const finalMatches = truncated ? matches.slice(0, this.resultLimit) : matches;
if (finalMatches.length === 0) {
return { content: "No files found" };
}
// Format output
const outputLines = [`Found ${finalMatches.length} matches`];
let currentFile = "";
for (const match of finalMatches) {
if (currentFile !== match.path) {
if (currentFile !== "") {
outputLines.push("");
}
currentFile = match.path;
outputLines.push(`${match.path}:`);
}
const truncatedLineText =
match.lineText.length > this.maxLineLength
? match.lineText.substring(0, this.maxLineLength) + "..."
: match.lineText;
outputLines.push(` Line ${match.lineNum}: ${truncatedLineText}`);
}
if (truncated) {
outputLines.push("");
outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)");
}
return { content: outputLines.join("\n") };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Search for files containing the pattern
*/
private async searchFiles(
dirPath: string,
regex: RegExp,
includePattern?: string
): Promise<Array<{ path: string; lineNum: number; lineText: string; modTime: number }>> {
const results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = [];
await this.searchRecursive(dirPath, regex, includePattern, results);
return results;
}
/**
* Recursively search directories for pattern matches
*/
private async searchRecursive(
dirPath: string,
regex: RegExp,
includePattern: string | undefined,
results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
// Skip common directories that should be ignored
if (entry.name === 'node_modules' || entry.name === '.git') {
continue;
}
// Recursively search subdirectory
await this.searchRecursive(entryPath, regex, includePattern, results);
} else if (entry.isFile()) {
// Check if file matches include pattern
if (includePattern && !this.matchesIncludePattern(entry.name, includePattern)) {
continue;
}
// Search file content
const fileMatches = await this.searchFileContent(entryPath, regex);
results.push(...fileMatches);
}
}
} catch {
// Skip directories we can't read
return;
}
}
/**
* Search a single file for pattern matches
*/
private async searchFileContent(
filePath: string,
regex: RegExp
): Promise<Array<{ path: string; lineNum: number; lineText: string; modTime: number }>> {
try {
// Get file modification time
const stats = await this.fs.stat(filePath);
const modTime = stats.mtimeMs || 0;
// Read file content
const content = await this.fs.readFile(filePath, 'utf8');
const lines = content.split('\n');
const matches: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Reset regex lastIndex for global regex
regex.lastIndex = 0;
if (regex.test(line)) {
matches.push({
path: filePath,
lineNum: i + 1,
lineText: line,
modTime,
});
}
}
return matches;
} catch {
// Skip files we can't read (likely binary)
return [];
}
}
/**
* Check if a filename matches the include pattern
*/
private matchesIncludePattern(filename: string, includePattern: string): boolean {
// Handle brace expansion like "*.{ts,tsx}"
if (includePattern.includes('{') && includePattern.includes('}')) {
const braceStart = includePattern.indexOf('{');
const braceEnd = includePattern.indexOf('}');
const prefix = includePattern.substring(0, braceStart);
const suffix = includePattern.substring(braceEnd + 1);
const options = includePattern.substring(braceStart + 1, braceEnd).split(',');
return options.some(option => {
const fullPattern = prefix + option + suffix;
return this.matchesSimplePattern(filename, fullPattern);
});
}
return this.matchesSimplePattern(filename, includePattern);
}
/**
* Check if a filename matches a simple glob pattern
*/
private matchesSimplePattern(filename: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.') // Escape dots
.replace(/\*/g, '.*') // * matches anything
.replace(/\?/g, '.'); // ? matches single character
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filename);
}
}
-52
View File
@@ -1,52 +0,0 @@
import { z } from "zod";
import { nip19 } from 'nostr-tools';
import type { Tool, ToolResult } from "./Tool";
interface NostrDecodeParams {
value: string;
}
export class NostrDecodeTool implements Tool<NostrDecodeParams> {
readonly description = "Decode NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr, nsec) into their hex and structured data representations";
readonly inputSchema = z.object({
value: z.string()
.superRefine((val, ctx) => {
// Strip nostr: URI prefix if present (NIP-21)
const cleaned = val.startsWith('nostr:') ? val.slice(6) : val;
try {
nip19.decode(cleaned);
} catch {
ctx.addIssue({
code: 'custom',
message: `Invalid NIP-19 identifier: ${val}. Expected an npub, note, nprofile, nevent, naddr, or nsec string.`,
});
}
})
.describe(
'A NIP-19 bech32-encoded identifier to decode (npub1..., note1..., nprofile1..., nevent1..., naddr1...). Also accepts nostr: URI prefix (NIP-21).',
),
});
async execute(args: NostrDecodeParams): Promise<ToolResult> {
const { value } = args;
// Strip nostr: URI prefix if present (NIP-21)
const cleaned = value.startsWith('nostr:') ? value.slice(6) : value;
try {
const decoded = nip19.decode(cleaned);
// Reject nsec for security reasons
if (decoded.type === 'nsec') {
throw new Error('nsec identifiers should not be shared or decoded in this context for security reasons');
}
return { content: JSON.stringify(decoded, null, 2) };
} catch (error) {
throw new Error(`Error decoding NIP-19 value: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
-146
View File
@@ -1,146 +0,0 @@
import { z } from "zod";
import { nip19 } from 'nostr-tools';
import type { Tool, ToolResult } from "./Tool";
type NostrEncodeType = 'npub' | 'note' | 'nprofile' | 'nevent' | 'naddr';
interface NostrEncodeParams {
type: NostrEncodeType;
hex: string;
relays?: string[];
author?: string;
kind?: number;
identifier?: string;
}
const HEX_64_REGEX = /^[0-9a-f]{64}$/;
export class NostrEncodeTool implements Tool<NostrEncodeParams> {
readonly description = "Encode hex values into NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr)";
readonly inputSchema = z.object({
type: z.enum(['npub', 'note', 'nprofile', 'nevent', 'naddr'])
.describe(
'The NIP-19 entity type to encode: npub (public key), note (event id), nprofile (profile with relay hints), nevent (event with relay hints and author), naddr (addressable event coordinate)',
),
hex: z.string()
.describe(
'The hex string to encode. For npub/nprofile this is a 64-char hex public key. For note/nevent this is a 64-char hex event id. For naddr this is not used directly (use identifier instead), but should be set to the author pubkey.',
),
relays: z.array(z.string())
.optional()
.describe(
'Optional relay URL hints to attach. Used with nprofile, nevent, and naddr types.',
),
author: z.string()
.optional()
.describe(
'Optional author pubkey (64-char hex) to attach as a hint. Used with nevent type.',
),
kind: z.number()
.optional()
.describe(
'Event kind number. Required for naddr type.',
),
identifier: z.string()
.optional()
.describe(
'The "d" tag identifier for addressable events. Required for naddr type.',
),
}).superRefine((data, ctx) => {
// Validate hex for types that need it
if (['npub', 'note', 'nprofile', 'nevent'].includes(data.type)) {
if (!HEX_64_REGEX.test(data.hex)) {
ctx.addIssue({
code: 'custom',
path: ['hex'],
message: 'hex must be a 64-character lowercase hex string',
});
}
}
// Validate author hex if provided
if (data.author && !HEX_64_REGEX.test(data.author)) {
ctx.addIssue({
code: 'custom',
path: ['author'],
message: 'author must be a 64-character lowercase hex public key',
});
}
// Validate naddr-specific requirements
if (data.type === 'naddr') {
if (!HEX_64_REGEX.test(data.hex)) {
ctx.addIssue({
code: 'custom',
path: ['hex'],
message: 'For naddr, hex must be the 64-character lowercase hex author pubkey',
});
}
if (data.kind === undefined) {
ctx.addIssue({
code: 'custom',
path: ['kind'],
message: 'kind is required for naddr encoding',
});
}
if (data.identifier === undefined) {
ctx.addIssue({
code: 'custom',
path: ['identifier'],
message: 'identifier (d tag) is required for naddr encoding',
});
}
}
});
async execute(args: NostrEncodeParams): Promise<ToolResult> {
const { type, hex, relays, author, kind, identifier } = args;
try {
let encoded: string;
switch (type) {
case 'npub': {
encoded = nip19.npubEncode(hex);
break;
}
case 'note': {
encoded = nip19.noteEncode(hex);
break;
}
case 'nprofile': {
encoded = nip19.nprofileEncode({
pubkey: hex,
relays: relays || [],
});
break;
}
case 'nevent': {
encoded = nip19.neventEncode({
id: hex,
relays: relays || [],
author: author,
});
break;
}
case 'naddr': {
encoded = nip19.naddrEncode({
pubkey: hex,
kind: kind!,
identifier: identifier || '',
relays: relays || [],
});
break;
}
default:
throw new Error(`Unsupported encode type: ${type}`);
}
return { content: encoded };
} catch (error) {
throw new Error(`Error encoding to ${type}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
+1 -1
View File
@@ -59,7 +59,7 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
const defaultRelays = [
'wss://relay.ditto.pub',
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://relay.primal.net',
];
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more