Compare commits

...
37 Commits
Author SHA1 Message Date
Alex Gleason 717c4cc207 Add support for deploying to Cloudflare Pages 2025-11-15 11:54:55 -06:00
Alex Gleason a6caf93e8b Display "Push to Nostr" when origin URL is empty 2025-11-14 21:19:01 -06:00
Alex Gleason b55fd857e1 Treat Vite ?url imports as external ESM CDN links 2025-11-14 13:20:46 -06:00
Alex Gleason 65c51e865a Treat wasm import as binary, remove nonstandard import attribute on esbuild.wasm 2025-11-14 12:39:52 -06:00
Alex Gleason 8ecf460140 Don't redirect /assets/* in netlify redirects file 2025-11-13 22:11:32 -06:00
Alex Gleason 8ee4efdee3 Remove outdated soapbox.dev mirror 2025-11-13 21:23:12 -06:00
Alex Gleason 5ac5fcc212 systemPromptDescription: EJS -> Jinja-like 2025-11-13 20:07:08 -06:00
Alex Gleason 58c24f615d Swap out eta for nunjucks 2025-11-13 19:49:15 -06:00
Alex Gleason d1cbcda5d5 Minor simplifications to system prompt template 2025-11-13 19:27:45 -06:00
Alex Gleason c30ed35c67 Fix eta CSP issue, disable autoTrim 2025-11-13 19:20:53 -06:00
Alex Gleason dea364c2a6 Use esbuild worker, emit wasm file in build 2025-11-13 18:50:46 -06:00
Alex Gleason eabba1ecec Expose full config and defaultConfig to systemPrompt template 2025-11-13 18:12:45 -06:00
Alex Gleason db02b9fb94 Let system prompt be configurable in System Settings (EJS template) 2025-11-13 17:36:04 -06:00
DanConwayDev 4d88823c2d Improve toast message for new branch push 2025-11-13 16:41:48 -06:00
Alex Gleason 933530a96c Add Edit with Shakespeare scaling note to system prompt 2025-11-13 16:40:51 -06:00
DanConwayDev 43f4e0d15d Auto-switch to newly crated branch 2025-11-13 16:22:50 -06:00
DanConwayDev 21e522cba7 Fix git fetch handle deteled refs 2025-11-13 16:11:39 -06:00
Alex Gleason d8bfa10b43 Indicate non-default System Settings, allow clicking to restore to default 2025-11-13 16:10:19 -06:00
Alex Gleason 7a000a80f0 Add system prompt test 2025-11-13 15:55:52 -06:00
Alex Gleason 866155d907 Add "Edit with Shakespeare" info to system prompt 2025-11-13 15:39:18 -06:00
Alex Gleason 72439d4ec9 Merge branch 'fix/periods-in-name-break-deployment' into 'main'
fix/periods-in-name-break-deployment

See merge request soapbox-pub/shakespeare!70
2025-11-13 04:03:25 +00:00
sam 51f079696a detect and block deployment when the target contains periods 2025-11-13 10:53:52 +07:00
Alex Gleason abe3368115 Add error handling to favicon URL 2025-11-12 14:34:46 -06:00
Alex Gleason 16d357364d Add abort reasons to abort controllers 2025-11-12 14:24:41 -06:00
Alex Gleason 2d505588c7 Refactor Quilly to fix conditional hook usage 2025-11-12 14:01:46 -06:00
Alex Gleason a9ab551ca2 Sentry remove unnecessary mode fallback 2025-11-12 13:51:04 -06:00
DanConwayDev 075d6aba2d Fix git fetch default branch identification
calling remote via getRemoteInfo is not needed and results in null
for nostr remotes.

default branch is used here to trigger git fetch toast notifications

improved test coverage to test whether toast mis-fire when there is
no update
2025-11-12 13:42:18 -06:00
DanConwayDev a1f571b2d8 Fix git push publish state to repo relays
instead of hardcoded default
2025-11-12 13:40:06 -06:00
DanConwayDev d4eca86ec6 Fix retain prior state during git push to nostr remote
otherwise git push to a feature branch removes all other branches
including main and sets HEAD to feature branch.
2025-11-12 13:39:31 -06:00
DanConwayDev 44a208aed5 Fix don't unwrap symrefs in nostr remote
this was causing `refs/remotes/origin/HEAD` to be a commit id rather
than a symbolic reference like in the nostr state event
2025-11-12 13:38:51 -06:00
DanConwayDev ccc3613c83 Fix git status when branch not published
instead using status 'X commits ahead' it says 'Branch not published' and disables pull disabled.
2025-11-12 13:38:20 -06:00
Alex Gleason fd309e0aab Merge branch 'pr/fix-npm-run-electron(8edc8583)' 2025-11-12 13:36:27 -06:00
Alex Gleason 3d06e0cb57 Accumulate and persist total project cost and display in Project Details dialog 2025-11-12 12:09:42 -06:00
Alex Gleason dbf5cfe0a3 Make curl virtual command use configured corsProxy instead of hardcoded 2025-11-12 11:10:30 -06:00
Alex Gleason 0b66f81bfc Make "Push to Nostr" actually push without requiring another click to "Push" 2025-11-12 11:02:01 -06:00
Alex Gleason 35a85c18bd Add CORS proxy to system prompt 2025-11-11 18:03:21 -06:00
DanConwayDev 465bef91e8 fix npm run electron by generating package.json
The electron package.json needs to exist for this command to succeed.
If `prepare-electron-publish.js` has never been run then it hasn't been generated yet. Solution, run that everytime.
2025-11-03 11:35:20 +00:00
55 changed files with 3519 additions and 604 deletions

No files matched your search

-1
View File
@@ -34,7 +34,6 @@ Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The p
Shakespeare is available on the following URLs:
- [shakespeare.diy](https://shakespeare.diy)
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
+1 -1
View File
@@ -11,7 +11,7 @@
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
<meta name="theme-color" content="#2b0037">
+55
View File
@@ -68,6 +68,7 @@
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
@@ -105,6 +106,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
"@types/qrcode": "^1.5.5",
@@ -5603,6 +5605,13 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/nunjucks": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
"integrity": "sha512-pHiGtf83na1nCzliuAdq8GowYiXvH5l931xZ0YEHaLMNFgynpEqx+IPStlu7UaDkehfvl01e4x/9Tpwhy7Ue3w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/path-browserify": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@types/path-browserify/-/path-browserify-1.0.3.tgz",
@@ -6088,6 +6097,12 @@
"url": "https://opencollective.com/vitest"
}
},
"node_modules/a-sync-waterfall": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz",
"integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==",
"license": "MIT"
},
"node_modules/acorn": {
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
@@ -6257,6 +6272,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/asap": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"license": "MIT"
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -11685,6 +11706,40 @@
"integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==",
"license": "MIT"
},
"node_modules/nunjucks": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz",
"integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==",
"license": "BSD-2-Clause",
"dependencies": {
"a-sync-waterfall": "^1.0.0",
"asap": "^2.0.3",
"commander": "^5.1.0"
},
"bin": {
"nunjucks-precompile": "bin/precompile"
},
"engines": {
"node": ">= 6.9.0"
},
"peerDependencies": {
"chokidar": "^3.3.0"
},
"peerDependenciesMeta": {
"chokidar": {
"optional": true
}
}
},
"node_modules/nunjucks/node_modules/commander": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
"integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
"license": "MIT",
"engines": {
"node": ">= 6"
}
},
"node_modules/nwsapi": {
"version": "2.2.20",
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz",
+3 -1
View File
@@ -18,7 +18,7 @@
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && electron electron",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
},
"dependencies": {
@@ -81,6 +81,7 @@
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
@@ -118,6 +119,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
"@types/qrcode": "^1.5.5",
+2 -1
View File
@@ -1 +1,2 @@
/* /index.html 200
/assets/* /assets/:splat 200
/* /index.html 200
+1
View File
@@ -79,6 +79,7 @@ export function AppProvider(props: AppProviderProps) {
const appContextValue: AppContextType = {
config,
defaultConfig,
updateConfig,
};
+73 -2
View File
@@ -27,13 +27,14 @@ import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
/**
* Helper function to get provider URL for favicon
@@ -58,6 +59,12 @@ function getProviderUrl(provider: DeployProvider): string | null {
}
return 'https://vercel.com';
case 'cloudflare':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://cloudflare.com';
case 'nsite':
return null;
@@ -110,6 +117,11 @@ interface VercelFormData {
teamId: string;
}
interface CloudflareFormData {
projectName: string;
branch: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -124,6 +136,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
@@ -140,6 +153,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
projectName: projectName || projectId,
teamId: '',
});
const [cloudflareForm, setCloudflareForm] = useState<CloudflareFormData>({
projectName: projectName || projectId,
branch: 'main',
});
// Load project settings when dialog opens
useEffect(() => {
@@ -229,6 +246,24 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
projectName: vercelForm.projectName || undefined,
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
if (!cloudflareProvider.apiToken) {
throw new Error('Cloudflare API token is required');
}
if (!cloudflareProvider.accountId) {
throw new Error('Cloudflare Account ID is required');
}
adapter = new CloudflareAdapter({
fs,
apiToken: cloudflareProvider.apiToken,
accountId: cloudflareProvider.accountId,
baseURL: cloudflareProvider.baseURL,
projectName: cloudflareForm.projectName || undefined,
branch: cloudflareForm.branch || undefined,
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -268,6 +303,15 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
projectId: vercelForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'cloudflare') {
await updateProjectSettings(selectedProviderId, {
type: 'cloudflare',
data: {
projectName: cloudflareForm.projectName || undefined,
branch: cloudflareForm.branch || undefined,
projectId: result.metadata?.projectId as string | undefined,
},
});
}
setDeployResult(result);
@@ -287,6 +331,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId, branch: 'main' });
onOpenChange(false);
};
@@ -294,6 +339,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setShakespeareForm({ subdomain });
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
@@ -306,6 +355,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setVercelForm({ projectName, teamId });
}, []);
const handleCloudflareConfigChange = useCallback((projectName: string, branch: string) => {
setCloudflareForm({ projectName, branch });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -317,6 +370,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
/>
);
}
@@ -367,6 +421,22 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
);
}
if (selectedProvider.type === 'cloudflare') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined;
const savedBranch = savedConfig?.type === 'cloudflare' ? savedConfig.data.branch : undefined;
return (
<CloudflareDeployForm
projectId={projectId}
projectName={projectName}
savedProjectName={savedProjectName}
savedBranch={savedBranch}
onConfigChange={handleCloudflareConfigChange}
/>
);
}
return null;
};
@@ -495,6 +565,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
}
+21 -6
View File
@@ -1,6 +1,7 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
@@ -25,14 +26,28 @@ export function ExternalFavicon({
}: ExternalFaviconProps) {
const { config } = useAppContext();
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
// Generate the favicon URL using the configured template
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
const faviconSrc = useMemo(() => {
try {
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
return faviconUrl(config.faviconUrl, normalizedUrl);
} catch {
return;
}
}, [url, config.faviconUrl]);
// If faviconSrc is not available, render the fallback directly
if (!faviconSrc) {
return (
<span className={cn('inline-flex items-center justify-center', className)}>
<span>{fallback}</span>
</span>
)
}
return (
<span className={`inline-flex items-center justify-center ${className}`}>
<span className={cn('inline-flex items-center justify-center', className)}>
<img
src={faviconSrc}
alt=""
+54 -2
View File
@@ -25,6 +25,7 @@ const baseGitStatus = {
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
@@ -82,7 +83,16 @@ describe('GitDialog', () => {
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status', () => {
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -133,7 +143,17 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead', () => {
it('disables push button when no commits ahead and branch is published', () => {
// Mock git status with published branch and no commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -147,6 +167,38 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).toBeDisabled();
});
it('enables push and disables pull when branch is not published', () => {
// Mock git status with unpublished branch (has commits but no remote branch)
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: false,
totalCommits: 5,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Sync Status')).toBeInTheDocument();
expect(screen.getByText('Branch not published')).toBeInTheDocument();
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
const pullButton = screen.getByText('Pull');
expect(pullButton).toBeInTheDocument();
expect(pullButton.closest('button')).toBeDisabled();
});
it('does not show credentials warning when credentials are configured', () => {
render(
<TestApp>
+107 -64
View File
@@ -243,13 +243,23 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// Close the dialog before showing the toast
setNewBranchName('');
setIsCreateBranchDialogOpen(false);
// Show success toast indicating the branch was created and checked out
toast({
title: 'Branch created and checked out',
description: `Switched to new branch "${newBranchName.trim()}"`,
});
await loadBranches();
await refetchGitStatus();
} catch (error) {
@@ -446,50 +456,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
}
// Get HEAD reference
let headRef: string | undefined;
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
if (currentBranch) {
headRef = `ref: refs/heads/${currentBranch}`;
console.log(`HEAD points to: ${headRef}`);
} else {
// HEAD is detached, use the commit ID directly
const headValue = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
if (headValue) {
headRef = headValue;
console.log(`HEAD is detached at: ${headRef}`);
}
}
} catch (error) {
console.warn('Failed to resolve HEAD:', error);
}
// Create repo state event (NIP-34 kind 30618)
const stateEvent = {
kind: 30618,
content: '',
tags: [
['d', result.repoId],
...refTags,
...(headRef ? [['HEAD', headRef]] : []),
],
created_at: Math.floor(Date.now() / 1000),
};
console.log('Creating repository state event:', stateEvent);
// Sign and publish the state event
const signedStateEvent = await user.signer.signEvent(stateEvent);
// State events only go to the relays specified in the repo announcement
console.log('Publishing repository state to relays:', result.relays);
await nostr.event(signedStateEvent, { relays: result.relays });
console.log('Published repository state to Nostr relays');
console.log('Repository has refs:', refTags);
// Set origin remote to Nostr URL
// Format: nostr://<npub>/<repo-id>
@@ -522,13 +489,54 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
console.log('Set nostr.repo config to:', result.naddr);
toast({
title: 'Repository published to Nostr',
description: 'Waiting for GRASP servers to update...',
});
// Refresh git status to pick up the new remote
await refetchGitStatus();
// Automatically push to the newly configured Nostr remote
// Get the current branch fresh from git instead of using stale gitStatus
console.log('Starting automatic push to Nostr...');
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
console.log('Current branch:', currentBranch);
if (!currentBranch) {
throw new Error('No current branch found');
}
toast({
title: 'Repository published to Nostr',
description: 'Pushing commits to ngit servers...',
});
console.log('Calling git.push with:', { dir: projectPath, remote: 'origin', ref: currentBranch });
await git.push({
dir: projectPath,
remote: 'origin',
ref: currentBranch,
signer: user.signer,
});
console.log('Push completed successfully');
toast({
title: 'Push successful',
description: 'Repository successfully pushed to Nostr',
});
// Refresh git status after push
await refetchGitStatus();
} catch (pushError) {
console.error('Push error:', pushError);
const pushErrorMessage = pushError instanceof Error ? pushError.message : 'Unknown error occurred';
toast({
title: 'Automatic push failed',
description: pushErrorMessage,
variant: 'destructive',
duration: Infinity,
});
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
@@ -561,7 +569,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return;
}
if (gitStatus.ahead === 0) {
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
toast({
title: "Nothing to push",
description: "No commits ahead of remote. Commit your changes first.",
@@ -570,6 +579,16 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return;
}
// Ensure we have commits to push when publishing a new branch
if (!gitStatus.remoteBranchExists && gitStatus.totalCommits === 0) {
toast({
title: "Cannot publish branch",
description: "No commits to push. Commit your changes first.",
variant: "destructive",
});
return;
}
setIsPushing(true);
try {
@@ -583,11 +602,32 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
signer: user?.signer, // For signing if pushing to Nostr
});
// Set up upstream tracking if this is the first push for this branch
if (!gitStatus.remoteBranchExists) {
await git.setConfig({
dir: projectPath,
path: `branch.${gitStatus.currentBranch}.remote`,
value: remote.name,
});
await git.setConfig({
dir: projectPath,
path: `branch.${gitStatus.currentBranch}.merge`,
value: `refs/heads/${gitStatus.currentBranch}`,
});
}
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
});
// Show different messages for publishing new branches vs pushing commits
if (gitStatus.remoteBranchExists) {
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
});
} else {
toast({
title: "Branch published",
description: `New branch published to ${remote.name}/${gitStatus.currentBranch}`,
});
}
// Refresh git status after push
await refetchGitStatus();
@@ -683,8 +723,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
}
};
const getFileStatusIcon = (status: string) => {
switch (status) {
case 'added':
@@ -728,6 +766,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
}
// Check if remote branch doesn't exist
if (!gitStatus.remoteBranchExists && gitStatus.currentBranch) {
return { status: 'not-published', text: 'Branch not published', icon: AlertCircle, color: 'text-yellow-600' };
}
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
}
@@ -1095,11 +1138,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
)}
</div>
{gitStatus.remotes.length > 0 && (
{originUrl.trim() && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
variant="outline"
size="sm"
className="flex-1"
@@ -1114,7 +1157,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
variant="outline"
size="sm"
className="flex-1"
@@ -1129,7 +1172,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
</div>
)}
{gitStatus.remotes.length === 0 && user && (
{!originUrl.trim() && user && (
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
@@ -1142,7 +1185,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
) : (
<Zap className="h-4 w-4 mr-2" />
)}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
</Button>
)}
+30
View File
@@ -33,9 +33,11 @@ import {
Loader2,
Trash2,
Save,
DollarSign,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
import { DotAI } from '@/lib/DotAI';
interface ProjectDetailsDialogProps {
project: Project;
@@ -49,6 +51,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
const [isDeleting, setIsDeleting] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [newProjectName, setNewProjectName] = useState(project.id);
const [totalCost, setTotalCost] = useState<number | null>(null);
const { toast } = useToast();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -62,6 +65,24 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost
useEffect(() => {
const loadCost = async () => {
try {
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
const cost = await dotAI.readCost();
setTotalCost(cost);
} catch (error) {
console.warn('Failed to load project cost:', error);
setTotalCost(null);
}
};
if (open) {
loadCost();
}
}, [fs, projectsPath, project.id, open]);
const formatDistanceToNow = (date: Date) => {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
@@ -226,6 +247,15 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
<span>{formatDistanceToNow(project.lastModified)}</span>
</div>
{/* Total Cost */}
{totalCost !== null && totalCost > 0 && (
<div className="flex items-center gap-2 text-sm">
<DollarSign className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Total Cost:</span>
<span className="font-mono">${totalCost.toFixed(6)}</span>
</div>
)}
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="project-name">Project Name</Label>
+68 -24
View File
@@ -11,6 +11,7 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useState } from 'react';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
import { AIProvider } from '@/contexts/AISettingsContext';
export interface QuillyProps {
error: Error;
@@ -30,23 +31,20 @@ interface ErrorBody {
}>;
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
interface QuillyContentProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
onTryAgain?: () => void;
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
provider: AIProvider | undefined;
}
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
// Handle empty provider model gracefully
let provider;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
@@ -69,7 +67,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
onClick: onOpenModelSelector,
}],
};
}
}
if (error instanceof EmptyMessageError) {
return {
@@ -101,13 +99,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
case error.code === 'insufficient_quota': {
if (credits.data) {
// Only show credits dialog if we have a provider with nostr enabled
if (provider?.nostr) {
return {
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
actions: [{
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}],
message: 'Your account is low on credits. Please add credits to keep creating.',
showCreditsButton: true,
actions: [],
};
} else {
return {
@@ -204,7 +201,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
};
const { message, actions = [] } = renderBody(error);
const { message, actions = [], showCreditsButton } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
@@ -217,6 +214,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{actions.length > 0 && (
<>
{' '}
@@ -242,12 +245,53 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
<X className="h-4 w-4" />
</Button>
</div>
</div>
);
}
interface QuillyCreditsButtonProps {
provider: AIProvider;
}
function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const credits = useAICredits(provider);
return (
<>
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
</button>
<CreditsDialog
open={showCreditsDialog}
onOpenChange={setShowCreditsDialog}
provider={provider}
/>
</div>
</>
);
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const { settings } = useAISettings();
// Handle empty provider model gracefully
let provider: AIProvider | undefined;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
return (
<QuillyContent
error={error}
onDismiss={onDismiss}
onNewChat={onNewChat}
onOpenModelSelector={onOpenModelSelector}
onTryAgain={onTryAgain}
onRequestConsoleErrorHelp={onRequestConsoleErrorHelp}
provider={provider}
/>
);
}
+4 -4
View File
@@ -42,7 +42,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -78,7 +78,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -115,7 +115,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -155,7 +155,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
+62 -12
View File
@@ -1,12 +1,12 @@
import { ReactNode, useMemo, useEffect } from 'react';
import { ReactNode, useEffect, useRef } from 'react';
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
import { SessionManager } from '@/lib/SessionManager';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
interface SessionManagerProviderProps {
children: ReactNode;
@@ -17,30 +17,80 @@ interface SessionManagerProviderProps {
*/
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
const { fs } = useFS();
const { projectsPath, pluginsPath } = useFSPaths();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user, metadata } = useCurrentUser();
const { config } = useAppContext();
const { config, defaultConfig } = useAppContext();
const { nostr } = useNostr();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
// Create SessionManager instance only once
const sessionManager = useRef<SessionManager | undefined>(undefined);
// Use refs so SessionManager always has the latest data
const configRef = useRef(config);
const defaultConfigRef = useRef(defaultConfig);
const settingsRef = useRef(settings);
const modelsRef = useRef(models);
const userRef = useRef(user);
const metadataRef = useRef(metadata);
// Update refs when values change
useEffect(() => {
configRef.current = config;
}, [config]);
useEffect(() => {
defaultConfigRef.current = defaultConfig;
}, [defaultConfig]);
useEffect(() => {
settingsRef.current = settings;
}, [settings]);
useEffect(() => {
modelsRef.current = models;
}, [models]);
useEffect(() => {
userRef.current = user;
}, [user]);
useEffect(() => {
metadataRef.current = metadata;
}, [metadata]);
// Initialize SessionManager only once
if (!sessionManager.current) {
// Callbacks access refs to get latest values
const getProviderModels = () => modelsRef.current;
const getCurrentUser = () => ({ user: userRef.current, metadata: metadataRef.current });
const getConfig = () => configRef.current;
const getDefaultConfig = () => defaultConfigRef.current;
const getSettings = () => settingsRef.current;
sessionManager.current = new SessionManager(
fs,
nostr,
getSettings,
getConfig,
getDefaultConfig,
getProviderModels,
getCurrentUser,
);
}
// Cleanup on unmount
useEffect(() => {
return () => {
// Fire and forget cleanup - we don't need to await in useEffect cleanup
sessionManager.cleanup().catch(error => {
sessionManager.current?.cleanup().catch(error => {
console.warn('Failed to cleanup session manager:', error);
});
};
}, [sessionManager]);
}, []);
return (
<SessionManagerContext.Provider value={sessionManager}>
<SessionManagerContext.Provider value={sessionManager.current}>
{children}
</SessionManagerContext.Provider>
);
+2 -2
View File
@@ -166,7 +166,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
nostr_publish_events: new NostrPublishEventsTool(),
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
shell: new ShellTool(fs, cwd, git, projectsPath, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath),
};
@@ -180,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
+4 -2
View File
@@ -8,6 +8,7 @@ import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useGit } from '@/hooks/useGit';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
interface TerminalProps {
@@ -37,10 +38,11 @@ export function Terminal({ projectId, className }: TerminalProps) {
const { projectsPath } = useFSPaths();
const { git } = useGit();
const { user } = useCurrentUser();
const { config } = useAppContext();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, config.corsProxy, user?.signer);
// Add welcome message
setLines([{
@@ -49,7 +51,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
timestamp: new Date()
}]);
}, [projectId, fs, git, projectsPath, user?.signer]);
}, [projectId, fs, git, projectsPath, config.corsProxy, user?.signer]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
@@ -0,0 +1,55 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface CloudflareDeployFormProps {
projectId: string;
projectName?: string;
savedProjectName?: string;
savedBranch?: string;
onConfigChange: (projectName: string, branch: string) => void;
}
export function CloudflareDeployForm({
projectId,
projectName: initialProjectName,
savedProjectName,
savedBranch,
onConfigChange,
}: CloudflareDeployFormProps) {
const [projectName, setProjectName] = useState(savedProjectName || initialProjectName || projectId);
const [branch, setBranch] = useState(savedBranch || 'main');
useEffect(() => {
onConfigChange(projectName, branch);
}, [projectName, branch, onConfigChange]);
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="cloudflare-project-name">Project Name</Label>
<Input
id="cloudflare-project-name"
value={projectName}
onChange={(e) => setProjectName(e.target.value)}
placeholder={initialProjectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{projectName || projectId}.pages.dev</span>
</p>
</div>
<div className="space-y-2">
<Label htmlFor="cloudflare-branch">Branch Name</Label>
<Input
id="cloudflare-branch"
value={branch}
onChange={(e) => setBranch(e.target.value)}
placeholder="main"
/>
<p className="text-xs text-muted-foreground">
Production branch for your Cloudflare Pages project
</p>
</div>
</div>
);
}
@@ -1,24 +1,35 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { AlertCircle } from 'lucide-react';
interface ShakespeareDeployFormProps {
host?: string;
projectId: string;
onSubdomainChange: (subdomain: string) => void;
onValidationChange?: (isValid: boolean) => void;
}
export function ShakespeareDeployForm({
host = 'shakespeare.wtf',
projectId,
onSubdomainChange,
onValidationChange,
}: ShakespeareDeployFormProps) {
const [subdomain, setSubdomain] = useState(projectId);
// Validate subdomain: no periods allowed (only single-level subdomains)
const hasPeriod = subdomain.includes('.');
const isValid = subdomain.trim() !== '' && !hasPeriod;
useEffect(() => {
onSubdomainChange(subdomain);
}, [subdomain, onSubdomainChange]);
useEffect(() => {
onValidationChange?.(isValid);
}, [isValid, onValidationChange]);
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
return (
@@ -30,7 +41,14 @@ export function ShakespeareDeployForm({
value={subdomain}
onChange={(e) => setSubdomain(e.target.value)}
placeholder={projectId}
className={hasPeriod ? 'border-destructive' : ''}
/>
{hasPeriod && (
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
</div>
)}
<p className="text-xs text-muted-foreground">
Will deploy to: <span className="font-mono">{fullDomain}</span>
</p>
+13 -3
View File
@@ -187,13 +187,23 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// Close the dialog before showing the toast
setNewBranchName('');
setIsCreateDialogOpen(false);
// Show success toast indicating the branch was created and checked out
toast({
title: 'Branch created and checked out',
description: `Switched to new branch "${newBranchName.trim()}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
+4
View File
@@ -44,11 +44,15 @@ export interface AppConfig {
sentryDsn: string;
/** Whether the user has enabled Sentry error reporting */
sentryEnabled: boolean;
/** System prompt EJS template */
systemPrompt?: string;
}
export interface AppContextType {
/** Current application configuration */
config: AppConfig;
/** Default application configuration */
defaultConfig: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
}
+9 -1
View File
@@ -32,7 +32,15 @@ export interface NsiteProvider extends BaseDeployProvider {
blossomServers: string[];
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
export interface CloudflareProvider extends BaseDeployProvider {
type: 'cloudflare';
apiToken: string;
accountId: string;
baseURL?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider;
export interface DeploySettings {
providers: DeployProvider[];
+23 -21
View File
@@ -38,28 +38,30 @@ describe('useAIProjectId', () => {
});
// Mock useAppContext
mockUseAppContext.mockReturnValue({
config: {
theme: 'dark',
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://github.com/example/template',
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
const config = {
theme: 'dark' as const,
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://github.com/example/template',
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
+648 -23
View File
@@ -1,32 +1,24 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useGitFetch } from './useGitFetch';
import { TestApp } from '@/test/TestApp';
// Create mocks that can be reconfigured per test
const mockGit = {
findRoot: vi.fn(),
listRemotes: vi.fn(),
currentBranch: vi.fn(),
resolveRef: vi.fn(),
fetch: vi.fn(),
};
const mockToast = vi.fn();
const mockInvalidateQueries = vi.fn();
// Mock the git operations
vi.mock('./useGit', () => ({
useGit: () => ({
git: {
findRoot: vi.fn().mockResolvedValue('/projects/test-project'),
listRemotes: vi.fn().mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]),
currentBranch: vi.fn().mockResolvedValue('main'),
getRemoteInfo: vi.fn().mockResolvedValue({
refs: {
HEAD: {
type: 'symref',
target: 'refs/heads/main',
},
},
}),
resolveRef: vi.fn()
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('abc123') // before current
.mockResolvedValueOnce('abc123') // after default
.mockResolvedValueOnce('abc123'), // after current
fetch: vi.fn().mockResolvedValue(undefined),
},
git: mockGit,
}),
}));
@@ -44,7 +36,30 @@ vi.mock('./useFSPaths', () => ({
}),
}));
vi.mock('./useToast', () => ({
useToast: () => ({
toast: mockToast,
}),
}));
// Mock QueryClient to track invalidateQueries calls
vi.mock('@tanstack/react-query', async () => {
const actual = await vi.importActual('@tanstack/react-query');
return {
...actual,
useQueryClient: () => ({
invalidateQueries: mockInvalidateQueries,
}),
};
});
describe('useGitFetch', () => {
beforeEach(() => {
vi.clearAllMocks();
mockToast.mockClear();
mockInvalidateQueries.mockClear();
});
it('returns null state when projectId is null', async () => {
const { result } = renderHook(() => useGitFetch(null), {
wrapper: TestApp,
@@ -57,7 +72,28 @@ describe('useGitFetch', () => {
expect(result.current.isSuccess).toBe(false);
});
it('fetches remote updates successfully', async () => {
it('fetches remote updates successfully when default branch is checked out', async () => {
// Setup mocks for default branch scenario
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef calls in order:
// 1. Read symbolic ref for default branch (returns the ref path)
// 2. Get default branch OID before fetch
// 3. Get current branch OID before fetch
// 4. Get default branch OID after fetch
// 5. Get current branch OID after fetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('abc123') // before current (same as default)
.mockResolvedValueOnce('abc123') // after default
.mockResolvedValueOnce('abc123'); // after current (same as default)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
@@ -72,9 +108,207 @@ describe('useGitFetch', () => {
remoteUrl: 'https://github.com/test/repo.git',
hasChanges: false,
});
// Verify fetch was called
expect(mockGit.fetch).toHaveBeenCalledWith(
expect.objectContaining({
dir: '/projects/test-project',
remote: 'origin',
})
);
});
it('fetches remote updates successfully when non-default branch is checked out', async () => {
// Setup mocks for non-default branch scenario
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef calls in order:
// 1. Read symbolic ref for default branch (returns the ref path)
// 2. Get default branch OID before fetch
// 3. Get current branch OID before fetch
// 4. Get default branch OID after fetch
// 5. Get current branch OID after fetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default (main)
.mockResolvedValueOnce('def456') // before current (feature-branch)
.mockResolvedValueOnce('abc123') // after default (main)
.mockResolvedValueOnce('def456'); // after current (feature-branch)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
remoteUrl: 'https://github.com/test/repo.git',
hasChanges: false,
});
// Verify fetch was called
expect(mockGit.fetch).toHaveBeenCalledWith(
expect.objectContaining({
dir: '/projects/test-project',
remote: 'origin',
})
);
});
it('detects changes on default branch when checked out', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on default branch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('abc123') // before current (same as default)
.mockResolvedValueOnce('xyz789') // after default (changed!)
.mockResolvedValueOnce('xyz789'); // after current (changed!)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'main',
hasChanges: true, // Changes detected on default branch
});
});
it('detects changes on non-default branch when checked out', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on non-default branch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('def456') // before current
.mockResolvedValueOnce('abc123') // after default (no change)
.mockResolvedValueOnce('xyz789'); // after current (changed!)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
hasChanges: true, // Changes detected on current branch
});
});
it('detects changes on both default and non-default branches', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on both branches
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('def456') // before current
.mockResolvedValueOnce('new111') // after default (changed!)
.mockResolvedValueOnce('new222'); // after current (changed!)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
hasChanges: true, // Changes detected on both branches
});
});
it('detects changes on default branch when non-default branch is checked out', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on default branch only
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('def456') // before current
.mockResolvedValueOnce('xyz789') // after default (changed!)
.mockResolvedValueOnce('def456'); // after current (no change)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
hasChanges: true, // Changes detected on default branch
});
});
it('can be manually refetched', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef for initial fetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
@@ -85,11 +319,402 @@ describe('useGitFetch', () => {
const firstFetchTime = result.current.data?.fetchedAt;
// Setup mocks for refetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
// Manually trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
});
// Verify fetch was called twice (initial + refetch)
expect(mockGit.fetch).toHaveBeenCalledTimes(2);
});
describe('Toast Notifications', () => {
it('shows toast when default branch changes (on default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('xyz789') // Changed!
.mockResolvedValueOnce('xyz789');
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Verify toast message
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
expect(gitStatusCalls[0][0]).toEqual({
queryKey: ['git-status', 'test-project'],
});
});
it('shows toast when non-default branch changes (on non-default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes on feature branch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123') // main unchanged
.mockResolvedValueOnce('xyz789'); // feature-branch changed!
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Verify toast message for feature branch
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The feature-branch branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
expect(gitStatusCalls[0][0]).toEqual({
queryKey: ['git-status', 'test-project'],
});
});
it('shows toast when default branch changes (on non-default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes on main branch only
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('xyz789') // main changed!
.mockResolvedValueOnce('def456'); // feature-branch unchanged
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Verify toast message for main branch
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
expect(gitStatusCalls[0][0]).toEqual({
queryKey: ['git-status', 'test-project'],
});
});
it('shows two toasts when both branches change (on non-default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes on both branches
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('new111') // main changed!
.mockResolvedValueOnce('new222'); // feature-branch changed!
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(2);
});
// Verify both toast messages
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The feature-branch branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated twice (once per toast)
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(2);
});
it('does not show toast on initial load', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch with changes detected in the fetch itself
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('xyz789') // Changed from before to after fetch
.mockResolvedValueOnce('xyz789');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Should report changes in data
expect(result.current.data?.hasChanges).toBe(true);
// But no toast on initial load
expect(mockToast).not.toHaveBeenCalled();
});
it('does not show toast when no changes detected', async () => {
// Setup mocks for initial fetch
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Setup for refetch with no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast should be shown
expect(mockToast).not.toHaveBeenCalled();
// Verify git status was not invalidated (filter out other queries like 'nostr')
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(0);
});
it('does not show duplicate toast for same branch when default equals current', async () => {
// Setup mocks for initial fetch
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Setup for refetch with changes (both default and current are 'main')
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('xyz789')
.mockResolvedValueOnce('xyz789');
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Should only show one toast (for default branch), not two
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
// Should only invalidate once
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
});
});
});
+45 -18
View File
@@ -131,25 +131,31 @@ export function useGitFetch(projectId: string | null) {
let beforeDefaultOid: string | null = null;
let beforeCurrentOid: string | null = null;
// Get remote info to find default branch
// Get default branch from local symbolic ref
let defaultBranch: string | null = null;
try {
console.log('Fetching remote info...');
const remoteInfo = await git.getRemoteInfo({
url: remoteUrl,
...(credentials && {
onAuth: () => ({
username: credentials.username,
password: credentials.password,
}),
}),
});
console.log('Reading default branch from local symbolic ref...');
// Extract default branch from symbolic ref
if (remoteInfo.refs?.HEAD?.type === 'symref') {
const symref = remoteInfo.refs.HEAD.target;
defaultBranch = symref?.replace('refs/heads/', '') || null;
console.log('Default branch from remote:', defaultBranch);
// Read the symbolic ref file directly
// The file contains something like: "ref: refs/remotes/origin/main"
try {
const symbolicRefContent = await git.resolveRef({
dir: cwd,
ref: `remotes/${remote.remote}/HEAD`,
depth: 1,
});
// Remove "ref: " prefix and extract the branch name
// Content looks like: "ref: refs/remotes/origin/main"
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
if (match) {
defaultBranch = match[1].trim();
console.log('Default branch from local symbolic ref:', defaultBranch);
} else {
console.log('Could not get default branch from local symbolic ref value:', refValue);
}
} catch {
console.log('No local symbolic ref found, will be set after fetch');
}
// If we have a default branch, try to get its OID before fetch
@@ -165,7 +171,7 @@ export function useGitFetch(projectId: string | null) {
}
}
} catch (error) {
console.warn('Could not get remote info:', error);
console.warn('Could not read default branch from local data:', error);
}
// Get current branch OID before fetch
@@ -204,6 +210,27 @@ export function useGitFetch(projectId: string | null) {
let afterDefaultOid: string | null = null;
let afterCurrentOid: string | null = null;
// Re-read default branch from symbolic ref in case it was just created by fetch
if (!defaultBranch) {
try {
const symbolicRefContent = await git.resolveRef({
dir: cwd,
ref: `remotes/${remote.remote}/HEAD`,
depth: 1,
});
// Remove "ref: " prefix and extract the branch name
// Content looks like: "ref: refs/remotes/origin/main"
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
if (match) {
defaultBranch = match[1].trim();
console.log('Default branch from local symbolic ref:', defaultBranch);
}
} catch {
console.log('No local symbolic ref found, will be set after fetch');
}
}
if (defaultBranch) {
try {
afterDefaultOid = await git.resolveRef({
@@ -319,7 +346,7 @@ export function useGitFetch(projectId: string | null) {
if (currentBranchChanged && query.data.currentBranch) {
toast({
title: 'Remote changes detected',
description: `The ${query.data.currentBranch} branch has new commits available.`,
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
variant: 'default',
});
+11 -5
View File
@@ -38,6 +38,7 @@ interface GitStatus {
branches: string[];
ahead: number;
behind: number;
remoteBranchExists: boolean;
}
export function useGitStatus(projectId: string | null) {
@@ -59,6 +60,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -80,6 +82,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -200,6 +203,7 @@ export function useGitStatus(projectId: string | null) {
// Calculate ahead/behind
let ahead = 0;
let behind = 0;
let remoteBranchExists = false;
try {
if (currentBranch && remotes.length > 0) {
const remote = remotes[0]; // Use first remote (usually 'origin')
@@ -224,6 +228,9 @@ export function useGitStatus(projectId: string | null) {
ref: currentBranch,
});
// Remote branch exists!
remoteBranchExists = true;
if (remoteRef && localRef && remoteRef !== localRef) {
// Get commits between local and remote
const localCommits = await git.log({
@@ -247,11 +254,8 @@ export function useGitStatus(projectId: string | null) {
behind = remoteOnlyCommits.length;
}
} catch {
// Remote branch might not exist or other issues
// If we can't find remote branch, assume we're ahead if we have commits
if (totalCommits > 0) {
ahead = totalCommits;
}
// Remote branch doesn't exist
remoteBranchExists = false;
}
}
} catch (err) {
@@ -269,6 +273,7 @@ export function useGitStatus(projectId: string | null) {
branches,
ahead,
behind,
remoteBranchExists,
};
} catch (error) {
console.error('Error checking git status:', error);
@@ -283,6 +288,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
},
+4 -1
View File
@@ -49,7 +49,10 @@ export function useOAuth(config: OAuthConfig) {
const { corsProxy } = appConfig;
// Check if OAuth is configured
const isOAuthConfigured = !!(config.clientId && config.clientSecret);
// For PKCE flows (like Cloudflare), we only need clientId
const isOAuthConfigured = config.usePKCE
? !!config.clientId
: !!(config.clientId && config.clientSecret);
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
+10 -1
View File
@@ -31,7 +31,16 @@ export interface VercelProjectConfig {
};
}
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
export interface CloudflareProjectConfig {
type: 'cloudflare';
data: {
projectName?: string;
branch?: string;
projectId?: string;
};
}
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig;
export interface ProjectDeploySettings {
providers: Record<string, ProjectProviderConfig>;
+63
View File
@@ -260,4 +260,67 @@ invalid json line
expect(sessionName1).not.toBe(sessionName2);
});
});
describe('readCost', () => {
it('should return 0 when COST file does not exist', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
const cost = await dotAI.readCost();
expect(cost).toBe(0);
});
it('should read and parse cost from COST file', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('0.123456\n');
const cost = await dotAI.readCost();
expect(cost).toBe(0.123456);
});
it('should return 0 for invalid cost value', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('invalid\n');
const cost = await dotAI.readCost();
expect(cost).toBe(0);
});
it('should handle cost with whitespace', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue(' 0.050000 \n');
const cost = await dotAI.readCost();
expect(cost).toBe(0.05);
});
});
describe('writeCost', () => {
it('should create shakespeare directory if it does not exist', async () => {
await dotAI.writeCost(0.123456);
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/shakespeare', { recursive: true });
});
it('should write cost with 6 decimal places', async () => {
await dotAI.writeCost(0.123456789);
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.git/shakespeare/COST',
'0.123457\n'
);
});
it('should write zero cost correctly', async () => {
await dotAI.writeCost(0);
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.git/shakespeare/COST',
'0.000000\n'
);
});
it('should handle write errors gracefully', async () => {
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed'));
// Should not throw
await expect(dotAI.writeCost(0.123456)).resolves.toBeUndefined();
});
});
});
+34
View File
@@ -278,4 +278,38 @@ export class DotAI {
return null;
}
}
/**
* Read the accumulated cost from .git/shakespeare/COST file
* @returns The accumulated cost as a number, or 0 if the file doesn't exist
*/
async readCost(): Promise<number> {
try {
const costPath = join(this.workingDir, ".git", "shakespeare", "COST");
const content = await this.fs.readFile(costPath, "utf8");
const cost = parseFloat(content.trim());
return isNaN(cost) ? 0 : cost;
} catch {
return 0;
}
}
/**
* Write the accumulated cost to .git/shakespeare/COST file
* @param cost The accumulated cost in USD
*/
async writeCost(cost: number): Promise<void> {
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
const costPath = join(shakespeareDir, "COST");
try {
// Ensure .git/shakespeare directory exists
await this.fs.mkdir(shakespeareDir, { recursive: true });
// Write the cost with 6 decimal places for precision
await this.fs.writeFile(costPath, cost.toFixed(6) + "\n");
} catch (error) {
console.warn(`Failed to write .git/shakespeare/COST file: ${error}`);
}
}
}
+39 -1
View File
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { SessionManager, type AIMessage } from './SessionManager';
import type { JSRuntimeFS } from './JSRuntime';
import type { NPool } from '@nostrify/nostrify';
import type { AppConfig } from '@/contexts/AppContext';
// Mock the filesystem
const mockFS: JSRuntimeFS = {
@@ -22,6 +24,39 @@ const mockFS: JSRuntimeFS = {
realpath: vi.fn(),
} as unknown as JSRuntimeFS;
// Mock NPool
const mockNostr: NPool = {
query: vi.fn(),
req: vi.fn(),
event: vi.fn(),
} as unknown as NPool;
// Test configuration
const testConfig: AppConfig = {
theme: 'light',
relayMetadata: {
relays: [
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
language: 'en',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
};
describe('SessionManager', () => {
let sessionManager: SessionManager;
const mockAISettings = {
@@ -35,7 +70,10 @@ describe('SessionManager', () => {
};
beforeEach(() => {
sessionManager = new SessionManager(mockFS, mockAISettings);
const getSettings = () => mockAISettings;
const getConfig = () => testConfig;
const getDefaultConfig = () => testConfig;
sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig);
});
it('should initialize streaming message with reasoning content', async () => {
+77 -24
View File
@@ -11,6 +11,9 @@ import { NostrMetadata } from '@nostrify/nostrify';
import { MalformedToolCallError } from './errors/MalformedToolCallError';
import { EmptyMessageError } from './errors/EmptyMessageError';
import { isEmptyMessage } from './isEmptyMessage';
import { Git } from './git';
import type { NPool } from '@nostrify/nostrify';
import type { AppConfig } from '@/contexts/AppContext';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
@@ -58,29 +61,34 @@ export class SessionManager {
private sessions = new Map<string, SessionState>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private aiSettings: { providers: AIProvider[] };
private nostr: NPool;
private getSettings: () => { providers: AIProvider[] };
private getConfig: () => AppConfig;
private getDefaultConfig: () => AppConfig;
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
private corsProxy?: string;
private projectsPath: string;
private pluginsPath?: string;
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: AIProvider[] },
nostr: NPool,
getSettings: () => { providers: AIProvider[] },
getConfig: () => AppConfig,
getDefaultConfig: () => AppConfig,
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
corsProxy?: string,
projectsPath = '/projects',
pluginsPath?: string,
) {
this.fs = fs;
this.aiSettings = aiSettings;
this.nostr = nostr;
this.getSettings = getSettings;
this.getConfig = getConfig;
this.getDefaultConfig = getDefaultConfig;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
this.projectsPath = projectsPath;
this.pluginsPath = pluginsPath;
this.corsProxy = corsProxy;
}
private get git(): Git {
const config = this.getConfig();
return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy });
}
/**
@@ -97,7 +105,8 @@ export class SessionManager {
// Try to load existing history
try {
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
@@ -154,7 +163,7 @@ export class SessionManager {
*/
async deleteSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
session?.abortController?.abort();
session?.abortController?.abort('Session deleted');
this.sessions.delete(projectId);
@@ -209,14 +218,19 @@ export class SessionManager {
this.emit('loadingChanged', projectId, true);
try {
// Get latest config and settings
const config = this.getConfig();
const defaultConfig = this.getDefaultConfig();
const settings = this.getSettings();
// Parse provider and model
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const parsed = parseProviderModel(providerModel, settings.providers);
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user, this.corsProxy);
const openai = createAIClient(provider, user, config.corsProxy);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -238,16 +252,26 @@ export class SessionManager {
tool_calls: undefined
};
// Get repository URL if available
let repositoryUrl: string | undefined;
try {
const remoteUrl = await this.git.getRemoteURL(`${config.fsPathProjects}/${projectId}`, 'origin');
repositoryUrl = remoteUrl || undefined;
} catch {
// No repository URL available
}
const systemPrompt = await makeSystemPrompt({
cwd: `${this.projectsPath}/${projectId}`,
cwd: `${config.fsPathProjects}/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
pluginsPath: this.pluginsPath,
config,
defaultConfig,
user,
metadata,
repositoryUrl,
template: config.systemPrompt,
});
// Prepare messages for AI
@@ -480,7 +504,7 @@ export class SessionManager {
const session = this.sessions.get(projectId);
if (!session) return;
session.abortController?.abort();
session.abortController?.abort('User stopped generation');
session.isLoading = false;
session.streamingMessage = undefined;
session.abortController = undefined;
@@ -524,7 +548,7 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise<void> {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
@@ -534,12 +558,16 @@ export class SessionManager {
if (typeof usage.cost === 'number') {
session.totalCost = (session.totalCost || 0) + usage.cost;
this.emit('costUpdated', projectId, session.totalCost);
// Accumulate cost to project total
await this.accumulateProjectCost(projectId, usage.cost);
return;
}
// Otherwise, get the cost from the models endpoint
try {
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const settings = this.getSettings();
const parsed = parseProviderModel(providerModel, settings.providers);
const modelName = parsed.model;
const provider = parsed.provider;
@@ -563,6 +591,9 @@ export class SessionManager {
// Update session total cost
session.totalCost = (session.totalCost || 0) + requestCost;
this.emit('costUpdated', projectId, session.totalCost);
// Accumulate cost to project total
await this.accumulateProjectCost(projectId, requestCost);
} catch (error) {
console.warn('Failed to calculate session cost:', error);
}
@@ -576,13 +607,35 @@ export class SessionManager {
if (!session) return;
try {
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
await dotAI.setHistory(session.sessionName, session.messages);
} catch (error) {
console.warn('Failed to save session history:', error);
}
}
/**
* Accumulate request cost to the project's total cost file
*/
private async accumulateProjectCost(projectId: string, requestCost: number): Promise<void> {
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
// Read current project total
const currentTotal = await dotAI.readCost();
// Add this request's cost
const newTotal = currentTotal + requestCost;
// Write back the new total
await dotAI.writeCost(newTotal);
} catch (error) {
console.warn('Failed to accumulate project cost:', error);
}
}
/**
* Simplified event system
*/
+24 -8
View File
@@ -243,14 +243,12 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
// HACK: https://github.com/esm-dev/esm.sh/issues/1217
if (args.path === "yet-another-react-lightbox/styles.css") {
args.path = "yet-another-react-lightbox/dist/styles.css";
}
const [path, query] = args.path.split("?");
const params = new URLSearchParams(query);
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const packageName = path.startsWith("@")
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
@@ -319,7 +317,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
}
}
const packagePath = args.path.slice(packageName.length);
const packagePath = path.slice(packageName.length);
const specifier = version
? `${cdnName}@${version}${packagePath}`
: `${cdnName}${packagePath}`;
@@ -339,6 +337,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
};
}
// https://vite.dev/guide/assets#explicit-url-imports
if (params.has("url")) {
return {
path: urlStr,
namespace: "esm-file-external",
};
}
return {
path: urlStr,
namespace: "esm",
@@ -426,6 +432,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
loader = "js";
} else if (contentType === "text/css") {
loader = "css";
} else if (contentType === "application/wasm") {
loader = "binary";
} else {
loader = "text";
}
@@ -438,6 +446,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
loader,
};
});
// Convert `?url` imports to URL strings pointing to the ESM CDN
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
return {
contents: `export default ${JSON.stringify(args.path)};`,
loader: "js",
};
});
},
};
}
+1 -1
View File
@@ -24,7 +24,7 @@ async function bundle(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
const { fs, projectPath, domParser, target = "esnext", esmUrl } = options;
const esbuild = await getEsbuild(esmUrl);
const esbuild = await getEsbuild();
const indexHtmlText = await fs.readFile(
`${projectPath}/index.html`,
+2 -1
View File
@@ -23,9 +23,10 @@ const mockFS: JSRuntimeFS = {
describe('CurlCommand', () => {
let curlCommand: CurlCommand;
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
beforeEach(() => {
curlCommand = new CurlCommand(mockFS);
curlCommand = new CurlCommand(mockFS, testCorsProxy);
vi.clearAllMocks();
});
+7 -4
View File
@@ -3,6 +3,7 @@ import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
import { proxyUrl } from "../proxyUrl";
/**
* Parsed curl options
@@ -35,9 +36,11 @@ export class CurlCommand implements ShellCommand {
usage = 'curl [options] <url>';
private fs: JSRuntimeFS;
private corsProxy: string;
constructor(fs: JSRuntimeFS) {
constructor(fs: JSRuntimeFS, corsProxy: string) {
this.fs = fs;
this.corsProxy = corsProxy;
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
@@ -61,9 +64,9 @@ export class CurlCommand implements ShellCommand {
return createErrorResult(`${this.name}: unsupported protocol: ${url.protocol}`);
}
// Proxy the URL through CorsProxy
// Proxy the URL through configured CorsProxy
const originalUrl = url.toString();
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
// Prepare request
const requestInit: RequestInit = {
@@ -93,7 +96,7 @@ export class CurlCommand implements ShellCommand {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
timeoutId = setTimeout(() => controller.abort(), options.timeout * 1000);
timeoutId = setTimeout(() => controller.abort('Request timeout'), options.timeout * 1000);
requestInit.signal = controller.signal;
}
+321
View File
@@ -0,0 +1,321 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface CloudflareFile {
key: string;
value: string;
metadata: {
contentType: string;
};
base64: boolean;
}
interface CloudflareDeployment {
id: string;
url: string;
environment: string;
deployment_trigger: {
type: string;
};
stages: Array<{
name: string;
status: string;
}>;
project_name: string;
}
interface CloudflareProject {
id: string;
name: string;
subdomain: string;
domains: string[];
created_on: string;
}
/**
* Cloudflare Pages Deploy Adapter
* Uses Cloudflare Pages Direct Upload API with API token
*
* Mimics the behavior of "wrangler pages deploy dist"
*/
export class CloudflareAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiToken: string;
private accountId: string;
private baseURL: string;
private projectName?: string;
private branch?: string;
private corsProxy?: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
this.apiToken = config.apiToken;
this.accountId = config.accountId;
this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4';
this.projectName = config.projectName;
this.branch = config.branch || 'main';
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// 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.');
}
// Determine project name
const cfProjectName = this.projectName || projectId;
// Ensure project exists or create it
let project: CloudflareProject;
try {
project = await this.getProject(cfProjectName);
} catch {
// Project doesn't exist, create it
project = await this.createProject(cfProjectName);
}
// Collect all files from dist directory
const manifest: Record<string, string> = {};
const files: CloudflareFile[] = [];
await this.collectFiles(distPath, '', files, manifest);
// Create deployment using Direct Upload API
const deployment = await this.createDeployment(cfProjectName, files, manifest);
// Construct the deployment URL
const deploymentUrl = deployment.url || `https://${deployment.id}.${project.subdomain}.pages.dev`;
return {
url: deploymentUrl,
metadata: {
deploymentId: deployment.id,
projectId: project.id,
projectName: project.name,
provider: 'cloudflare',
environment: deployment.environment,
},
};
}
private async getProject(projectName: string): Promise<CloudflareProject> {
const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to get Cloudflare Pages project: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async createProject(projectName: string): Promise<CloudflareProject> {
const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: projectName,
production_branch: this.branch,
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create Cloudflare Pages project: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async createDeployment(
projectName: string,
files: CloudflareFile[],
manifest: Record<string, string>
): Promise<CloudflareDeployment> {
const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create form data for multipart upload
const formData = new FormData();
// Add manifest
formData.append('manifest', JSON.stringify(manifest));
// Add each file
for (const file of files) {
const blob = new Blob([file.value], { type: file.metadata.contentType });
formData.append(file.key, blob);
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
// Don't set Content-Type - browser will set it with boundary for multipart/form-data
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create Cloudflare Pages deployment: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async collectFiles(
dirPath: string,
relativePath: string,
files: CloudflareFile[],
manifest: Record<string, string>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
// Recursively collect files from subdirectories
await this.collectFiles(fullPath, entryRelativePath, files, manifest);
} else if (entry.isFile()) {
try {
// Read file content
const fileContent = await this.fs.readFile(fullPath);
// Determine content type based on file extension
const contentType = this.getContentType(entry.name);
// Convert to base64 for binary files, or keep as string for text files
let base64Content: string;
let isBase64 = false;
if (this.isBinaryFile(entry.name)) {
// Handle binary files (images, fonts, etc.)
if (typeof fileContent === 'string') {
base64Content = btoa(fileContent);
} else {
// Handle Uint8Array
const binary = Array.from(fileContent)
.map(byte => String.fromCharCode(byte))
.join('');
base64Content = btoa(binary);
}
isBase64 = true;
} else {
// Handle text files (HTML, CSS, JS, etc.)
if (typeof fileContent === 'string') {
base64Content = fileContent;
} else {
// Decode Uint8Array to string
const decoder = new TextDecoder();
base64Content = decoder.decode(fileContent);
}
}
// Add to files array
files.push({
key: entryRelativePath,
value: base64Content,
metadata: {
contentType,
},
base64: isBase64,
});
// Add to manifest (hash placeholder - Cloudflare will compute actual hash)
manifest[entryRelativePath] = '';
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
/**
* Get MIME type based on file extension
*/
private getContentType(filename: string): string {
const ext = filename.split('.').pop()?.toLowerCase();
const mimeTypes: Record<string, string> = {
// Text
'html': 'text/html',
'htm': 'text/html',
'css': 'text/css',
'js': 'application/javascript',
'mjs': 'application/javascript',
'json': 'application/json',
'xml': 'application/xml',
'txt': 'text/plain',
'md': 'text/markdown',
// Images
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'svg': 'image/svg+xml',
'webp': 'image/webp',
'ico': 'image/x-icon',
// Fonts
'woff': 'font/woff',
'woff2': 'font/woff2',
'ttf': 'font/ttf',
'otf': 'font/otf',
'eot': 'application/vnd.ms-fontobject',
// Other
'pdf': 'application/pdf',
'zip': 'application/zip',
'wasm': 'application/wasm',
};
return mimeTypes[ext || ''] || 'application/octet-stream';
}
/**
* Determine if a file should be treated as binary
*/
private isBinaryFile(filename: string): boolean {
const ext = filename.split('.').pop()?.toLowerCase();
const binaryExtensions = [
'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico',
'woff', 'woff2', 'ttf', 'otf', 'eot',
'pdf', 'zip', 'wasm',
];
return binaryExtensions.includes(ext || '');
}
}
+1
View File
@@ -3,3 +3,4 @@ export * from './ShakespeareAdapter';
export * from './NetlifyAdapter';
export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
+10
View File
@@ -54,3 +54,13 @@ export interface NsiteDeployConfig {
relayUrls: string[];
blossomServers: string[];
}
export interface CloudflareDeployConfig {
fs: JSRuntimeFS;
apiToken: string;
accountId: string;
baseURL?: string;
projectName?: string;
branch?: string;
corsProxy?: string;
}
+6 -5
View File
@@ -1,22 +1,23 @@
import type _ESBuild from "esbuild-wasm";
import wasmUrl from "esbuild-wasm/esbuild.wasm?url";
type ESBuild = typeof _ESBuild;
let promise: Promise<ESBuild> | undefined;
export function getEsbuild(esmUrl: string): Promise<ESBuild> {
export function getEsbuild(): Promise<ESBuild> {
if (!promise) {
promise = loadEsbuild(esmUrl);
promise = loadEsbuild();
}
return promise;
}
async function loadEsbuild(esmUrl: string): Promise<ESBuild> {
async function loadEsbuild(): Promise<ESBuild> {
const { default: esbuild } = await import("esbuild-wasm");
await esbuild.initialize({
worker: false,
wasmURL: `${esmUrl}/[email protected]/esbuild.wasm`,
worker: true,
wasmURL: wasmUrl,
});
return esbuild;
+152 -33
View File
@@ -681,12 +681,14 @@ export class Git {
}
/**
* Get current repository state for creating a NIP-34 repository state event
* Create initial repository state from current local git repository
* This should only be used when no existing state event is found
*/
private async getCurrentRepositoryState(dir: string): Promise<{
refTags: string[][];
headRef?: string;
}> {
private async createInitialRepositoryState(
dir: string,
dTag: string,
signer: NostrSigner
): Promise<NostrEvent> {
const refTags: string[][] = [];
let headRef: string | undefined;
@@ -765,11 +767,70 @@ export class Git {
}
console.log(`Repository state: ${refTags.length} refs, HEAD=${headRef}`);
return { refTags, headRef };
} catch (error) {
console.error('Failed to get repository state:', error);
throw new Error(`Failed to get repository state: ${error}`);
}
// Create and sign the state event
return await signer.signEvent({
kind: 30618,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags: [
['d', dTag],
...refTags,
...(headRef ? [['HEAD', headRef]] : []),
],
});
}
/**
* Apply changes from a push operation to repository state and create updated event
* Mutates the state object directly and returns the signed event
*/
private async applyPushAndUpdateStateEvent(
state: RespositoryState,
remoteRef: string,
newCommit: string,
signer: NostrSigner
): Promise<NostrEvent> {
const remoteRefName = remoteRef.startsWith('refs/') ? remoteRef : `refs/heads/${remoteRef}`;
// Update the ref
state.refs[remoteRefName] = newCommit;
// Update head commit if this ref is HEAD
if (state.HEAD === `ref: ${remoteRefName}`) {
state.headCommit = newCommit;
}
// Extract d tag from original event
const dTag = state.event.tags.find(([name]) => name === 'd');
if (!dTag || !dTag[1]) {
throw new Error('Repository state event missing required d tag');
}
const tags: string[][] = [['d', dTag[1]]];
// Add HEAD if set
if (state.HEAD) {
tags.push(['HEAD', state.HEAD]);
}
// Add all refs
for (const [ref, commit] of Object.entries(state.refs)) {
tags.push([ref, commit]);
}
// Create and sign the updated event
state.event = await signer.signEvent({
kind: 30618,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags,
});
return state.event;
}
/**
@@ -1327,7 +1388,7 @@ export class Git {
/**
* Update remote tracking refs to match the Nostr state if git data present locally
* @returns refs with missing data including HEAD
* @returns refs with missing data including HEAD, updated refs, and deleted stale refs
*/
private async updateRemoteRefsToNostrState(
state: RespositoryState,
@@ -1335,18 +1396,22 @@ export class Git {
): Promise<{
updated?: Record<string, string>,
refsWithMissingData?: Record<string, string>,
deleted?: string[],
}> {
// Get the remote name from options (passed from the fetch call)
const remoteName = options.remote || 'origin';
const refsWithMissingData: Record<string, string> = {};
const updated: Record<string, string> = {};
for (const [refName, entry] of [
const entries = [
...Object.entries(state.refs),
...(state.HEAD ? [["HEAD", state.HEAD]] : [])
]) {
];
for (const [refName, entry] of entries) {
// update symbolic ref to use remote ref
const value = entry.startsWith("ref: ") ? `ref: ${this.localRefToRemoteRef(remoteName, entry.slice(5))}` : entry;
const isSymbolic = value.startsWith("ref: ");
const refValue = isSymbolic ? value.slice(5) : value; // Remove "ref: " prefix for symbolic refs
try {
// Check if we have this commit locally
try {
@@ -1356,27 +1421,32 @@ export class Git {
fs: this.fs,
dir: options.dir,
ref:remoteRefName,
depth: 1, // Don't resolve symbolic refs, just get the raw value
});
// update correct ref
if (existingValue === value) continue;
if (existingValue === refValue) continue;
} catch {
// ref doesnt exist yet
}
if (!value.startsWith("ref: ")) await git.readCommit({
fs: this.fs,
dir: options.dir,
// TODO handle and annotated tags
oid: value,
});
// We have the commit, update the remote tracking ref
if (!isSymbolic) {
// For non-symbolic refs, verify we have the commit locally
await git.readCommit({
fs: this.fs,
dir: options.dir,
// TODO handle annotated tags
oid: refValue,
});
}
// We have the commit (or it's a symbolic ref), update the remote tracking ref
await git.writeRef({
fs: this.fs,
dir: options.dir,
ref: remoteRefName,
force: true, // standard behaviour of git fetch
value: value,
value: refValue,
symbolic: isSymbolic, // Set symbolic flag for symbolic refs
});
console.log(`✓ Updated ${remoteRefName} to ${value}`);
console.log(`✓ Updated ${remoteRefName} to ${isSymbolic ? 'ref: ' : ''}${refValue}`);
updated[refName] = entry;
} catch (error) {
refsWithMissingData[refName] = value;
@@ -1388,9 +1458,48 @@ export class Git {
}
}
// Delete local remote refs that don't exist in Repository State
const deleted: string[] = [];
try {
// Get all local remote tracking refs for this remote
const localRemoteRefs = await git.listRefs({
fs: this.fs,
dir: options.dir,
filepath: `refs/remotes/${remoteName}`
});
// Build set of expected remote refs based on Repository State
// This should match the same set of refs we iterated over above
const expectedRemoteRefs = new Set<string>();
for (const [refName] of entries) {
expectedRemoteRefs.add(this.localRefToRemoteRef(remoteName, refName));
}
// Delete any local remote refs that don't exist in the Repository State
for (const localRemoteRef of localRemoteRefs) {
const fullRef = this.localRefToRemoteRef(remoteName, localRemoteRef);
if (!expectedRemoteRefs.has(fullRef)) {
try {
await git.deleteRef({
fs: this.fs,
dir: options.dir,
ref: fullRef,
});
console.log(`✓ Deleted stale remote ref ${localRemoteRef}`);
deleted.push(localRemoteRef);
} catch (error) {
console.warn(`Failed to delete stale remote ref ${localRemoteRef}:`, error);
}
}
}
} catch (error) {
console.warn('Failed to clean up stale remote refs:', error);
}
return {
refsWithMissingData: Object.keys(refsWithMissingData).length > 0 ? refsWithMissingData : undefined,
updated: Object.keys(updated).length > 0 ? updated : undefined,
deleted: deleted.length > 0 ? deleted : undefined,
}
}
@@ -1774,7 +1883,7 @@ export class Git {
}
// Extract relay URLs and clone URLs from the repository announcement
const relayUrls: string[] = [];
const relayUrls: string[] = [ ...(repo.relays) ?? []];
// If no relays specified in announcement, use default git-focused relays
if (relayUrls.length === 0) {
@@ -1813,20 +1922,30 @@ export class Git {
}
}
// Get current repository state
const repoState = await this.getCurrentRepositoryState(dir);
// Update or create repository state
let stateEvent: NostrEvent;
// Create repository state event (kind 30618)
const stateEvent = await signer.signEvent({
kind: 30618,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags: [
['d', nostrURI.d], // Repository identifier
...repoState.refTags,
...(repoState.headRef ? [['HEAD', repoState.headRef]] : []),
],
});
if (state) {
// We have an existing state event - update it with the new ref
// Get the commit we're pushing
let localCommit: string;
try {
localCommit = await git.resolveRef({
fs: this.fs,
dir,
ref,
});
} catch (error) {
throw new Error(`Failed to resolve local ref ${ref}: ${error}`);
}
// Apply push changes and create updated event
stateEvent = await this.applyPushAndUpdateStateEvent(state, remoteRef, localCommit, signer);
} else {
// No existing state event - create initial state from repository
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.d, signer);
}
// Publish the state event to Nostr relays
console.log(`Publishing repository state to ${relayUrls.length} relays`);
+1 -1
View File
@@ -50,7 +50,7 @@ export async function initializeSentry(dsn: string): Promise<void> {
// Environment
environment: import.meta.env.MODE,
// Release
release: import.meta.env.VERSION || 'development',
release: import.meta.env.VERSION,
// Censor sensitive data before sending to Sentry
beforeSend(event) {
// Regex to match Nostr nsec private keys
+522
View File
@@ -0,0 +1,522 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { makeSystemPrompt, MakeSystemPromptOpts } from './system';
import { JSRuntimeFS } from './JSRuntime';
import { NUser } from '@nostrify/react/login';
import { NostrMetadata } from '@nostrify/nostrify';
import { AppConfig } from '@/contexts/AppContext';
import OpenAI from 'openai';
// Mock the plugins module
vi.mock('./plugins', () => ({
getAllSkills: vi.fn(),
}));
// Mock path-browserify
vi.mock('path-browserify', () => ({
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
}));
import { getAllSkills } from './plugins';
// Test configuration
const testConfig: AppConfig = {
theme: 'light',
relayMetadata: {
relays: [
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
language: 'en',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
};
describe('makeSystemPrompt', () => {
let mockFs: JSRuntimeFS;
let baseOpts: MakeSystemPromptOpts;
beforeEach(() => {
vi.clearAllMocks();
// Mock filesystem
mockFs = {
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
stat: vi.fn(),
mkdir: vi.fn(),
rmdir: vi.fn(),
unlink: vi.fn(),
rename: vi.fn(),
exists: vi.fn(),
} as unknown as JSRuntimeFS;
// Base options for tests
baseOpts = {
tools: [],
mode: 'agent',
fs: mockFs,
cwd: '/projects/test-project',
config: testConfig,
defaultConfig: testConfig,
};
// Mock getAllSkills to return empty array by default
vi.mocked(getAllSkills).mockResolvedValue([]);
});
describe('basic system prompt generation', () => {
it('should generate a basic system prompt in agent mode', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
expect(result).toContain('Your goal is to work on the project in the current directory');
expect(result).toContain('explore and understand the project structure');
});
it('should generate a basic system prompt in init mode', async () => {
const result = await makeSystemPrompt({ ...baseOpts, mode: 'init' });
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
expect(result).toContain('The files in the current directory are a template');
expect(result).toContain('transform this template into a working project');
});
it('should include current date', async () => {
const result = await makeSystemPrompt(baseOpts);
const currentDate = new Date().toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
});
expect(result).toContain(`**Current Date**: ${currentDate}`);
});
it('should include current working directory', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('**Current Working Directory**: /projects/test-project');
});
});
describe('user information', () => {
it('should include logged-out user message when no user is provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('The user is not logged in');
expect(result).toContain('can log into Nostr by clicking the "Login" button');
});
it('should include basic user information when user is provided', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const result = await makeSystemPrompt({ ...baseOpts, user });
expect(result).toContain('The user is logged into Nostr');
expect(result).toContain('**Nostr pubkey (hex)**: abc123def456');
expect(result).toContain('**Nostr npub**: npub1');
});
it('should include user metadata when provided', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const metadata: NostrMetadata = {
name: 'Alice',
about: 'A passionate developer',
website: 'https://alice.example.com',
picture: 'https://alice.example.com/avatar.jpg',
banner: 'https://alice.example.com/banner.jpg',
nip05: '[email protected]',
lud16: '[email protected]',
};
const result = await makeSystemPrompt({ ...baseOpts, user, metadata });
expect(result).toContain('**Name**: Alice');
expect(result).toContain('**About**: A passionate developer');
expect(result).toContain('**Website**: https://alice.example.com');
expect(result).toContain('**Avatar**: https://alice.example.com/avatar.jpg');
expect(result).toContain('**Banner**: https://alice.example.com/banner.jpg');
expect(result).toContain('**NIP-05**: [email protected]');
expect(result).toContain('**Lightning Address**: [email protected]');
});
it('should sanitize multiline about text', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const metadata: NostrMetadata = {
about: 'Line 1\nLine 2\r\nLine 3',
};
const result = await makeSystemPrompt({ ...baseOpts, user, metadata });
expect(result).toContain('**About**: Line 1 Line 2 Line 3');
expect(result).not.toContain('\n**About**');
});
});
describe('tools section', () => {
it('should not include tools section when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).not.toContain('## Available Tools');
});
it('should list available tools with descriptions', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'read_file',
description: 'Read contents of a file',
parameters: {},
},
},
{
type: 'function',
function: {
name: 'write_file',
description: 'Write contents to a file',
parameters: {},
},
},
];
const result = await makeSystemPrompt({ ...baseOpts, tools });
expect(result).toContain('## Available Tools');
expect(result).toContain('**read_file**: Read contents of a file');
expect(result).toContain('**write_file**: Write contents to a file');
});
it('should handle tools without descriptions', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'some_tool',
parameters: {},
},
},
];
const result = await makeSystemPrompt({ ...baseOpts, tools });
expect(result).toContain('**some_tool**: No description available');
});
});
describe('skills section', () => {
it('should show no skills message when pluginsPath is not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, fsPathPlugins: '' },
});
expect(result).toContain('## Skills');
expect(result).toContain('No skills are currently configured');
});
it('should show no skills message when getAllSkills returns empty array', async () => {
vi.mocked(getAllSkills).mockResolvedValue([]);
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins');
});
it('should list available skills when they exist', async () => {
vi.mocked(getAllSkills).mockResolvedValue([
{
name: 'create_component',
description: 'Create a new React component',
plugin: 'react-plugin',
path: '/plugins/react-plugin/skills/create_component.md',
},
{
name: 'setup_routing',
description: 'Setup React Router',
plugin: 'react-plugin',
path: '/plugins/react-plugin/skills/setup_routing.md',
},
]);
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Skills');
expect(result).toContain('**create_component**: Create a new React component');
expect(result).toContain('Plugin: react-plugin');
expect(result).toContain('**setup_routing**: Setup React Router');
expect(result).toContain('Skills MUST be used whenever applicable');
});
it('should handle getAllSkills errors gracefully', async () => {
vi.mocked(getAllSkills).mockRejectedValue(new Error('Plugin error'));
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
});
});
describe('CORS proxy section', () => {
it('should not include CORS proxy section when not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, corsProxy: '' },
});
expect(result).not.toContain('## Working Around CORS Issues');
});
it('should include CORS proxy information when provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('**CORS Proxy URL Template**: `https://proxy.shakespeare.diy/?url={href}`');
});
});
describe('Edit with Shakespeare section', () => {
it('should show message when no repository URL is configured', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Edit with Shakespeare');
expect(result).toContain('This project does not currently have a repository URL configured');
});
it('should include badge code snippets when repository URL is provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
repositoryUrl: 'https://github.com/user/repo.git',
});
expect(result).toContain('## Edit with Shakespeare');
expect(result).toContain('[![Edit with Shakespeare]');
expect(result).toContain('/badge.svg');
expect(result).toContain('/clone');
// URL is encoded, so check for the encoded version
expect(result).toContain('url=https%3A%2F%2Fgithub.com%2Fuser%2Frepo.git');
});
});
describe('README.md inclusion', () => {
it('should include README.md content when it exists', async () => {
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
if (path === '/projects/test-project/README.md') {
return '# My Project\n\nThis is a test project.';
}
throw new Error('File not found');
});
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('# My Project');
expect(result).toContain('This is a test project.');
});
it('should continue when README.md does not exist', async () => {
vi.mocked(mockFs.readFile).mockRejectedValue(new Error('File not found'));
const result = await makeSystemPrompt(baseOpts);
expect(result).toBeTruthy();
expect(result).not.toContain('# My Project');
});
});
describe('AGENTS.md and context files inclusion', () => {
it('should include AGENTS.md content when it exists', async () => {
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
if (path === '/projects/test-project/AGENTS.md') {
return '# Agent Instructions\n\nFollow these guidelines.';
}
throw new Error('File not found');
});
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('# Agent Instructions');
expect(result).toContain('Follow these guidelines.');
});
it('should try alternative context files in order', async () => {
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
if (path === '/projects/test-project/CONTEXT.md') {
return '# Context File\n\nProject context.';
}
throw new Error('File not found');
});
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('# Context File');
expect(result).toContain('Project context.');
});
it('should continue when no context files exist', async () => {
vi.mocked(mockFs.readFile).mockRejectedValue(new Error('File not found'));
const result = await makeSystemPrompt(baseOpts);
expect(result).toBeTruthy();
});
it('should try context files in correct order', async () => {
const readFileCalls: string[] = [];
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
readFileCalls.push(path);
throw new Error('File not found');
});
await makeSystemPrompt(baseOpts);
// Check that AGENTS.md is tried first
expect(readFileCalls).toContain('/projects/test-project/AGENTS.md');
});
});
describe('complete system prompt structure', () => {
it('should include all major sections', async () => {
// Use a valid hex pubkey (64 characters)
const validPubkey = '0'.repeat(64);
const user = new NUser('extension', validPubkey, {} as NUser['signer']);
const result = await makeSystemPrompt({
...baseOpts,
user,
repositoryUrl: 'https://github.com/test/repo.git',
});
expect(result).toContain('# Your Environment');
expect(result).toContain('## What Shakespeare Is');
expect(result).toContain('## The User');
expect(result).toContain('## User Interface');
expect(result).toContain('## User Actions');
expect(result).toContain('## Virtual Filesystem Structure');
expect(result).toContain('## Your Role');
expect(result).toContain('## Skills');
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('## Edit with Shakespeare');
});
it('should include Shakespeare architecture information', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('Browser-Based Storage');
expect(result).toContain('AI Provider Independence');
expect(result).toContain('Shakespeare AI Credits');
expect(result).toContain('Cross-Browser Access');
expect(result).toContain('No Central Shakespeare Server');
});
it('should include user interface description', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('**Homepage**');
expect(result).toContain('**Project View**');
expect(result).toContain('**Settings**');
expect(result).toContain('**Left Pane**: AI chat interface');
expect(result).toContain('**Right Pane**: Toggles between two views');
});
it('should include virtual filesystem structure', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('/projects/');
// The config/ and tmp/ paths are in a code block, so check for the exact format
expect(result).toContain('├── config/');
expect(result).toContain('└── tmp/');
expect(result).toContain('Project Isolation');
expect(result).toContain('Persistent Storage');
});
it('should include role description with commit reminder', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Your Role');
expect(result).toContain('Always commit your code changes');
});
});
describe('custom template support', () => {
it('should render a custom template when provided', async () => {
const customTemplate = `Hello Shakespeare! Current directory: {{ cwd }}`;
const result = await makeSystemPrompt({
...baseOpts,
template: customTemplate,
});
expect(result).toContain('Hello Shakespeare!');
expect(result).toContain('Current directory: /projects/test-project');
expect(result).not.toContain('# Your Environment'); // Should not include default template content
});
it('should support conditional logic in custom templates', async () => {
const customTemplate = `{% if mode === 'init' %}Initializing...{% else %}Working on project{% endif %}`;
const result = await makeSystemPrompt({
...baseOpts,
mode: 'agent',
template: customTemplate,
});
expect(result).toContain('Working on project');
expect(result).not.toContain('Initializing');
});
it('should provide access to all context variables in custom templates', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const customTemplate = `User: {{ user.pubkey if user else 'none' }}
CWD: {{ cwd }}
Origin: {{ location.origin }}
Skills: {{ skills.length }}`;
const result = await makeSystemPrompt({
...baseOpts,
user,
template: customTemplate,
});
expect(result).toContain('User: abc123def456');
expect(result).toContain('CWD: /projects/test-project');
expect(result).toContain('Origin: http://localhost:3000');
expect(result).toContain('Skills: 0');
});
});
});
+164 -91
View File
@@ -3,64 +3,38 @@ import { NostrMetadata } from "@nostrify/nostrify";
import { join } from "path-browserify";
import OpenAI from "openai";
import { nip19 } from "nostr-tools";
import nunjucks from "nunjucks";
import { JSRuntimeFS } from "./JSRuntime";
import { getAllSkills } from "./plugins";
import type { AppConfig } from "@/contexts/AppContext";
export interface MakeSystemPromptOpts {
name: string;
profession: string;
tools: OpenAI.Chat.Completions.ChatCompletionTool[];
mode: "init" | "agent";
fs: JSRuntimeFS;
cwd: string;
pluginsPath?: string;
config: AppConfig;
defaultConfig: AppConfig;
user?: NUser;
metadata?: NostrMetadata;
repositoryUrl?: string;
template?: string;
}
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { name, profession, tools, mode, fs, cwd, pluginsPath, user, metadata } = opts;
/**
* Default system prompt template.
* This can be customized by users in Settings > System > System Prompt.
*/
export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare, an expert software extraordinaire. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.{% else %}You are Shakespeare, an expert software extraordinaire. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.{% endif %}
let system = mode === "init"
? `You are ${name}, an expert ${profession}. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.`
: `You are ${name}, an expert ${profession}. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.`;
// Add current date
const currentDate = new Date().toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
let userText: string;
if (user) {
userText = `The user is logged into Nostr with the following profile:
- **Nostr pubkey (hex)**: ${user.pubkey}
- **Nostr npub**: ${nip19.npubEncode(user.pubkey)}`;
if (metadata?.name) userText += `\n- **Name**: ${metadata.name}`;
if (metadata?.about) userText += `\n- **About**: ${metadata.about.replace(/[\r\n]+/g, ' ')}`;
if (metadata?.website) userText += `\n- **Website**: ${metadata.website}`;
if (metadata?.picture) userText += `\n- **Avatar**: ${metadata.picture}`;
if (metadata?.banner) userText += `\n- **Banner**: ${metadata.banner}`;
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
} else {
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
}
// Add Your Environment section
system += `\n\n# Your Environment
# Your Environment
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
- **Current Date**: ${currentDate}
- **Current Page**: ${location.href}
- **Current Working Directory**: ${cwd}
- **Current Date**: {{ date }}
- **Current Page**: {{ location.href }}
- **Current Working Directory**: {{ cwd }}
- **Repository URL**: {{ repositoryUrl }}
## What Shakespeare Is
@@ -78,7 +52,19 @@ Shakespeare is a web-based development environment where users can build Nostr w
## The User
${userText}
{% if user %}The user is logged into Nostr with the following profile:
- **Nostr pubkey (hex)**: {{ user.pubkey }}
- **Nostr npub**: {{ user.npub }}{% if user.name %}
- **Name**: {{ user.name }}{% endif %}{% if user.about %}
- **About**: {{ user.about }}{% endif %}{% if user.website %}
- **Website**: {{ user.website }}{% endif %}{% if user.picture %}
- **Avatar**: {{ user.picture }}{% endif %}{% if user.banner %}
- **Banner**: {{ user.banner }}{% endif %}{% if user.nip05 %}
- **NIP-05**: {{ user.nip05 }}{% endif %}{% if user.lud16 %}
- **Lightning Address**: {{ user.lud16 }}{% endif %}
Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.{% else %}The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.{% endif %}
## User Interface
@@ -138,8 +124,8 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a
├── config/ # Configuration files
│ ├── ai.json # AI provider settings and API keys
│ └── git.json # Git credentials and repository settings
└── tmp/ # Temporary files and scratch space
└── ... # Various temporary files and directories
└── tmp/ # Temporary files and scratch space
└── ... # Various temporary files and directories
\`\`\`
### Key VFS Features
@@ -163,73 +149,160 @@ As the AI assistant in Shakespeare, you help users by:
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.`;
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.{% if tools.length > 0 %}
// Add available tools to the system prompt
const toolNames = tools
.filter((tool) => tool.type === "function")
.map((tool) => tool.function.name);
## Available Tools
if (toolNames.length > 0) {
system +=
"\n\n## Available Tools\n\nYou have access to the following tools:\n";
for (const tool of tools) {
if (tool.type === "function") {
system += `\n- **${tool.function.name}**: ${
tool.function.description || "No description available"
}`;
}
}
}
You have access to the following tools:
{% for tool in tools %}{% if tool.type === 'function' %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% endif %}
// Add skills section
system += "\n\n## Skills\n\n";
## Skills
if (pluginsPath) {
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
Available skills:
{% for skill in skills %}
- **{{ skill.name }}**: {{ skill.description }}
- Plugin: {{ skill.plugin }}
- Path: {{ skill.path }}
{% endfor %}
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
Users can configure skills in Settings > AI ({{ location.origin }}/settings/ai) by adding plugins that contain skills.{% if config.corsProxy %}
## Working Around CORS Issues
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
**CORS Proxy URL Template**: \`{{ config.corsProxy }}\`
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.{% endif %}
## Edit with Shakespeare
The "Edit with Shakespeare" button is a way that people can start editing any Shakespeare-compatible site with a single click. It can be added anywhere markdown or HTML is supported, including in READMEs, or within an app itself.{% if repositoryUrl %}
This project has a repository URL configured, so you can create an "Edit with Shakespeare" button using the following code snippets:
**Markdown:**
\`\`\`markdown
[![Edit with Shakespeare]({{ badgeUrl }})]({{ editUrl }})
\`\`\`
**HTML/JSX/TSX:**
\`\`\`jsx
<a href="{{ editUrl }}" target="_blank">
<img src="{{ badgeUrl }}" alt="Edit with Shakespeare" />
</a>
\`\`\`
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if readmeText %}
{{ readmeText }}{% endif %}{% if agentsText %}
{{ agentsText }}{% endif %}`;
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts;
// Add current date
const date = new Date().toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
// Get skills
let skills: Array<{ name: string; description: string; plugin: string; path: string }> = [];
if (config.fsPathPlugins) {
try {
const skills = await getAllSkills(fs, pluginsPath);
if (skills.length > 0) {
system += "You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.\n\n";
system += "Available skills:\n\n";
for (const skill of skills) {
system += `- **${skill.name}**: ${skill.description}\n - Plugin: ${skill.plugin}\n - Path: ${skill.path}\n`;
}
system += `\n**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.\n`;
} else {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
skills = await getAllSkills(fs, config.fsPathPlugins);
} catch {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
// Skills not available, use empty array
skills = [];
}
} else {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
system += `\nUsers can configure skills in Settings > AI (${location.origin}/settings/ai) by adding plugins that contain skills.`;
// Add README.md if it exists
// Get README.md if it exists
let readmeText: string | undefined;
try {
const readmePath = join(cwd, "README.md");
const readmeText = await fs.readFile(readmePath, "utf8");
if (readmeText) {
system += "\n\n" + readmeText;
}
readmeText = await fs.readFile(readmePath, "utf8");
} catch {
// README.md not found, continue
}
// Add context from AGENTS.md if it exists
// Get agent context if it exists
let agentsText: string | undefined;
try {
const { text } = await getAgentContext(fs, cwd);
system += "\n\n" + text;
agentsText = text;
} catch {
// AGENTS.md not found, continue
}
return system;
// Build URLs for Edit with Shakespeare
let badgeUrl: string | undefined;
let editUrl: string | undefined;
if (repositoryUrl) {
badgeUrl = new URL('/badge.svg', location.origin).toString();
const editUrlObj = new URL('/clone', location.origin);
editUrlObj.searchParams.set('url', repositoryUrl);
editUrl = editUrlObj.toString();
}
// Build context object for template
const context = {
mode,
date,
cwd,
repositoryUrl,
config,
defaultConfig,
user: user
? {
...metadata,
pubkey: user.pubkey,
npub: nip19.npubEncode(user.pubkey),
about: metadata?.about?.replace(/[\r\n]+/g, ' '),
}
: undefined,
tools,
skills,
location: {
href: location.href,
origin: location.origin,
pathname: location.pathname,
port: location.port,
hostname: location.hostname,
protocol: location.protocol,
search: location.search,
hash: location.hash,
},
badgeUrl,
editUrl,
readmeText,
agentsText,
};
// Render the template with the context
// Use the provided template, or fall back to the default
const templateToRender = template || defaultSystemPrompt;
try {
// Configure nunjucks environment
const env = new nunjucks.Environment(null, { autoescape: false });
return env.renderString(templateToRender, context);
} catch (error) {
console.error("Error rendering system prompt template:", error);
// Return the template as-is if rendering fails
return templateToRender;
}
}
async function getAgentContext(
+2 -1
View File
@@ -35,12 +35,13 @@ describe('ShellTool', () => {
let mockNostr: NPool;
let shellTool: ShellTool;
const testCwd = '/test/dir';
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
beforeEach(() => {
mockFS = createMockFS();
mockNostr = createMockNostr();
mockGit = new Git({ fs: mockFS, nostr: mockNostr });
shellTool = new ShellTool(mockFS, testCwd, mockGit);
shellTool = new ShellTool(mockFS, testCwd, mockGit, '/projects', testCorsProxy);
});
it('should have correct tool properties', () => {
+4 -2
View File
@@ -53,6 +53,7 @@ export class ShellTool implements Tool<ShellToolParams> {
private commands: Map<string, ShellCommand>;
private projectsPath: string;
private signer?: NostrSigner;
private corsProxy: string;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
@@ -62,11 +63,12 @@ export class ShellTool implements Tool<ShellToolParams> {
),
});
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', signer?: NostrSigner) {
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', corsProxy: string, signer?: NostrSigner) {
this.fs = fs;
this.cwd = cwd;
this.git = git;
this.projectsPath = projectsPath;
this.corsProxy = corsProxy;
this.signer = signer;
this.commands = new Map();
@@ -75,7 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new CdCommand(fs));
this.registerCommand(new ClearCommand());
this.registerCommand(new CpCommand(fs));
this.registerCommand(new CurlCommand(fs));
this.registerCommand(new CurlCommand(fs, this.corsProxy));
this.registerCommand(new CutCommand(fs));
this.registerCommand(new DateCommand());
this.registerCommand(new DiffCommand(fs));
+6 -1
View File
@@ -59,6 +59,8 @@
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"systemPrompt": "System Prompt",
"systemPromptDescription": "Customize the AI assistant's system prompt using Jinja-like template syntax. This controls the assistant's behavior and knowledge.",
"english": "English",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -483,5 +485,8 @@
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
"temporaryDirectory": "Temporary Directory",
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
"deleting": "Deleting..."
"deleting": "Deleting...",
"modified": "Modified",
"restoreToDefault": "Restore to default",
"restoredToDefault": "Restored to Default"
}
+6 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Hanyar tsarin fayil inda ake adana fayilolin saiti",
"temporaryDirectory": "Kundin Wucin Gadi",
"temporaryDirectoryDescription": "Hanyar tsarin fayil don fayilolin wucin gadi",
"systemPrompt": "Tambarin Tsarin",
"systemPromptDescription": "Keɓanta tambarin tsarin mataimaki na AI ta amfani da tsarin samfuri mai kama da Jinja. Wannan yana sarrafa ɗabi'a da ilimi na mataimaki.",
"english": "Turanci",
"portuguese": "Fotigis",
"chinese": "Sinanci",
@@ -422,5 +424,8 @@
"invalidGiftCard": "Katin Kyauta Ba Daidai Ba",
"giftCardNotFound": "Ba a iya samun wannan katin kyauta.",
"alreadyRedeemed": "An riga an Fanshi",
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta."
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta.",
"modified": "An Canza",
"restoreToDefault": "Mayar da asali",
"restoredToDefault": "An Mayar da Asali"
}
+6 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara faịlụ nhazi",
"temporaryDirectory": "Ndekọ Nwa Oge",
"temporaryDirectoryDescription": "Ụzọ sistemu faịlụ maka faịlụ nwa oge",
"systemPrompt": "Ajụjụ Sistemu",
"systemPromptDescription": "Hazie ajụjụ sistemu nke enyemaka AI site na iji syntax template yiri Jinja. Nke a na-achịkwa omume na ihe ọmụma nke enyemaka ahụ.",
"english": "Bekee",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -419,5 +421,8 @@
"invalidGiftCard": "Kaadị Onyinye Na-ezighị Ezi",
"giftCardNotFound": "Achọtaghị kaadị onyinye a.",
"alreadyRedeemed": "Egbapụtalarị",
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a."
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.",
"modified": "Gbanwere",
"restoreToDefault": "Weghachi na nke mbụ",
"restoredToDefault": "Weghachiri na Nke Mbụ"
}
+6 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Caminho do sistema de arquivos onde os arquivos de configuração são armazenados",
"temporaryDirectory": "Diretório Temporário",
"temporaryDirectoryDescription": "Caminho do sistema de arquivos para arquivos temporários",
"systemPrompt": "Prompt do Sistema",
"systemPromptDescription": "Personalize o prompt do sistema do assistente de IA usando sintaxe de template semelhante a Jinja. Isso controla o comportamento e conhecimento do assistente.",
"english": "Inglês",
"portuguese": "Português",
"chinese": "Chinês",
@@ -432,5 +434,8 @@
"invalidGiftCard": "Cartão Presente Inválido",
"giftCardNotFound": "Este cartão presente não pôde ser encontrado.",
"alreadyRedeemed": "Já Resgatado",
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado."
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado.",
"modified": "Modificado",
"restoreToDefault": "Restaurar para padrão",
"restoredToDefault": "Restaurado para Padrão"
}
+6 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Ọna eto faili nibiti a tọju awọn faili iṣeto",
"temporaryDirectory": "Itọsọna Igba diẹ",
"temporaryDirectoryDescription": "Ọna eto faili fun awọn faili igba diẹ",
"systemPrompt": "Ibeere Eto",
"systemPromptDescription": "Ṣe adani ibeere eto oluranlọwọ AI nipa lilo sintasi awoṣe ti o jọ Jinja. Eyi n ṣakoso ihuwasi ati imọ oluranlọwọ naa.",
"english": "Gẹẹsi",
"portuguese": "Potogisi",
"chinese": "Kannada",
@@ -419,5 +421,8 @@
"invalidGiftCard": "Kaadi Ẹbun Ti ko Tọ",
"giftCardNotFound": "A ko le ri kaadi ẹbun yii.",
"alreadyRedeemed": "Ti ra Tẹlẹ",
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ."
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ.",
"modified": "Ti Yipada",
"restoreToDefault": "Pada si atilẹwa",
"restoredToDefault": "Ti Pada si Atilẹwa"
}
+6 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "存储配置文件的文件系统路径",
"temporaryDirectory": "临时目录",
"temporaryDirectoryDescription": "临时文件的文件系统路径",
"systemPrompt": "系统提示",
"systemPromptDescription": "使用类似Jinja的模板语法自定义AI助手的系统提示。这控制助手的行为和知识。",
"english": "English",
"portuguese": "Português",
"chinese": "中文",
@@ -432,5 +434,8 @@
"invalidGiftCard": "无效的礼品卡",
"giftCardNotFound": "找不到此礼品卡。",
"alreadyRedeemed": "已兑换",
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。"
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。",
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值"
}
-10
View File
@@ -105,16 +105,6 @@ export function AboutSettings() {
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
<Button
variant="outline"
className="w-full h-10 flex items-center gap-2 justify-start"
asChild
>
<a href="https://shakespeare.soapbox.dev" target="_blank" rel="noopener noreferrer">
<span className="font-mono text-sm">shakespeare.soapbox.dev</span>
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
<Button
variant="outline"
className="w-full h-10 flex items-center gap-2 justify-start"
+161 -26
View File
@@ -45,12 +45,14 @@ import { normalizeUrl } from '@/lib/faviconUrl';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare';
name: string;
description: string;
requiresNostr?: boolean;
apiKeyLabel?: string;
apiKeyURL?: string;
accountIdLabel?: string;
accountIdURL?: string;
proxy?: boolean;
}
@@ -186,29 +188,54 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
<PasswordInput
id={`provider-${index}-apiKey`}
placeholder={t('enterApiKey')}
value={provider.apiKey}
value={
provider.type === 'cloudflare' ? provider.apiToken :
provider.type === 'netlify' ? provider.apiKey :
provider.type === 'vercel' ? provider.apiKey : ''
}
onChange={(e) => {
if (provider.type === 'netlify') {
onUpdate(index, { ...provider, apiKey: e.target.value });
} else if (provider.type === 'vercel') {
onUpdate(index, { ...provider, apiKey: e.target.value });
} else if (provider.type === 'cloudflare') {
onUpdate(index, { ...provider, apiToken: e.target.value });
}
}}
/>
</div>
{provider.type === 'cloudflare' && (
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-accountId`}>
Account ID
</Label>
<Input
id={`provider-${index}-accountId`}
placeholder="Enter your Cloudflare Account ID"
value={provider.accountId || ''}
onChange={(e) => onUpdate(index, { ...provider, accountId: e.target.value })}
/>
</div>
)}
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-baseURL`}>
Base URL (Optional)
</Label>
<Input
id={`provider-${index}-baseURL`}
placeholder={provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' : 'https://api.vercel.com'}
placeholder={
provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' :
provider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
'https://api.vercel.com'
}
value={provider.baseURL || ''}
onChange={(e) => {
if (provider.type === 'netlify') {
onUpdate(index, { ...provider, baseURL: e.target.value });
} else if (provider.type === 'vercel') {
onUpdate(index, { ...provider, baseURL: e.target.value });
} else if (provider.type === 'cloudflare') {
onUpdate(index, { ...provider, baseURL: e.target.value });
}
}}
/>
@@ -256,6 +283,17 @@ const PRESET_PROVIDERS: PresetProvider[] = [
name: 'nsite',
description: 'Deploy to Nostr as a static website',
},
{
id: 'cloudflare',
type: 'cloudflare',
name: 'Cloudflare Pages',
description: 'Deploy to Cloudflare Pages',
apiKeyLabel: 'API Token',
apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens',
accountIdLabel: 'Account ID',
accountIdURL: 'https://dash.cloudflare.com/',
proxy: true,
},
{
id: 'netlify',
type: 'netlify',
@@ -306,6 +344,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul
}
return 'https://vercel.com';
case 'cloudflare':
// For Cloudflare providers, check for custom baseURL first, then use default
if ('baseURL' in provider && provider.baseURL) {
return provider.baseURL;
}
return 'https://cloudflare.com';
case 'nsite':
// nsite uses Rocket icon fallback
return null;
@@ -327,12 +372,14 @@ export function DeploySettings() {
const vercelOAuth = useVercelOAuth();
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const [presetAccountIds, setPresetAccountIds] = useState<Record<string, string>>({});
const [forceManualEntry, setForceManualEntry] = useState<Record<string, boolean>>({});
// Custom provider form state
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
@@ -366,12 +413,18 @@ export function DeploySettings() {
}
const apiKey = presetApiKeys[preset.id];
const accountId = presetAccountIds[preset.id];
// For non-Shakespeare/non-nsite providers, require API key
if (!preset.requiresNostr && preset.type !== 'nsite' && !apiKey?.trim()) {
return;
}
// For Cloudflare, also require account ID
if (preset.type === 'cloudflare' && !accountId?.trim()) {
return;
}
let newProvider: DeployProvider;
if (preset.type === 'shakespeare') {
@@ -400,6 +453,15 @@ export function DeploySettings() {
'https://cdn.sovbit.host',
],
};
} else if (preset.type === 'cloudflare') {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'cloudflare',
apiToken: apiKey.trim(),
accountId: accountId.trim(),
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'netlify') {
newProvider = {
id: preset.id, // Use preset ID for presets
@@ -422,6 +484,7 @@ export function DeploySettings() {
// Clear inputs
setPresetApiKeys(prev => ({ ...prev, [preset.id]: '' }));
setPresetAccountIds(prev => ({ ...prev, [preset.id]: '' }));
};
const handleAddCustomProvider = () => {
@@ -454,6 +517,17 @@ export function DeploySettings() {
relayUrls,
blossomServers,
};
} else if (customProviderType === 'cloudflare') {
if (!customApiKey.trim() || !customAccountId.trim()) return;
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'cloudflare',
apiToken: customApiKey.trim(),
accountId: customAccountId.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
newProvider = {
@@ -482,6 +556,7 @@ export function DeploySettings() {
setCustomProviderType('');
setCustomName('');
setCustomApiKey('');
setCustomAccountId('');
setCustomBaseURL('');
setCustomHost('');
setCustomProxy(false);
@@ -694,34 +769,77 @@ export function DeploySettings() {
) : (
// Show manual token input
<div className="space-y-2">
<div className="flex gap-2">
{!preset.requiresNostr && preset.type !== 'nsite' && (
{preset.type === 'cloudflare' ? (
// Cloudflare needs both API token and Account ID
<>
<PasswordInput
placeholder={preset.apiKeyLabel || t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
/>
<Input
placeholder={preset.accountIdLabel || 'Account ID'}
value={presetAccountIds[preset.id] || ''}
onChange={(e) => setPresetAccountIds(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && presetAccountIds[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
}
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
{preset.accountIdURL && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.accountIdURL, '_blank')}
>
Find your Account ID
</button>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!presetApiKeys[preset.id]?.trim() || !presetAccountIds[preset.id]?.trim()}
className="w-full"
>
{t('add')}
</Button>
</>
) : (
<div className="flex gap-2">
{!preset.requiresNostr && preset.type !== 'nsite' && (
<PasswordInput
placeholder={preset.apiKeyLabel || t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
}
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
)}
</div>
)}
</div>
@@ -744,10 +862,11 @@ export function DeploySettings() {
<Label htmlFor="custom-provider-type">{t('providerType')}</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
setCustomAccountId('');
setCustomBaseURL('');
setCustomHost('');
setCustomProxy(false);
@@ -762,6 +881,7 @@ export function DeploySettings() {
<SelectContent>
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
<SelectItem value="nsite">nsite</SelectItem>
<SelectItem value="cloudflare">Cloudflare Pages</SelectItem>
<SelectItem value="netlify">Netlify</SelectItem>
<SelectItem value="vercel">Vercel</SelectItem>
</SelectContent>
@@ -832,7 +952,8 @@ export function DeploySettings() {
<>
<div className="grid gap-2">
<Label htmlFor="custom-apikey">
{customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'}
{customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'}
</Label>
<PasswordInput
id="custom-apikey"
@@ -841,14 +962,27 @@ export function DeploySettings() {
onChange={(e) => setCustomApiKey(e.target.value)}
/>
</div>
{customProviderType === 'cloudflare' && (
<div className="grid gap-2">
<Label htmlFor="custom-accountid">Account ID</Label>
<Input
id="custom-accountid"
placeholder="Enter your Cloudflare Account ID"
value={customAccountId}
onChange={(e) => setCustomAccountId(e.target.value)}
/>
</div>
)}
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">Base URL (Optional)</Label>
<Input
id="custom-baseurl"
placeholder={
customProviderType === 'netlify'
? 'https://api.netlify.com/api/v1'
: 'https://api.vercel.com'
customProviderType === 'cloudflare'
? 'https://api.cloudflare.com/client/v4'
: customProviderType === 'netlify'
? 'https://api.netlify.com/api/v1'
: 'https://api.vercel.com'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
@@ -873,7 +1007,8 @@ export function DeploySettings() {
disabled={
!customProviderType ||
!customName.trim() ||
(customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim())
(customProviderType === 'cloudflare' && (!customApiKey.trim() || !customAccountId.trim())) ||
(customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && customProviderType !== 'cloudflare' && !customApiKey.trim())
}
className="gap-2 ml-auto"
>
+564 -194
View File
@@ -1,22 +1,24 @@
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2 } from "lucide-react";
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useState, useEffect } from "react";
import { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
import { useOffline } from "@/hooks/useOffline";
import { useToast } from "@/hooks/useToast";
import { defaultSystemPrompt } from "@/lib/system";
export function SystemSettings() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { config, updateConfig } = useAppContext();
const { config, defaultConfig, updateConfig } = useAppContext();
const { toast } = useToast();
const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline();
@@ -31,6 +33,102 @@ export function SystemSettings() {
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
// Check which settings differ from defaults
const isModified = useMemo(() => ({
projectTemplate: config.projectTemplate !== defaultConfig.projectTemplate,
esmUrl: config.esmUrl !== defaultConfig.esmUrl,
corsProxy: config.corsProxy !== defaultConfig.corsProxy,
faviconUrl: config.faviconUrl !== defaultConfig.faviconUrl,
previewDomain: config.previewDomain !== defaultConfig.previewDomain,
showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled,
showcaseModerator: config.showcaseModerator !== defaultConfig.showcaseModerator,
fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects,
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
}), [config, defaultConfig]);
// Restore functions
const restoreProjectTemplate = () => {
const defaultValue = defaultConfig.projectTemplate;
setProjectTemplateInput(defaultValue);
updateConfig((current) => ({ ...current, projectTemplate: defaultValue }));
};
const restoreEsmUrl = () => {
const defaultValue = defaultConfig.esmUrl;
setEsmUrlInput(defaultValue);
updateConfig((current) => ({ ...current, esmUrl: defaultValue }));
};
const restoreCorsProxy = () => {
const defaultValue = defaultConfig.corsProxy;
setCorsProxyInput(defaultValue);
updateConfig((current) => ({ ...current, corsProxy: defaultValue }));
};
const restoreFaviconUrl = () => {
const defaultValue = defaultConfig.faviconUrl;
setFaviconUrlInput(defaultValue);
updateConfig((current) => ({ ...current, faviconUrl: defaultValue }));
};
const restorePreviewDomain = () => {
const defaultValue = defaultConfig.previewDomain;
setPreviewDomainInput(defaultValue);
updateConfig((current) => ({ ...current, previewDomain: defaultValue }));
};
const restoreShowcaseEnabled = () => {
const defaultValue = defaultConfig.showcaseEnabled;
updateConfig((current) => ({ ...current, showcaseEnabled: defaultValue }));
};
const restoreShowcaseModerator = () => {
const defaultValue = defaultConfig.showcaseModerator;
setShowcaseModeratorInput(defaultValue);
updateConfig((current) => ({ ...current, showcaseModerator: defaultValue }));
};
const restoreFsPathProjects = () => {
const defaultValue = defaultConfig.fsPathProjects;
setFsPathProjectsInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathProjects: defaultValue }));
};
const restoreFsPathConfig = () => {
const defaultValue = defaultConfig.fsPathConfig;
setFsPathConfigInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathConfig: defaultValue }));
};
const restoreFsPathTmp = () => {
const defaultValue = defaultConfig.fsPathTmp;
setFsPathTmpInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathTmp: defaultValue }));
};
const restoreFsPathPlugins = () => {
const defaultValue = defaultConfig.fsPathPlugins;
setFsPathPluginsInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathPlugins: defaultValue }));
};
const restoreSentryDsn = () => {
const defaultValue = defaultConfig.sentryDsn;
setSentryDsnInput(defaultValue);
updateConfig((current) => ({ ...current, sentryDsn: defaultValue }));
};
const restoreSystemPrompt = () => {
const defaultValue = defaultSystemPrompt;
setSystemPromptInput(defaultValue);
updateConfig((current) => ({ ...current, systemPrompt: defaultValue }));
};
// Service Worker state
const [swState, setSwState] = useState<string>('');
@@ -265,24 +363,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="project-template" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
{isModified.projectTemplate && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="project-template"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={projectTemplateInput}
onChange={(e) => {
const value = e.target.value;
setProjectTemplateInput(value);
updateConfig((current) => ({
...current,
projectTemplate: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="project-template"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={projectTemplateInput}
onChange={(e) => {
const value = e.target.value;
setProjectTemplateInput(value);
updateConfig((current) => ({
...current,
projectTemplate: value,
}));
}}
className="flex-1"
/>
{isModified.projectTemplate && (
<Button
variant="outline"
size="icon"
onClick={restoreProjectTemplate}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectTemplateDescription')}
</p>
@@ -295,24 +411,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="cors-proxy" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
{isModified.corsProxy && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="cors-proxy"
type="url"
placeholder="https://proxy.shakespeare.diy/?url={href}"
value={corsProxyInput}
onChange={(e) => {
const value = e.target.value;
setCorsProxyInput(value);
updateConfig((current) => ({
...current,
corsProxy: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="cors-proxy"
type="url"
placeholder="https://proxy.shakespeare.diy/?url={href}"
value={corsProxyInput}
onChange={(e) => {
const value = e.target.value;
setCorsProxyInput(value);
updateConfig((current) => ({
...current,
corsProxy: value,
}));
}}
className="flex-1"
/>
{isModified.corsProxy && (
<Button
variant="outline"
size="icon"
onClick={restoreCorsProxy}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('corsProxyDescription')}
</p>
@@ -325,24 +459,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="favicon-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
{isModified.faviconUrl && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="favicon-url"
type="url"
placeholder="https://favicon.shakespeare.diy/?url={href}"
value={faviconUrlInput}
onChange={(e) => {
const value = e.target.value;
setFaviconUrlInput(value);
updateConfig((current) => ({
...current,
faviconUrl: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="favicon-url"
type="url"
placeholder="https://favicon.shakespeare.diy/?url={href}"
value={faviconUrlInput}
onChange={(e) => {
const value = e.target.value;
setFaviconUrlInput(value);
updateConfig((current) => ({
...current,
faviconUrl: value,
}));
}}
className="flex-1"
/>
{isModified.faviconUrl && (
<Button
variant="outline"
size="icon"
onClick={restoreFaviconUrl}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('faviconUrlDescription')}
</p>
@@ -355,25 +507,43 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="esm-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
{isModified.esmUrl && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="esm-url"
type="url"
placeholder="https://esm.sh"
value={esmUrlInput}
onChange={(e) => {
// Strip trailing slash on save.
const value = e.target.value;
setEsmUrlInput(value);
updateConfig((current) => ({
...current,
esmUrl: value.replace(/\/+$/, ''),
}));
}}
/>
<div className="flex gap-2">
<Input
id="esm-url"
type="url"
placeholder="https://esm.sh"
value={esmUrlInput}
onChange={(e) => {
// Strip trailing slash on save.
const value = e.target.value;
setEsmUrlInput(value);
updateConfig((current) => ({
...current,
esmUrl: value.replace(/\/+$/, ''),
}));
}}
className="flex-1"
/>
{isModified.esmUrl && (
<Button
variant="outline"
size="icon"
onClick={restoreEsmUrl}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('esmUrlDescription')}
</p>
@@ -386,24 +556,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="preview-domain" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
{isModified.previewDomain && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="preview-domain"
type="text"
placeholder="local-shakespeare.dev"
value={previewDomainInput}
onChange={(e) => {
const value = e.target.value;
setPreviewDomainInput(value);
updateConfig((current) => ({
...current,
previewDomain: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="preview-domain"
type="text"
placeholder="local-shakespeare.dev"
value={previewDomainInput}
onChange={(e) => {
const value = e.target.value;
setPreviewDomainInput(value);
updateConfig((current) => ({
...current,
previewDomain: value,
}));
}}
className="flex-1"
/>
{isModified.previewDomain && (
<Button
variant="outline"
size="icon"
onClick={restorePreviewDomain}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('previewDomainDescription')}
</p>
@@ -416,47 +604,87 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="showcase" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('showcase')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('showcase')}</h4>
{(isModified.showcaseEnabled || isModified.showcaseModerator) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="flex items-center justify-between">
<Label htmlFor="showcase-enabled" className="text-sm font-medium">
{t('showcaseEnabled')}
</Label>
<Switch
id="showcase-enabled"
checked={config.showcaseEnabled}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
showcaseEnabled: checked,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="showcase-enabled" className="text-sm font-medium">
{t('showcaseEnabled')}
</Label>
{isModified.showcaseEnabled && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex items-center gap-2">
<Switch
id="showcase-enabled"
checked={config.showcaseEnabled}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
showcaseEnabled: checked,
}));
}}
/>
{isModified.showcaseEnabled && (
<Button
variant="outline"
size="icon"
onClick={restoreShowcaseEnabled}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
</div>
<p className="text-xs text-muted-foreground">
{t('showcaseEnabledDescription')}
</p>
<div className="space-y-2">
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
{t('showcaseModerator')}
</Label>
<Input
id="showcase-moderator"
type="text"
placeholder="npub1..."
value={showcaseModeratorInput}
onChange={(e) => {
const value = e.target.value;
setShowcaseModeratorInput(value);
updateConfig((current) => ({
...current,
showcaseModerator: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
{t('showcaseModerator')}
</Label>
{isModified.showcaseModerator && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="showcase-moderator"
type="text"
placeholder="npub1..."
value={showcaseModeratorInput}
onChange={(e) => {
const value = e.target.value;
setShowcaseModeratorInput(value);
updateConfig((current) => ({
...current,
showcaseModerator: value,
}));
}}
className="flex-1"
/>
{isModified.showcaseModerator && (
<Button
variant="outline"
size="icon"
onClick={restoreShowcaseModerator}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('showcaseModeratorDescription')}
</p>
@@ -470,24 +698,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="sentry-dsn" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
{isModified.sentryDsn && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="sentry-dsn"
type="text"
placeholder="https://..."
value={sentryDsnInput}
onChange={(e) => {
const value = e.target.value;
setSentryDsnInput(value);
updateConfig((current) => ({
...current,
sentryDsn: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="sentry-dsn"
type="text"
placeholder="https://..."
value={sentryDsnInput}
onChange={(e) => {
const value = e.target.value;
setSentryDsnInput(value);
updateConfig((current) => ({
...current,
sentryDsn: value,
}));
}}
className="flex-1"
/>
{isModified.sentryDsn && (
<Button
variant="outline"
size="icon"
onClick={restoreSentryDsn}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('sentryDsnDescription')}
</p>
@@ -500,97 +746,174 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="filesystem-paths" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="space-y-2">
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
{t('projectsDirectory')}
</Label>
<Input
id="fs-path-projects"
type="text"
placeholder="/projects"
value={fsPathProjectsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathProjectsInput(value);
updateConfig((current) => ({
...current,
fsPathProjects: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
{t('projectsDirectory')}
</Label>
{isModified.fsPathProjects && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-projects"
type="text"
placeholder="/projects"
value={fsPathProjectsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathProjectsInput(value);
updateConfig((current) => ({
...current,
fsPathProjects: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathProjects && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathProjects}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-config" className="text-sm font-medium">
{t('configDirectory')}
</Label>
<Input
id="fs-path-config"
type="text"
placeholder="/config"
value={fsPathConfigInput}
onChange={(e) => {
const value = e.target.value;
setFsPathConfigInput(value);
updateConfig((current) => ({
...current,
fsPathConfig: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-config" className="text-sm font-medium">
{t('configDirectory')}
</Label>
{isModified.fsPathConfig && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-config"
type="text"
placeholder="/config"
value={fsPathConfigInput}
onChange={(e) => {
const value = e.target.value;
setFsPathConfigInput(value);
updateConfig((current) => ({
...current,
fsPathConfig: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathConfig && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathConfig}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('configDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-tmp" className="text-sm font-medium">
{t('temporaryDirectory')}
</Label>
<Input
id="fs-path-tmp"
type="text"
placeholder="/tmp"
value={fsPathTmpInput}
onChange={(e) => {
const value = e.target.value;
setFsPathTmpInput(value);
updateConfig((current) => ({
...current,
fsPathTmp: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-tmp" className="text-sm font-medium">
{t('temporaryDirectory')}
</Label>
{isModified.fsPathTmp && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-tmp"
type="text"
placeholder="/tmp"
value={fsPathTmpInput}
onChange={(e) => {
const value = e.target.value;
setFsPathTmpInput(value);
updateConfig((current) => ({
...current,
fsPathTmp: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathTmp && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathTmp}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('temporaryDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
{t('pluginsDirectory')}
</Label>
<Input
id="fs-path-plugins"
type="text"
placeholder="/plugins"
value={fsPathPluginsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathPluginsInput(value);
updateConfig((current) => ({
...current,
fsPathPlugins: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
{t('pluginsDirectory')}
</Label>
{isModified.fsPathPlugins && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-plugins"
type="text"
placeholder="/plugins"
value={fsPathPluginsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathPluginsInput(value);
updateConfig((current) => ({
...current,
fsPathPlugins: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathPlugins && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathPlugins}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('pluginsDirectoryDescription')}
</p>
@@ -599,6 +922,53 @@ export function SystemSettings() {
</AccordionContent>
</AccordionItem>
</Accordion>
{/* System Prompt Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('systemPrompt')}</h4>
{isModified.systemPrompt && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<div className="flex gap-2 flex-col">
<Textarea
id="system-prompt"
placeholder="Enter EJS template..."
value={systemPromptInput}
onChange={(e) => {
const value = e.target.value;
setSystemPromptInput(value);
updateConfig((current) => ({
...current,
systemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[400px]"
/>
{isModified.systemPrompt && (
<Button
variant="outline"
onClick={restoreSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('systemPromptDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
);
+1 -1
View File
@@ -33,7 +33,7 @@ export default defineConfig(() => ({
manifest: false, // Use existing manifest.webmanifest from public folder
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, // 10 MB
maximumFileSizeToCacheInBytes: 15 * 1024 * 1024, // 15 MB (to accommodate esbuild.wasm at ~12 MB)
cleanupOutdatedCaches: true,
},
devOptions: {