Compare commits

..
166 changed files with 4587 additions and 12549 deletions

No files matched your search

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