Compare commits

..
Author SHA1 Message Date
Alex Gleason 1ae491dd81 Support .opencode/tools/ 2026-01-23 23:00:31 -06:00
86 changed files with 1689 additions and 4920 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="****************************************"
+3 -30
View File
@@ -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
+28 -8
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.
@@ -54,11 +50,35 @@ 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
#### Project-Specific Custom Tools
Shakespeare now supports loading custom tools from `.opencode/tools` within each project. This allows users to create project-specific functionality that the AI can use.
**How it works:**
1. Place tool files (`.ts` or `.js`) in `.opencode/tools/` relative to the project root
2. Tools use the OpenCode tool format: https://opencode.ai/docs/custom-tools/
3. Tools are automatically loaded and transformed using esbuild-wasm
4. Tools that fail to load are silently skipped
5. Tool naming: single exports use filename, multiple exports use `filename_exportname`
**Example tool:**
```typescript
// .opencode/tools/hello.ts
import { z } from 'zod';
export default {
description: "Say hello to someone",
args: {
name: z.string().describe("Name of the person to greet"),
},
async execute(args: { name: string }) {
return `Hello, ${args.name}!`;
},
};
```
#### Shell Commands
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
@@ -1099,7 +1119,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,
},
-7
View File
@@ -1,7 +0,0 @@
# Changelog
## [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
@@ -11,7 +11,7 @@
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval' blob:; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
<meta name="theme-color" content="#2b0037">
+691 -862
View File
File diff suppressed because it is too large. Load diff
+5 -6
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.1",
"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",
@@ -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",
-7
View File
@@ -1,7 +0,0 @@
# Changelog
## [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
+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();
})
+37 -41
View File
@@ -15,7 +15,6 @@ 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';
@@ -29,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 { VersionCheck } from '@/components/VersionCheck';
import AppRouter from './AppRouter';
@@ -55,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,
@@ -73,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}",
@@ -89,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
@@ -135,41 +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>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<VersionCheck />
<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>
-2
View File
@@ -23,7 +23,6 @@ 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() {
return (
@@ -50,7 +49,6 @@ 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 />} />
+31 -24
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';
@@ -64,8 +63,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 +84,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;
@@ -154,8 +157,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
setCustomRelayUrls('');
setCustomBlossomServers('');
onOpenChange(false);
};
@@ -195,8 +198,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
setCustomRelayUrls('');
setCustomBlossomServers('');
}}
>
<SelectTrigger>
@@ -246,7 +249,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 +260,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>
</>
) : (
<>
-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) {
-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}</>;
}
-12
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,6 @@ interface ProjectTitleMenuProps {
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
onApp: () => void;
isAnyLoading: boolean;
className?: string;
}
@@ -41,7 +39,6 @@ export function ProjectTitleMenu({
onDuplicate,
onDelete,
onProjectDetails,
onApp,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
@@ -101,15 +98,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}
+28 -17
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>
</>
) : (
<>
-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(
+30 -20
View File
@@ -15,6 +15,7 @@ import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useMCPTools } from '@/hooks/useMCPTools';
import { useProjectTools } from '@/hooks/useProjectTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
@@ -35,9 +36,6 @@ 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';
@@ -49,7 +47,6 @@ 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';
@@ -198,6 +195,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Fetch MCP tools
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
// Load project-specific tools from .opencode/tools
const projectTools = useProjectTools(cwd, config.esmUrl);
// Log project tools when they change
useEffect(() => {
const toolCount = Object.keys(projectTools).length;
if (toolCount > 0) {
console.log(`[ChatPane] Project tools loaded: ${Object.keys(projectTools).join(', ')}`);
}
}, [projectTools]);
// Separate built-in tools from MCP tools for clarity
const builtInTools = useMemo(() => {
const tools: Record<string, Tool<unknown>> = {
@@ -221,9 +229,6 @@ 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),
@@ -231,13 +236,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
websearch: new WebSearchTool(),
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
app: new AppTool(
fs,
cwd,
user?.signer,
user?.pubkey,
config.relayMetadata.relays.filter(r => r.write).map(r => r.url),
),
};
// Add generate_image tool if imageModel is configured
@@ -289,16 +287,21 @@ 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, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
// Combined tool executors (for SessionManager to call)
const customTools = useMemo(() => ({
...builtInTools,
...mcpToolWrappers,
}), [builtInTools, mcpToolWrappers]);
const customTools = useMemo(() => {
const combined = {
...builtInTools,
...projectTools,
...mcpToolWrappers,
};
console.log(`[ChatPane] Combined ${Object.keys(combined).length} custom tools (built-in: ${Object.keys(builtInTools).length}, project: ${Object.keys(projectTools).length}, MCP: ${Object.keys(mcpToolWrappers).length})`);
return combined;
}, [builtInTools, projectTools, mcpToolWrappers]);
// Convert tools to OpenAI format for AI provider
const tools = useMemo(() => {
@@ -309,11 +312,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
}
// Convert project-specific tools to OpenAI format
for (const [name, tool] of Object.entries(projectTools)) {
console.log(`[ChatPane] Converting project tool to OpenAI format: ${name}`);
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
}
// Add MCP tools (already in OpenAI format from useMCPTools)
Object.assign(result, mcpOpenAITools);
console.log(`[ChatPane] Total tools available to AI: ${Object.keys(result).length}`);
return result;
}, [builtInTools, mcpOpenAITools]);
}, [builtInTools, projectTools, mcpOpenAITools]);
// Keep-alive functionality to prevent tab throttling during AI processing
const { updateMetadata } = useKeepAlive({
-20
View File
@@ -28,7 +28,6 @@ import {
X,
Search,
Clipboard,
AppWindow,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
@@ -413,25 +412,6 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
};
}
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 {
-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>
);
}
-1
View File
@@ -35,7 +35,6 @@ export function UserMessage({ content }: UserMessageProps) {
// Detect "Added file: <filename>" pattern
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
console.log('fileAddedMatch', part, fileAddedMatch);
if (fileAddedMatch && fileAddedMatch[1]) {
const path = fileAddedMatch[1];
const filename = getFileName(path);
-67
View File
@@ -1,67 +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 the first item from the first section.
return entry.sections[0]?.items[0];
} 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;
}
+16 -262
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';
@@ -36,9 +33,6 @@ 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 +44,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,10 +82,7 @@ interface ShakespeareFormData {
}
interface NsiteFormData {
siteTitle: string;
siteDescription: string;
dTag: string;
siteType: 'named' | 'root';
nsec: string;
}
interface NetlifyFormData {
@@ -146,8 +120,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);
@@ -155,49 +127,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) {
const derivedSiteType = cfg.id === null ? 'root' : 'named';
setNsiteForm({
siteTitle: cfg.title ?? '',
siteDescription: cfg.description ?? '',
dTag: (cfg.id != null && cfg.id !== '') ? cfg.id : '',
siteType: derivedSiteType,
});
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: '',
siteType: 'named',
nsec: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
@@ -265,27 +200,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.siteType === 'named' && nsiteForm.dTag
? nsiteForm.dTag
: undefined,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider;
@@ -394,29 +319,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,
siteType: nsiteForm.siteType,
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.siteType === 'root' ? null : (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',
@@ -464,53 +369,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
}
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 {
@@ -524,14 +382,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '', siteType: 'named' });
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();
};
@@ -543,21 +399,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 handleNsiteSiteTypeChange = useCallback((siteType: 'named' | 'root') => {
setNsiteForm(prev => ({ ...prev, siteType }));
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
@@ -606,87 +449,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 isRoot = nsiteVfsConfig.id === null;
const siteLabel = isRoot
? 'Root site'
: nsiteVfsConfig.id
? `Named site: ${nsiteVfsConfig.id}`
: 'Named site';
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">Type</span>
<span className="font-medium">{siteLabel}</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 savedSiteType = nsiteVfsConfig
? (nsiteVfsConfig.id === null ? 'root' : 'named')
: legacy?.siteType;
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}
savedSiteType={savedSiteType}
onSiteTitleChange={handleNsiteSiteTitleChange}
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
onSiteTypeChange={handleNsiteSiteTypeChange}
/>
{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}
/>
);
}
@@ -946,22 +717,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" />
@@ -976,8 +731,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !user) ||
(selectedProvider.type === 'nsite' && nsiteForm.siteType === 'named' && !nsiteForm.dTag) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
+77 -150
View File
@@ -1,180 +1,107 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Globe, Tag } 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 { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
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 for named sites */
projectName: string;
/** Persisted values from a previous deployment */
savedSiteTitle?: string;
savedSiteDescription?: string;
savedSiteType?: 'named' | 'root';
/** 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;
onSiteTypeChange: (type: 'named' | 'root') => void;
onNsecChange: (nsec: string) => void;
}
export function NsiteDeployForm({
projectName,
savedSiteTitle,
savedSiteDescription,
savedSiteType,
gateway,
savedNsec,
onSiteTitleChange,
onSiteDescriptionChange,
onSiteTypeChange,
onNsecChange,
}: NsiteDeployFormProps) {
const [siteType, setSiteType] = useState<'named' | 'root'>(savedSiteType ?? 'named');
const [siteTitle, setSiteTitle] = useState(
savedSiteTitle ?? (savedSiteType === 'root' ? '' : 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 (savedSiteType) onSiteTypeChange(savedSiteType);
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
const initialTitle = savedSiteTitle ?? (siteType === 'named' ? projectName : '');
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
onSiteTitleChange(initialTitle);
}, [savedSiteType, savedSiteDescription, savedSiteTitle, siteType, siteTitle, projectName, onSiteTypeChange, onSiteDescriptionChange, onSiteTitleChange]);
const [nsec, setNsec] = useState(savedNsec || '');
const [npub, setNpub] = useState('');
const initialized = useRef(false);
// Initialize nsec on mount
useEffect(() => {
stableSyncToParent();
}, [stableSyncToParent]);
// When the user switches site type, update the title default only if
// the current title still matches the previous type's auto-fill value.
const prevSiteTypeRef = useRef(siteType);
useEffect(() => {
const prev = prevSiteTypeRef.current;
prevSiteTypeRef.current = siteType;
if (prev === siteType) return;
if (siteType === 'named' && siteTitle === '') {
setSiteTitle(projectName);
onSiteTitleChange(projectName);
} else if (siteType === 'root' && siteTitle === projectName) {
setSiteTitle('');
onSiteTitleChange('');
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);
}
}
}, [siteType, siteTitle, projectName, onSiteTitleChange]);
}, [savedNsec, nsec, onNsecChange]);
const handleSiteTypeChange = (value: 'named' | 'root') => {
setSiteType(value);
onSiteTypeChange(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 handleSiteTitleChange = (value: string) => {
setSiteTitle(value);
onSiteTitleChange(value);
const handleGenerateNew = () => {
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
};
const handleSiteDescriptionChange = (value: string) => {
setSiteDescription(value);
onSiteDescriptionChange(value);
};
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
return (
<div className="space-y-4">
{/* Migration notice */}
{savedNsec && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Site identity is changing.</strong> This project was previously deployed with a
dedicated private key. Going forward, it will deploy under your Nostr identity. The old
site will remain at its original address until overwritten.
</AlertDescription>
</Alert>
)}
{/* Site type */}
<div className="space-y-2">
<Label>Site Type</Label>
<RadioGroup
value={siteType}
onValueChange={handleSiteTypeChange}
className="space-y-2"
>
<div className="flex items-start gap-3 p-3 rounded-md border cursor-pointer hover:bg-muted/50 transition-colors">
<RadioGroupItem value="named" id="nsite-type-named" className="mt-0.5" />
<label htmlFor="nsite-type-named" className="flex-1 cursor-pointer">
<div className="flex items-center gap-2 font-medium text-sm">
<Tag className="h-3.5 w-3.5" />
Named site
</div>
<p className="text-xs text-muted-foreground mt-0.5">
A site with a unique identifier. You can have many named sites.
</p>
</label>
</div>
<div className="flex items-start gap-3 p-3 rounded-md border cursor-pointer hover:bg-muted/50 transition-colors">
<RadioGroupItem value="root" id="nsite-type-root" className="mt-0.5" />
<label htmlFor="nsite-type-root" className="flex-1 cursor-pointer">
<div className="flex items-center gap-2 font-medium text-sm">
<Globe className="h-3.5 w-3.5" />
Root site
</div>
<p className="text-xs text-muted-foreground mt-0.5">
Your personal site at your npub address. You can only have one.
</p>
</label>
</div>
</RadioGroup>
</div>
{/* Root site warning */}
{siteType === 'root' && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You only have one root site per Nostr identity. Deploying here will replace any
existing root site published under your key.
</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>
+11 -19
View File
@@ -54,28 +54,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 +96,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" />;
}
@@ -21,7 +21,6 @@ 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 {
@@ -58,7 +57,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(() => {
@@ -171,15 +169,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 +176,6 @@ export function ConfigureRepoStep({
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags,
webUrls,
});
// Publish the event
-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 {
-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,
};
}
},
+1 -9
View File
@@ -15,15 +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 */
/** 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). Absent → root site (kind 15128). */
dTag: z.string().optional(),
/** 'named' | 'root'. Absent on legacy configs — treated as 'named' by the form. */
siteType: z.enum(['named', 'root']).optional(),
nsec: z.string(),
}),
});
+43
View File
@@ -0,0 +1,43 @@
import { useEffect, useState } from 'react';
import { useFS } from './useFS';
import { loadProjectTools } from '@/lib/tools/project-tools-loader';
import type { Tool } from '@/lib/tools/Tool';
/**
* Hook to load project-specific tools from .opencode/tools directory
*/
export function useProjectTools(projectPath: string, esmUrl: string): Record<string, Tool<unknown>> {
const { fs } = useFS();
const [tools, setTools] = useState<Record<string, Tool<unknown>>>({});
useEffect(() => {
let mounted = true;
async function load() {
console.log(`[useProjectTools] Loading tools for project: ${projectPath}`);
try {
// Use static IDs since project tools don't need to be session-specific
const loadedTools = await loadProjectTools(fs, projectPath, 'shakespeare', 'project-tools', esmUrl);
if (mounted) {
const toolCount = Object.keys(loadedTools).length;
console.log(`[useProjectTools] Setting ${toolCount} tool(s) in state`);
setTools(loadedTools);
} else {
console.log(`[useProjectTools] Component unmounted, not setting tools`);
}
} catch (error) {
console.error('[useProjectTools] Failed to load project tools:', error);
}
}
load();
return () => {
mounted = false;
};
}, [fs, projectPath, esmUrl]);
console.log(`[useProjectTools] Current tools in state: ${Object.keys(tools).length} tool(s) - ${Object.keys(tools).join(', ')}`);
return tools;
}
-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;
}
+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', () => {
-29
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);
-104
View File
@@ -1,104 +0,0 @@
import git from 'isomorphic-git';
import { DotAI } from './DotAI';
import { NostrURI } from './NostrURI';
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
}
}
return {
content: JSON.stringify(content),
tags,
};
}
-12
View File
@@ -287,18 +287,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();
-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 };
+2 -2
View File
@@ -208,7 +208,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
};
} catch (error) {
if (error instanceof z.ZodError) {
console.error('AI settings parsing error:', error.issues);
console.error('AI settings parsing error:', error.errors);
}
return defaultSettings;
}
@@ -329,7 +329,7 @@ export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'
return deploySettingsSchema.parse(data);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('Deploy settings parsing error:', error.issues);
console.error('Deploy settings parsing error:', error.errors);
}
return defaultSettings;
}
+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) });
}
}
+1 -14
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 {
-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');
}
-1
View File
@@ -83,7 +83,6 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
title: t('aboutShakespeare'),
href: '/settings/about',
},
],
},
];
-2
View File
@@ -45,8 +45,6 @@ const testConfig: AppConfig = {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
describe('makeSystemPrompt', () => {
+2 -27
View File
@@ -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:**
@@ -193,7 +191,6 @@ 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.
## Working Around CORS Issues
@@ -275,29 +272,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;
+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'),
-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',
];
@@ -11,15 +11,6 @@ vi.mock('nostr-tools', () => ({
id: 'test-event-id-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
sig: 'test-signature-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
})),
nip19: {
decode: vi.fn((value: string) => {
if (value.startsWith('nsec1')) {
return { type: 'nsec', data: new Uint8Array(32).fill(2) };
}
throw new Error('Invalid nip19 value');
}),
nsecEncode: vi.fn(() => 'nsec1testkey'),
},
}));
// Mock NPool to avoid actual network calls
+6 -19
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify';
import { generateSecretKey, getPublicKey, finalizeEvent, nip19 } from 'nostr-tools';
import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools';
import type { Tool, ToolResult } from "./Tool";
@@ -12,11 +12,10 @@ interface NostrPublishEventsParams {
created_at?: number;
}>;
relays?: string[];
nsec?: string;
}
export class NostrPublishEventsTool implements Tool<NostrPublishEventsParams> {
readonly description = "Publish Nostr events using an ephemeral keypair. All events in a single call are signed by the same ephemeral pubkey. You should include a kind 0 (profile metadata) event in the events array to give the publisher an identity. If no kind 0 is provided, a generic one will be created automatically as a fallback. To reuse the same identity across calls, pass the nsec returned from a previous call.";
readonly description = "Publish Nostr events using an ephemeral keypair. All events in a single call are signed by the same ephemeral pubkey. You should include a kind 0 (profile metadata) event in the events array to give the publisher an identity. If no kind 0 is provided, a generic one will be created automatically as a fallback.";
readonly inputSchema = z.object({
events: z.array(
@@ -28,34 +27,23 @@ export class NostrPublishEventsTool implements Tool<NostrPublishEventsParams> {
})
).min(1).describe('Array of partial Nostr events to publish. Include a kind 0 event to set profile metadata.'),
relays: z.array(z.string().url()).optional().describe('Optional array of relay URLs to publish to (default: hardcoded relay list)'),
nsec: z.string().startsWith('nsec1').optional().describe('Optional nsec (bech32-encoded secret key) to reuse a keypair from a previous call. If omitted, a new ephemeral keypair is generated.'),
});
async execute(args: NostrPublishEventsParams): Promise<ToolResult> {
const { events: partialEvents, relays, nsec } = args;
const { events: partialEvents, relays } = args;
// Default relays if none provided
const defaultRelays = [
'wss://relay.ditto.pub',
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://relay.primal.net',
];
const targetRelays = relays && relays.length > 0 ? relays : defaultRelays;
// Use provided nsec or generate a new ephemeral keypair
let secretKey: Uint8Array;
if (nsec) {
const decoded = nip19.decode(nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec: expected an nsec1-encoded secret key');
}
secretKey = decoded.data;
} else {
secretKey = generateSecretKey();
}
// Generate ephemeral keypair
const secretKey = generateSecretKey();
const pubkey = getPublicKey(secretKey);
const nsecEncoded = nip19.nsecEncode(secretKey);
// Check if user provided a kind 0 event
const hasKind0 = partialEvents.some((e) => e.kind === 0);
@@ -117,7 +105,6 @@ export class NostrPublishEventsTool implements Tool<NostrPublishEventsParams> {
const summary = {
success: true,
pubkey,
nsec: nsecEncoded,
events_published: allEvents.length,
relays: targetRelays,
events: allEvents.map((e) => ({
+5 -5
View File
@@ -22,7 +22,7 @@ describe('openai-adapter', () => {
expect(result.type).toBe('function');
expect(result.function.name).toBe('test_tool');
expect(result.function.description).toBe('Test tool');
expect(result.function.parameters).toMatchObject({
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
message: {
@@ -50,7 +50,7 @@ describe('openai-adapter', () => {
const result = toolToOpenAI('user_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toMatchObject({
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
user: {
@@ -92,7 +92,7 @@ describe('openai-adapter', () => {
const result = toolToOpenAI('todo_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toMatchObject({
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
todos: {
@@ -137,7 +137,7 @@ describe('openai-adapter', () => {
const result = toolToOpenAI('test_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toMatchObject({
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
required: {
@@ -182,7 +182,7 @@ describe('openai-adapter', () => {
const result = toolToOpenAI('priority_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toMatchObject({
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
priority: {
+123 -1
View File
@@ -15,7 +15,7 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
};
if (tool.inputSchema) {
functionDef.parameters = tool.inputSchema.toJSONSchema();
functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema);
} else {
functionDef.parameters = { type: "object", properties: {} };
}
@@ -25,3 +25,125 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
function: functionDef
};
}
/**
* Convert a Zod schema to JSON Schema format for OpenAI
*/
function zodSchemaToJsonSchema(schema: unknown): Record<string, unknown> {
// This is a simplified conversion. For a full implementation,
// you might want to use a library like zod-to-json-schema
const schemaObj = schema as { _def?: { typeName?: string; shape?: () => Record<string, unknown> } };
if (schemaObj._def?.typeName === 'ZodObject') {
const properties: Record<string, unknown> = {};
const required: string[] = [];
const shape = schemaObj._def.shape?.();
if (shape) {
for (const [key, value] of Object.entries(shape)) {
const fieldSchema = value as { _def?: { typeName?: string } };
properties[key] = convertZodField(fieldSchema);
if (!fieldSchema._def?.typeName?.includes('Optional')) {
required.push(key);
}
}
}
return {
type: 'object',
properties,
required: required.length > 0 ? required : undefined
};
}
return { type: 'object' };
}
/**
* Convert individual Zod field to JSON Schema
*/
function convertZodField(field: unknown): Record<string, unknown> {
const fieldObj = field as {
_def?: {
typeName?: string;
description?: string;
checks?: Array<{ kind: string; value: unknown }>;
innerType?: unknown;
type?: unknown;
shape?: () => Record<string, unknown>;
values?: unknown[];
}
};
const typeName = fieldObj._def?.typeName;
switch (typeName) {
case 'ZodString':
return {
type: 'string',
description: fieldObj._def?.description
};
case 'ZodNumber':
return {
type: 'number',
description: fieldObj._def?.description,
minimum: fieldObj._def?.checks?.find((c) => c.kind === 'min')?.value
};
case 'ZodBoolean':
return {
type: 'boolean',
description: fieldObj._def?.description
};
case 'ZodOptional': {
const innerSchema = convertZodField(fieldObj._def?.innerType);
// Preserve description from ZodOptional if it exists
if (fieldObj._def?.description && !innerSchema.description) {
innerSchema.description = fieldObj._def.description;
}
return innerSchema;
}
case 'ZodArray':
return {
type: 'array',
items: convertZodField(fieldObj._def?.type),
description: fieldObj._def?.description
};
case 'ZodObject': {
const properties: Record<string, unknown> = {};
const required: string[] = [];
const shape = fieldObj._def?.shape?.();
if (shape) {
for (const [key, value] of Object.entries(shape)) {
const fieldSchema = value as { _def?: { typeName?: string } };
properties[key] = convertZodField(fieldSchema);
if (!fieldSchema._def?.typeName?.includes('Optional')) {
required.push(key);
}
}
}
return {
type: 'object',
properties,
required: required.length > 0 ? required : undefined,
description: fieldObj._def?.description
};
}
case 'ZodEnum': {
const values = fieldObj._def?.values as string[] | undefined;
return {
type: 'string',
enum: values || [],
description: fieldObj._def?.description
};
}
default:
return {
type: 'string',
description: fieldObj._def?.description || ''
};
}
}
+102
View File
@@ -0,0 +1,102 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { loadProjectTools } from './project-tools-loader';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock esbuild-wasm to avoid initialization issues in test environment
vi.mock('esbuild-wasm', async () => ({
initialize: vi.fn().mockResolvedValue(undefined),
transform: vi.fn().mockResolvedValue({ code: '' }),
}));
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('loadProjectTools', () => {
let mockFS: JSRuntimeFS;
const projectPath = '/projects/test-project';
const sessionID = 'test-session';
const messageID = 'test-message';
const esmUrl = 'https://esm.sh';
beforeEach(() => {
mockFS = createMockFS();
});
it('should return empty object when .opencode/tools directory does not exist', async () => {
// Mock stat to throw error (directory doesn't exist)
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT'));
const tools = await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
expect(tools).toEqual({});
expect(mockFS.stat).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
});
it('should return empty object when .opencode/tools is not a directory', async () => {
// Mock stat to return a file instead of directory
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
size: 100,
mtimeMs: Date.now(),
});
const tools = await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
expect(tools).toEqual({});
expect(mockFS.stat).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
});
it('should return empty object when .opencode/tools directory is empty', async () => {
// Mock stat to return directory
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock readdir to return no files
vi.mocked(mockFS.readdir).mockResolvedValue([]);
const tools = await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
expect(tools).toEqual({});
expect(mockFS.readdir).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
});
it('should filter out non-tool files', async () => {
// Mock stat to return directory
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock readdir to return various file types
vi.mocked(mockFS.readdir).mockResolvedValue([
'tool.ts',
'tool.js',
'README.md',
'config.json',
'data.txt',
]);
// For simplicity, we won't test actual tool loading here since it requires esbuild
// Just verify the filtering logic
await loadProjectTools(mockFS, projectPath, sessionID, messageID, esmUrl);
// Tools object should be empty because we didn't mock readFile
// but the important thing is that it tried to process .ts and .js files
expect(mockFS.readdir).toHaveBeenCalledWith(`${projectPath}/.opencode/tools`);
});
});
+257
View File
@@ -0,0 +1,257 @@
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { Tool, ToolResult } from './Tool';
import { z } from 'zod';
import { getEsbuild } from '@/lib/esbuild';
import { esmPlugin } from '@/lib/build/esmPlugin';
import { fsPlugin } from '@/lib/build/fsPlugin';
// OpenCode tool definition types
interface OpenCodeToolContext {
sessionID: string;
messageID: string;
agent: string;
abort: AbortSignal;
metadata(input: { title?: string; metadata?: Record<string, unknown> }): void;
ask(input: {
permission: string;
patterns: string[];
always: string[];
metadata: Record<string, unknown>;
}): Promise<void>;
}
interface OpenCodeToolDefinition {
description: string;
args: Record<string, z.ZodType>;
execute(args: unknown, context: OpenCodeToolContext): Promise<string>;
}
/**
* Bundle a tool file using esbuild with esmPlugin and fsPlugin
*/
async function bundleTool(
code: string,
filename: string,
fs: JSRuntimeFS,
projectPath: string,
esmUrl: string
): Promise<string> {
try {
const esbuild = await getEsbuild();
const result = await esbuild.build({
stdin: {
contents: code,
sourcefile: filename,
loader: filename.endsWith('.ts') ? 'ts' : 'js',
},
bundle: true,
format: 'esm',
platform: 'browser',
target: 'es2020',
write: false,
plugins: [
fsPlugin({ fs, cwd: projectPath }),
esmPlugin({
packageJson: { dependencies: {} },
esmUrl
}),
],
});
if (!result.outputFiles || result.outputFiles.length === 0) {
throw new Error('No output from esbuild');
}
return result.outputFiles[0].text;
} catch (error) {
console.warn(`Failed to bundle ${filename}:`, error);
throw error;
}
}
/**
* Load and execute a tool module
*/
async function loadToolModule(
bundledCode: string,
filename: string
): Promise<Record<string, OpenCodeToolDefinition> | null> {
try {
// Create a blob URL for the module
const blob = new Blob([bundledCode], { type: 'application/javascript' });
const url = URL.createObjectURL(blob);
try {
// Dynamically import the module
const module = await import(/* @vite-ignore */ url);
return module as Record<string, OpenCodeToolDefinition>;
} finally {
// Clean up the blob URL
URL.revokeObjectURL(url);
}
} catch (error) {
console.warn(`Failed to load tool module ${filename}:`, error);
return null;
}
}
/**
* Convert an OpenCode tool to Shakespeare's tool format
*/
function convertOpenCodeTool(
name: string,
openCodeTool: OpenCodeToolDefinition,
sessionID: string,
messageID: string
): Tool<unknown> {
return {
description: openCodeTool.description,
inputSchema: z.object(openCodeTool.args),
async execute(args: unknown): Promise<ToolResult> {
// Create a minimal context for the OpenCode tool
const context: OpenCodeToolContext = {
sessionID,
messageID,
agent: 'shakespeare',
abort: new AbortController().signal,
metadata: () => {}, // No-op for now
ask: async () => {}, // No-op for now
};
try {
const result = await openCodeTool.execute(args, context);
return {
content: result,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: `Error executing tool ${name}: ${errorMessage}`,
};
}
},
};
}
/**
* Load project-specific tools from .opencode/tools directory
*/
export async function loadProjectTools(
fs: JSRuntimeFS,
projectPath: string,
sessionID: string,
messageID: string,
esmUrl: string
): Promise<Record<string, Tool<unknown>>> {
const tools: Record<string, Tool<unknown>> = {};
const toolsDir = `${projectPath}/.opencode/tools`;
console.log(`[Project Tools] Scanning for tools in: ${toolsDir}`);
try {
// Check if .opencode/tools directory exists
try {
const stat = await fs.stat(toolsDir);
if (!stat.isDirectory()) {
console.log('[Project Tools] Path exists but is not a directory');
return tools;
}
} catch {
// Directory doesn't exist
console.log('[Project Tools] Directory does not exist, skipping');
return tools;
}
// Get list of tool files (*.ts and *.js)
const files = await fs.readdir(toolsDir);
const toolFiles = files.filter(
(file) => file.endsWith('.ts') || file.endsWith('.js')
);
console.log(`[Project Tools] Found ${toolFiles.length} tool file(s): ${toolFiles.join(', ')}`);
if (toolFiles.length === 0) {
console.log('[Project Tools] No tool files found');
return tools;
}
// Load and bundle each tool file
for (const file of toolFiles) {
const toolPath = `${toolsDir}/${file}`;
const namespace = file.replace(/\.(ts|js)$/, '');
console.log(`[Project Tools] Loading tool file: ${file}`);
try {
// Read the tool file
const code = await fs.readFile(toolPath, 'utf8');
console.log(`[Project Tools] Read ${code.length} bytes from ${file}`);
// Bundle the tool with proper dependency resolution
console.log(`[Project Tools] Bundling ${file}...`);
const bundledCode = await bundleTool(code, file, fs, projectPath, esmUrl);
console.log(`[Project Tools] Bundled to ${bundledCode.length} bytes`);
// Load and execute the bundled module
console.log(`[Project Tools] Loading module from ${file}...`);
const module = await loadToolModule(bundledCode, file);
if (!module) {
console.warn(`[Project Tools] Failed to load module from ${file}`);
continue;
}
console.log(`[Project Tools] Module loaded, extracting exports from ${file}`);
// Extract tools from the module
let exportCount = 0;
for (const [exportName, toolDef] of Object.entries(module)) {
if (!toolDef || typeof toolDef !== 'object') {
console.debug(`[Project Tools] Skipping non-object export "${exportName}" in ${file}`);
continue;
}
const openCodeTool = toolDef as OpenCodeToolDefinition;
// Validate that it looks like an OpenCode tool
if (
!openCodeTool.description ||
!openCodeTool.args ||
!openCodeTool.execute
) {
console.debug(`[Project Tools] Skipping invalid tool export "${exportName}" in ${file} (missing description, args, or execute)`);
continue;
}
// Determine the tool name
const toolName =
exportName === 'default' ? namespace : `${namespace}_${exportName}`;
console.log(`[Project Tools] Registering tool: ${toolName} - ${openCodeTool.description}`);
// Convert and register the tool
tools[toolName] = convertOpenCodeTool(
toolName,
openCodeTool,
sessionID,
messageID
);
exportCount++;
}
console.log(`[Project Tools] Successfully loaded ${exportCount} tool(s) from ${file}`);
} catch (error) {
// Log errors for debugging but don't fail the entire load
console.warn(`[Project Tools] Failed to load tool ${file}:`, error);
}
}
const toolCount = Object.keys(tools).length;
console.log(`[Project Tools] ✓ Loaded ${toolCount} custom tool(s) total: ${Object.keys(tools).join(', ')}`);
} catch (error) {
// Log errors for debugging
console.error('[Project Tools] Error loading project tools:', error);
}
return tools;
}
-113
View File
@@ -1,113 +0,0 @@
/**
* Utilities for the nsite v2 deployment spec.
*/
/** Max length of a valid nsite dTag — must fit as a DNS label component */
const DTAG_MAX_LENGTH = 13;
/**
* Valid nsite dTag pattern:
* - 1–13 lowercase alphanumeric characters or hyphens
* - Must start and end with an alphanumeric character (valid DNS label)
* - No consecutive hyphens
*
* Examples: "myblog", "my-blog", "site-2"
*/
const DTAG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
/**
* Convert a project name into a valid nsite dTag identifier.
*
* Strategy:
* 1. Lowercase, replace spaces/underscores/dots with hyphens, strip everything else.
* 2. Collapse consecutive hyphens, strip leading/trailing hyphens.
* 3. If the result is 1–13 chars and valid → use it directly.
* 4. If too long → truncate to 13, then strip any trailing hyphens.
* 5. If the result is empty (name had no alphanumeric content) →
* SHA-256 hash the original name and take the first 13 hex digits.
* This is fully deterministic: the same project name always produces the same dTag.
*
* The hash fallback produces lowercase hex (`[0-9a-f]`), which satisfies the dTag rules.
*/
export async function projectNameToDTag(name: string): Promise<string> {
const slug = name
.toLowerCase()
.replace(/[\s_./]+/g, '-') // spaces, underscores, dots → hyphens
.replace(/[^a-z0-9-]/g, '') // strip everything else
.replace(/-{2,}/g, '-') // collapse consecutive hyphens
.replace(/^-+|-+$/g, '') // strip leading/trailing hyphens
.slice(0, DTAG_MAX_LENGTH)
.replace(/-+$/g, ''); // re-strip trailing hyphens after truncation
if (slug.length >= 1) {
return slug;
}
// Name had no usable alphanumeric content — hash for a short, stable identifier
const encoded = new TextEncoder().encode(name);
const buf = await crypto.subtle.digest('SHA-256', encoded);
const hex = Array.from(new Uint8Array(buf))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
return hex.slice(0, DTAG_MAX_LENGTH);
}
/**
* Validate that a string is an acceptable nsite dTag.
* - 1–13 characters
* - Lowercase alphanumeric and hyphens only
* - Must start and end with an alphanumeric character (valid DNS label)
*/
export function isValidDTag(value: string): boolean {
return value.length >= 1 && value.length <= DTAG_MAX_LENGTH && DTAG_REGEX.test(value);
}
/**
* Encode a 32-byte pubkey (as hex string) into a 50-character lowercase base36 string.
* Used to build named-site subdomain URLs: `{base36pubkey}{dTag}.{gateway}`
*
* Ported from nsite.run/apps/spa/src/lib/base36.js
*/
export function pubkeyToBase36(pubkeyHex: string): string {
// hex → Uint8Array
const bytes = new Uint8Array(32);
for (let i = 0; i < 32; i++) {
bytes[i] = parseInt(pubkeyHex.slice(i * 2, i * 2 + 2), 16);
}
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
const BASE = 36n;
let value = 0n;
for (let i = 0; i < bytes.length; i++) {
value = (value << 8n) | BigInt(bytes[i]);
}
const digits: string[] = [];
while (value > 0n) {
digits.push(ALPHABET[Number(value % BASE)]);
value = value / BASE;
}
return digits.reverse().join('').padStart(50, '0');
}
/**
* Build the deployed URL for an nsite.
*
* - Named site (kind 35128): `https://{base36pubkey}{dTag}.{gateway}`
* - Root site (kind 15128): `https://{npub}.{gateway}`
*/
export function buildNsiteUrl(opts: {
pubkeyHex: string;
npub: string;
gateway: string;
siteIdentifier?: string;
}): string {
const { pubkeyHex, npub, gateway, siteIdentifier } = opts;
if (siteIdentifier) {
const base36 = pubkeyToBase36(pubkeyHex);
return `https://${base36}${siteIdentifier}.${gateway}`;
}
return `https://${npub}.${gateway}`;
}
+2 -7
View File
@@ -59,11 +59,6 @@
"temporaryDirectory": "Temporary",
"sentryDsn": "Sentry DSN",
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"plausibleAnalytics": "Plausible Analytics",
"plausibleDomain": "Domain",
"plausibleDomainDescription": "The domain to track with Plausible Analytics. Leave empty to disable analytics.",
"plausibleEndpoint": "API Endpoint",
"plausibleEndpointDescription": "Custom Plausible API endpoint for self-hosted instances. Leave empty to use Plausible Cloud's default endpoint.",
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"systemPrompt": "System Prompt",
@@ -239,8 +234,6 @@
"aboutShakespeareDescription": "Information about Shakespeare",
"mirrors": "Mirrors",
"mirrorsDescription": "Shakespeare is available at multiple mirror URLs for redundancy and accessibility.",
"changelog": "Changelog",
"changelogDescription": "See what's new in each release of Shakespeare.",
"sourceCode": "Source Code",
"description": "Description",
"license": "License",
@@ -539,6 +532,8 @@
"deleting": "Deleting...",
"restoreToDefault": "Restore to default",
"restoredToDefault": "Restored to Default",
"templateUpdateFailed": "Template Update Failed",
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
"templatesDirectory": "Templates",
"terminal": "Terminal",
"templateName": "Template Name",
-2
View File
@@ -267,8 +267,6 @@
"aboutShakespeareDescription": "Bayani game da Shakespeare.",
"mirrors": "Madubai",
"mirrorsDescription": "Shakespeare yana samuwa a URLs masu yawa don inganci da samun dama.",
"changelog": "Tarihin Canje-canje",
"changelogDescription": "Duba abubuwan da suka canja a kowane sigar Shakespeare.",
"sourceCode": "Lambar Tushe",
"description": "Bayanin",
"license": "Lasisi",
-2
View File
@@ -267,8 +267,6 @@
"aboutShakespeareDescription": "Ozi gbasara Shakespeare.",
"mirrors": "Enyo",
"mirrorsDescription": "Shakespeare dị na ọtụtụ URL enyo maka nnọchi na nnweta.",
"changelog": "Ndekọ Mgbanwe",
"changelogDescription": "Lee ihe ọhụrụ n'ụdị ọ bụla nke Shakespeare.",
"sourceCode": "Koodu Isi",
"description": "Nkọwa",
"license": "Ikike",
-2
View File
@@ -276,8 +276,6 @@
"aboutShakespeareDescription": "Informações sobre o Shakespeare.",
"mirrors": "Espelhos",
"mirrorsDescription": "Shakespeare está disponível em vários URLs espelhados para redundância e acessibilidade.",
"changelog": "Registro de alterações",
"changelogDescription": "Veja as novidades em cada versão do Shakespeare.",
"sourceCode": "Código-fonte",
"description": "Descrição",
"license": "Licença",
-2
View File
@@ -267,8 +267,6 @@
"aboutShakespeareDescription": "Alaye nipa Shakespeare.",
"mirrors": "Awọn Digi",
"mirrorsDescription": "Shakespeare wa ni awọn URL digi pupọ fun aredundan ati iraye si.",
"changelog": "Akọsilẹ Ayipada",
"changelogDescription": "Wo ohun tuntun ninu ẹya kọọkan ti Shakespeare.",
"sourceCode": "Koodu Orisun",
"description": "Apejuwe",
"license": "Iwe-aṣẹ",
-2
View File
@@ -276,8 +276,6 @@
"aboutShakespeareDescription": "关于Shakespeare的信息。",
"mirrors": "镜像",
"mirrorsDescription": "Shakespeare可通过多个镜像URL访问,以确保冗余和可访问性。",
"changelog": "更新日志",
"changelogDescription": "查看Shakespeare每个版本的更新内容。",
"sourceCode": "源代码",
"description": "描述",
"license": "许可证",
+4 -21
View File
@@ -1,7 +1,6 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Info, ExternalLink, Loader2, AlertTriangle, Code, Globe, ScrollText } from 'lucide-react';
import { Info, ExternalLink, Loader2, AlertTriangle, Code, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
@@ -98,22 +97,6 @@ export function AboutSettings() {
</AccordionItem>
</Accordion>
{/* Changelog */}
<Card>
<CardContent className="p-0">
<Button
variant="ghost"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<Link to="/changelog">
<ScrollText className="!size-5 text-muted-foreground" />
{t('changelog')}
</Link>
</Button>
</CardContent>
</Card>
{/* Project Information */}
<Card>
<CardContent className="p-0">
@@ -165,9 +148,9 @@ export function AboutSettings() {
</div>
{import.meta.env.VERSION && (
<Link to="/changelog" className="block text-center text-[11px] text-muted-foreground/50 hover:text-muted-foreground transition-colors select-none pt-4 pb-2">
v{import.meta.env.VERSION}{import.meta.env.COMMIT_TAG ? '' : '+'} ({new Date(import.meta.env.BUILD_DATE).toLocaleDateString()})
</Link>
<div className="text-center text-xs text-muted-foreground/60 pt-4">
v{import.meta.env.VERSION}
</div>
)}
</SettingsPageLayout>
);
-317
View File
@@ -1,317 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSeoMeta } from '@unhead/react';
import { Bug, FlaskConical, Minus, Package, Plus, RefreshCw, ScrollText, ShieldAlert } from 'lucide-react';
import { AppLayout } from '@/components/AppLayout';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { parseChangelog } from '@/lib/changelog';
import type { ChangelogCategory, ChangelogEntry } from '@/lib/changelog';
const GITLAB_REPO = 'https://gitlab.com/soapbox-pub/shakespeare';
/** Per-category icon + color used as inline list bullets. */
const CATEGORY_STYLES: Record<ChangelogCategory, { icon: typeof Plus; colorClass: string }> = {
Added: { icon: Plus, colorClass: 'text-emerald-600 dark:text-emerald-400' },
Changed: { icon: RefreshCw, colorClass: 'text-blue-600 dark:text-blue-400' },
Deprecated: { icon: Package, colorClass: 'text-orange-600 dark:text-orange-400' },
Removed: { icon: Minus, colorClass: 'text-red-600 dark:text-red-400' },
Fixed: { icon: Bug, colorClass: 'text-amber-600 dark:text-amber-400' },
Security: { icon: ShieldAlert, colorClass: 'text-purple-600 dark:text-purple-400' },
};
/** Format "2026-03-26" as a readable date string. */
function formatDate(raw: string): string {
const date = new Date(raw + 'T00:00:00');
if (isNaN(date.getTime())) return raw;
return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
}
const commitSha = import.meta.env.COMMIT_SHA;
const commitTag = import.meta.env.COMMIT_TAG;
const buildDate = import.meta.env.BUILD_DATE;
const isPreRelease = !commitTag;
export function ChangelogPage() {
const [content, setContent] = useState<string | null>(null);
const [error, setError] = useState(false);
useSeoMeta({
title: 'Changelog | Shakespeare',
description: "What's new in Shakespeare",
});
useEffect(() => {
fetch('/CHANGELOG.md')
.then((res) => {
if (!res.ok) throw new Error(res.statusText);
return res.text();
})
.then(setContent)
.catch(() => setError(true));
}, []);
const entries = useMemo(() => (content ? parseChangelog(content) : []), [content]);
const latestVersion = entries[0]?.version;
return (
<AppLayout>
<div className="max-w-2xl mx-auto">
<div className="flex items-center gap-3 mb-6">
<ScrollText className="size-6 text-primary" />
<h1 className="text-2xl font-bold">Changelog</h1>
</div>
<div className="space-y-4">
{error ? (
<p className="text-sm text-muted-foreground pt-4">Failed to load changelog.</p>
) : content === null ? (
<ChangelogSkeleton />
) : entries.length === 0 ? (
<p className="text-sm text-muted-foreground pt-4">No releases yet.</p>
) : (
<>
{isPreRelease && latestVersion && <PreReleaseBanner latestVersion={latestVersion} />}
<LatestRelease entry={entries[0]} />
{entries.length > 1 && (
<>
<div className="flex items-center gap-3 pt-4 pb-1">
<div className="h-px flex-1 bg-border" />
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Past releases</span>
<div className="h-px flex-1 bg-border" />
</div>
{entries.slice(1).map((entry) => (
<ChangelogEntryCard key={entry.version} entry={entry} />
))}
</>
)}
</>
)}
</div>
</div>
</AppLayout>
);
}
/** Hero treatment for the most recent release — no card, centered version + date. */
function LatestRelease({ entry }: { entry: ChangelogEntry }) {
const contentRef = useRef<HTMLUListElement>(null);
const [overflows, setOverflows] = useState(false);
const [expanded, setExpanded] = useState(false);
const measure = useCallback(() => {
const el = contentRef.current;
if (el) setOverflows(el.scrollHeight > ENTRY_MAX_HEIGHT);
}, []);
useEffect(() => {
measure();
window.addEventListener('resize', measure);
return () => window.removeEventListener('resize', measure);
}, [measure]);
return (
<div className="pt-2 pb-1">
{/* Big centered version + date */}
<a
href={`${GITLAB_REPO}/-/releases/v${entry.version}`}
target="_blank"
rel="noopener noreferrer"
className="block text-center text-2xl font-bold tracking-tight hover:underline"
>
v{entry.version}
</a>
<a
href={`${GITLAB_REPO}/-/releases/v${entry.version}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors mt-1"
>
{formatDate(entry.date)}
</a>
{/* Items */}
<div className="relative mt-4">
<ul
ref={contentRef}
style={!expanded && overflows ? { maxHeight: ENTRY_MAX_HEIGHT, overflow: 'hidden' } : undefined}
className="space-y-2.5"
>
{entry.sections.flatMap((section) => {
const style = CATEGORY_STYLES[section.category] ?? CATEGORY_STYLES.Changed;
const Icon = style.icon;
return section.items.map((item, i) => (
<li key={`${section.category}-${i}`} className="flex gap-2 text-base text-foreground/90">
<Tooltip>
<TooltipTrigger asChild>
<Icon className={`size-4 shrink-0 mt-1 cursor-default ${style.colorClass}`} />
</TooltipTrigger>
<TooltipContent side="left">{section.category}</TooltipContent>
</Tooltip>
<span>{item}</span>
</li>
));
})}
</ul>
{!expanded && overflows && (
<div className="absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-background to-transparent pointer-events-none" />
)}
</div>
{overflows && (
<button
className="w-full text-sm text-primary hover:underline mt-1"
onClick={() => setExpanded((v) => !v)}
>
{expanded ? 'Show less' : 'Read more'}
</button>
)}
</div>
);
}
const ENTRY_MAX_HEIGHT = 240; // px — entries taller than this get a "Read more" button
/** A single changelog release card with truncation for long entries. */
function ChangelogEntryCard({ entry }: { entry: ChangelogEntry }) {
const contentRef = useRef<HTMLUListElement>(null);
const [overflows, setOverflows] = useState(false);
const [expanded, setExpanded] = useState(false);
const measure = useCallback(() => {
const el = contentRef.current;
if (el) setOverflows(el.scrollHeight > ENTRY_MAX_HEIGHT);
}, []);
useEffect(() => {
measure();
window.addEventListener('resize', measure);
return () => window.removeEventListener('resize', measure);
}, [measure]);
return (
<div className="rounded-2xl border border-border overflow-hidden">
{/* Version header */}
<div className="flex items-center gap-3 px-4 py-3">
<a
href={`${GITLAB_REPO}/-/releases/v${entry.version}`}
target="_blank"
rel="noopener noreferrer"
className="font-semibold text-sm hover:underline"
>
v{entry.version}
</a>
<a
href={`${GITLAB_REPO}/-/releases/v${entry.version}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors ml-auto"
>
<span>{formatDate(entry.date)}</span>
</a>
</div>
{/* Items */}
<div className="relative">
<ul
ref={contentRef}
style={!expanded && overflows ? { maxHeight: ENTRY_MAX_HEIGHT, overflow: 'hidden' } : undefined}
className="px-4 py-3 space-y-2.5"
>
{entry.sections.flatMap((section) => {
const style = CATEGORY_STYLES[section.category] ?? CATEGORY_STYLES.Changed;
const Icon = style.icon;
return section.items.map((item, i) => (
<li key={`${section.category}-${i}`} className="flex gap-2 text-sm text-foreground/90">
<Tooltip>
<TooltipTrigger asChild>
<Icon className={`size-3.5 shrink-0 mt-[3px] cursor-default ${style.colorClass}`} />
</TooltipTrigger>
<TooltipContent side="left">{section.category}</TooltipContent>
</Tooltip>
<span>{item}</span>
</li>
));
})}
</ul>
{!expanded && overflows && (
<div className="absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-background to-transparent pointer-events-none" />
)}
</div>
{overflows && (
<button
className="w-full text-sm text-primary hover:underline py-2"
onClick={() => setExpanded((v) => !v)}
>
{expanded ? 'Show less' : 'Read more'}
</button>
)}
</div>
);
}
/** Banner shown at the top of the changelog for untagged (pre-release) builds. */
function PreReleaseBanner({ latestVersion }: { latestVersion: string }) {
return (
<div className="rounded-2xl border border-dashed border-amber-500/50 bg-amber-50/50 dark:bg-amber-950/20 px-4 py-3 space-y-1.5">
<div className="flex items-center gap-2">
<FlaskConical className="size-4 text-amber-600 dark:text-amber-400 shrink-0" />
<span className="text-sm font-medium text-amber-800 dark:text-amber-300">Pre-release build</span>
{commitSha && buildDate && (
<a
href={`${GITLAB_REPO}/-/commit/${commitSha}`}
target="_blank"
rel="noopener noreferrer"
className="ml-auto text-[11px] text-amber-600/70 dark:text-amber-400/70 hover:text-amber-800 dark:hover:text-amber-300 transition-colors"
>
{formatDate(buildDate.split('T')[0])}
</a>
)}
</div>
<p className="text-xs text-amber-700/80 dark:text-amber-400/70">
This build contains changes not yet included in a release.{' '}
<a
href={`${GITLAB_REPO}/-/compare/v${latestVersion}...${commitSha || 'main'}`}
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-amber-900 dark:hover:text-amber-200 transition-colors"
>
View unreleased changes
</a>
</p>
</div>
);
}
function ChangelogSkeleton() {
return (
<div className="space-y-4 pt-1">
{[1, 2].map((i) => (
<div key={i} className="rounded-2xl border border-border overflow-hidden">
<div className="flex items-center gap-3 px-4 py-3">
<Skeleton className="size-4 rounded" />
<Skeleton className="h-4 w-16" />
<div className="ml-auto flex items-center gap-1.5">
<Skeleton className="size-3.5 rounded" />
<Skeleton className="h-3 w-24" />
</div>
</div>
<div className="px-4 py-3 space-y-2">
<Skeleton className="h-4 w-16 rounded-full" />
<Skeleton className="h-4 w-full ml-3" />
<Skeleton className="h-4 w-4/5 ml-3" />
<Skeleton className="h-4 w-3/5 ml-3" />
</div>
</div>
))}
</div>
);
}
export default ChangelogPage;
+1 -43
View File
@@ -87,48 +87,6 @@ export default function Clone() {
description: t('cloneGitRepository'),
});
/** Convert GitHub/GitLab web URLs to git clone URLs (append .git if needed). */
const normalizeGitUrl = (url: string): string => {
const trimmed = url.trim();
// Don't touch Nostr URIs or non-HTTP URLs
if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
return trimmed;
}
try {
const parsed = new URL(trimmed);
const host = parsed.hostname.toLowerCase();
// Only normalize GitHub and GitLab URLs
if (host !== 'github.com' && host !== 'gitlab.com' && !host.endsWith('.github.com') && !host.endsWith('.gitlab.com')) {
return trimmed;
}
// Strip trailing slash and common web UI suffixes
let pathname = parsed.pathname.replace(/\/+$/, '');
pathname = pathname.replace(/\/(tree|blob|commits|issues|merge_requests|pulls|releases|tags|branches|settings|pipelines|actions)(\/.*)?$/, '');
// Need at least /owner/repo
const segments = pathname.split('/').filter(Boolean);
if (segments.length < 2) {
return trimmed;
}
// Take only owner/repo (first two segments)
const repoPath = `/${segments[0]}/${segments[1]}`;
// Already ends with .git — keep as-is
if (repoPath.endsWith('.git')) {
return `${parsed.protocol}//${parsed.host}${repoPath}`;
}
return `${parsed.protocol}//${parsed.host}${repoPath}.git`;
} catch {
return trimmed;
}
};
const extractRepoName = async (url: string): Promise<string> => {
try {
const cleanUrl = url.trim();
@@ -179,7 +137,7 @@ export default function Clone() {
}, []);
const handleClone = useCallback(async (url?: string) => {
const targetUrl = normalizeGitUrl(url || repoUrl);
const targetUrl = url || repoUrl;
if (!targetUrl.trim()) {
setError(t('pleaseEnterRepositoryUrl'));
+1 -1
View File
@@ -208,9 +208,9 @@ export function DeploySettings() {
type: 'nsite',
gateway: 'nosto.re',
relayUrls: [
'wss://relay.ditto.pub',
'wss://relay.nsite.lol',
'wss://relay.nosto.re',
'wss://relay.nostr.band',
'wss://relay.primal.net',
'wss://relay.damus.io',
'wss://purplerelay.com',
+11
View File
@@ -24,8 +24,11 @@ import { ArrowUp } from 'lucide-react';
import { useSeoMeta } from '@unhead/react';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { AppShowcase } from '@/components/AppShowcase';
import { useToast } from '@/hooks/useToast';
export default function Index() {
const { t } = useTranslation();
const { toast } = useToast();
const [prompt, setPrompt] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
@@ -231,6 +234,14 @@ export default function Index() {
prompt.trim(),
template.url,
projectId,
() => {
// Show a toast if template update fails (non-critical)
toast({
title: t('templateUpdateFailed'),
description: t('templateUpdateFailedDescription'),
variant: 'default',
});
},
{ name: template.name, description: template.description }
);
-9
View File
@@ -8,7 +8,6 @@ import { PreviewPane } from '@/components/Shakespeare/PreviewPane';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { ProjectDetailsDialog } from '@/components/ProjectDetailsDialog';
import { DeleteProjectDialog } from '@/components/DeleteProjectDialog';
import { AppDialog } from '@/components/AppDialog';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
@@ -45,7 +44,6 @@ export function ProjectView() {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [appDialogOpen, setAppDialogOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
// Use console error state from provider
@@ -219,7 +217,6 @@ export function ProjectView() {
onDuplicate={() => setDuplicateDialogOpen(true)}
onDelete={() => setDeleteDialogOpen(true)}
onProjectDetails={() => setIsProjectDetailsOpen(true)}
onApp={() => setAppDialogOpen(true)}
isAnyLoading={isAnyLoading || isDeleting}
className="text-base"
/>
@@ -449,7 +446,6 @@ export function ProjectView() {
onDuplicate={() => setDuplicateDialogOpen(true)}
onDelete={() => setDeleteDialogOpen(true)}
onProjectDetails={() => setIsProjectDetailsOpen(true)}
onApp={() => setAppDialogOpen(true)}
isAnyLoading={isAnyLoading || isDeleting}
className="text-lg"
/>
@@ -561,11 +557,6 @@ export function ProjectView() {
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
/>
<AppDialog
projectId={project.id}
open={appDialogOpen}
onOpenChange={setAppDialogOpen}
/>
</>
)}
</div>
+1 -123
View File
@@ -1,4 +1,4 @@
import { Settings, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, BarChart3, FolderTree, Terminal as TerminalIcon, GitBranch } from "lucide-react";
import { Settings, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon, GitBranch } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
@@ -30,8 +30,6 @@ export function SystemSettings() {
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates);
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
const [plausibleDomainInput, setPlausibleDomainInput] = useState(config.plausibleDomain);
const [plausibleEndpointInput, setPlausibleEndpointInput] = useState(config.plausibleEndpoint);
// Check which settings differ from defaults
const isModified = useMemo(() => ({
@@ -48,8 +46,6 @@ export function SystemSettings() {
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates,
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
plausibleDomain: config.plausibleDomain !== defaultConfig.plausibleDomain,
plausibleEndpoint: config.plausibleEndpoint !== defaultConfig.plausibleEndpoint,
}), [config, defaultConfig]);
// Restore functions - clear the value from config to use the default
@@ -168,24 +164,6 @@ export function SystemSettings() {
});
};
const restorePlausibleDomain = () => {
const defaultValue = defaultConfig.plausibleDomain;
setPlausibleDomainInput(defaultValue);
updateConfig((current) => {
const { plausibleDomain, ...rest } = current;
return rest;
});
};
const restorePlausibleEndpoint = () => {
const defaultValue = defaultConfig.plausibleEndpoint;
setPlausibleEndpointInput(defaultValue);
updateConfig((current) => {
const { plausibleEndpoint, ...rest } = current;
return rest;
});
};
// Service Worker state
const [swState, setSwState] = useState<string>('');
const [isUpdatingSW, setIsUpdatingSW] = useState(false);
@@ -777,106 +755,6 @@ export function SystemSettings() {
</AccordionItem>
</Accordion>
{/* Plausible Analytics Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="plausible-analytics">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<BarChart3 className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('plausibleAnalytics')}</h4>
{(isModified.plausibleDomain || isModified.plausibleEndpoint) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="plausible-domain" className="text-sm font-medium">
{t('plausibleDomain')}
</Label>
{isModified.plausibleDomain && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="plausible-domain"
type="text"
placeholder="example.com"
value={plausibleDomainInput}
onChange={(e) => {
const value = e.target.value;
setPlausibleDomainInput(value);
updateConfig((current) => ({
...current,
plausibleDomain: value,
}));
}}
className="flex-1"
/>
{isModified.plausibleDomain && (
<Button
variant="outline"
size="icon"
onClick={restorePlausibleDomain}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('plausibleDomainDescription')}
</p>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="plausible-endpoint" className="text-sm font-medium">
{t('plausibleEndpoint')}
</Label>
{isModified.plausibleEndpoint && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="plausible-endpoint"
type="text"
placeholder="https://plausible.example.com/api/event"
value={plausibleEndpointInput}
onChange={(e) => {
const value = e.target.value;
setPlausibleEndpointInput(value);
updateConfig((current) => ({
...current,
plausibleEndpoint: value,
}));
}}
className="flex-1"
/>
{isModified.plausibleEndpoint && (
<Button
variant="outline"
size="icon"
onClick={restorePlausibleEndpoint}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('plausibleEndpointDescription')}
</p>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Filesystem Paths Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="filesystem-paths">
+1 -3
View File
@@ -31,7 +31,7 @@ export function TestApp({ children }: TestAppProps) {
theme: 'light',
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
@@ -65,8 +65,6 @@ export function TestApp({ children }: TestAppProps) {
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
plausibleDomain: '',
plausibleEndpoint: '',
};
// Initialize LightningFS for testing
+1 -12
View File
@@ -1,13 +1,2 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
interface ImportMetaEnv {
/** Marketing version from package.json (e.g., "9.9.0"). */
readonly VERSION: string;
/** ISO 8601 timestamp of when the app was built (e.g., "2026-04-02T19:42:00.000Z"). */
readonly BUILD_DATE: string;
/** Short git commit SHA (e.g., "c1266823"). Empty string if unavailable. */
readonly COMMIT_SHA: string;
/** Git tag for the current commit (e.g., "v9.9.0"). Empty string if untagged (pre-release build). */
readonly COMMIT_TAG: string;
}
/// <reference types="vite-plugin-pwa/client" />
+9 -24
View File
@@ -1,4 +1,3 @@
import { createRequire } from "node:module";
import { execSync } from "node:child_process";
import path from "node:path";
@@ -6,26 +5,15 @@ import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vitest/config";
import { VitePWA } from 'vite-plugin-pwa';
const require = createRequire(import.meta.url);
const pkg = require("./package.json") as { version: string };
/** Short commit SHA — prefer CI env var, fall back to git. */
function getCommitSha(): string {
if (process.env.CI_COMMIT_SHORT_SHA) return process.env.CI_COMMIT_SHORT_SHA;
function getVersion(): string {
try {
return execSync("git rev-parse --short HEAD", { encoding: "utf-8" }).trim();
const gitCommit = execSync('git rev-parse --short HEAD').toString().trim();
const commitTimestamp = execSync('git log -1 --format=%ct').toString().trim();
const commitDate = new Date(parseInt(commitTimestamp) * 1000);
const utcDate = commitDate.toISOString().split('T')[0].replace(/-/g, '.');
return `${utcDate}+${gitCommit}`;
} catch {
return "";
}
}
/** Git tag for the current commit — prefer CI env var, fall back to git. Empty string if untagged. */
function getCommitTag(): string {
if (process.env.CI_COMMIT_TAG) return process.env.CI_COMMIT_TAG;
try {
return execSync("git describe --exact-match --tags HEAD 2>/dev/null", { encoding: "utf-8" }).trim();
} catch {
return "";
return new Date().toISOString().split('T')[0].replace(/-/g, '.');
}
}
@@ -36,10 +24,7 @@ export default defineConfig(() => ({
port: 8080,
},
define: {
'import.meta.env.VERSION': JSON.stringify(pkg.version),
'import.meta.env.BUILD_DATE': JSON.stringify(new Date().toISOString()),
'import.meta.env.COMMIT_SHA': JSON.stringify(getCommitSha()),
'import.meta.env.COMMIT_TAG': JSON.stringify(getCommitTag()),
'import.meta.env.VERSION': JSON.stringify(getVersion()),
},
plugins: [
react(),
@@ -77,4 +62,4 @@ export default defineConfig(() => ({
"@": path.resolve(__dirname, "./src"),
},
},
}));
}));