Compare commits

...
Author SHA1 Message Date
Chad Curtis 272e07795e Soften tool output eviction: keep prefix and require 2+ assistant turns
- Preserve the first 1 KiB of truncated tool output instead of replacing
  with a zero-information placeholder, so the model retains partial context
  and can decide whether to re-fetch.
- Only evict tool outputs that are at least 2 assistant turns old, not
  everything before the most recent assistant message. This prevents
  truncating outputs the model may still need on the immediately following
  turn in multi-step agentic workflows.
2026-04-10 19:44:19 -05:00
Chad Curtis ebd6fc9a10 Evict large tool outputs from old messages before sending to API
Add evictSeenToolOutputs following the same pattern as evictSeenImages. Tool
results larger than 1 KiB that the model has already seen and responded to are
replaced with a short placeholder at send time. This prevents multi-MB tool
output history from being re-sent on every subsequent turn in long agentic
sessions.
2026-04-10 19:29:28 -05:00
Alex Gleason c285dbcd05 Merge branch 'fix/app-window-not-showing-on-mobile' into 'main'
fix: render AppDialog on mobile project view

See merge request soapbox-pub/shakespeare!108
2026-04-06 14:43:27 +00:00
Dmitriy E b80205a942 fix: render AppDialog on mobile project view 2026-04-06 15:13:12 +03:00
Alex Gleason 50f85f232d release: v9.11.2 2026-04-06 00:58:48 -05:00
Alex Gleason c5605c9be8 Derive private iframe.diy subdomains with HMAC-SHA256
The project ID used for the preview iframe subdomain is AI-generated
from user input. Using it directly as the iframe.diy subdomain lets
a crafted project name produce a subdomain that collides with another
project's origin, gaining access to its localStorage/IndexedDB.

Introduce a persistent random seed in localStorage (shakespeare:seed)
and derive the subdomain as base36(HMAC-SHA256(seed, prefix|identifier)).
The prefix ("preview") domain-separates different use-cases.
The subdomain is stable per device+project but unpredictable to
third parties.
2026-04-06 00:46:01 -05:00
Alex Gleason 33564842d0 release: v9.11.1 2026-04-05 23:59:06 -05:00
Alex Gleason 0511976688 Switch back to local-shakespeare.dev, which is now an iframe.diy instance 2026-04-05 23:47:55 -05:00
Alex Gleason 819813a000 Replace local-shakespeare.dev with iframe.diy for preview pane 2026-04-05 23:34:15 -05:00
Alex Gleason 2736f71687 Fix default settings overriding user's recently used models
Separate EMPTY_AI_SETTINGS (for initial state and error fallback) from
OPENCODE_DEFAULT_SETTINGS (for genuinely new users only). Previously,
readAISettings returned OPENCODE_DEFAULT_SETTINGS on any error, which
could overwrite an existing user's recentlyUsedModels with
['opencode/big-pickle']. Now the error path returns empty settings, and
OPENCODE defaults are only applied when no providers are configured.
2026-04-04 02:13:35 -05:00
Alex Gleason 0a2cbf4bca Default to OpenCode Zen with big-pickle model for zero-config first experience
Pre-configure OpenCode Zen as the default AI provider so new users can
submit prompts immediately without any setup. Sends x-opencode-* headers
to qualify for the higher daily rate limit tier.
2026-04-04 01:26:07 -05:00
Alex Gleason c359eda1d6 Fix showcase card clone URLs to use NostrURI for proper npub encoding 2026-04-04 00:10:55 -05:00
Alex Gleason 269047d742 Update default blossom servers and relay lists
Add blossom.ditto.pub and blossom.dreamith.to to the top of all blossom
server lists. Add relay.dreamith.to below relay.ditto.pub and remove
relay.damus.io and purplerelay.com from deploy relay lists.
2026-04-03 23:59:20 -05:00
Alex Gleason d2673effd8 Change default nsite gateway to shakespeare.to 2026-04-03 23:38:36 -05:00
Alex Gleason c49564e70d Support vanity subdomain URLs for nsite deployments
After deploying a named site, the adapter probes the gateway for vanity
subdomain support via X-Nsite-* response headers. When the gateway
confirms a vanity name (e.g. ditto.shakespeare.wtf), it is used as the
primary deploy URL. Gracefully degrades to the canonical base36 URL when
the gateway doesn't support vanity subdomains.
2026-04-03 22:49:38 -05:00
Alex Gleason 63671ea85b Fix SW excluding all /_* paths, breaking SvelteKit nsites
The fetch event handler was skipping all paths starting with `/_`,
intended to protect iframe-fetch-client system files. But this also
excluded SvelteKit asset paths like `/_app/immutable/chunks/*.js`,
causing them to bypass JSON-RPC and hit the network directly, which
returns HTML instead of JavaScript.

Narrow the exclusion to only `/_iframe-client/` — the specific
prefix used by the iframe-fetch-client's own assets.
2026-04-03 18:58:24 -05:00
30 changed files with 773 additions and 110 deletions

No files matched your search

+18
View File
@@ -1,5 +1,23 @@
# Changelog
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
+27 -2
View File
@@ -1,12 +1,12 @@
{
"name": "shakespeare.diy",
"version": "9.10.4",
"version": "9.11.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shakespeare.diy",
"version": "9.10.4",
"version": "9.11.2",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^8.1.0",
@@ -5001,6 +5001,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5014,6 +5015,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5027,6 +5029,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5040,6 +5043,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5053,6 +5057,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5066,6 +5071,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5079,6 +5085,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5092,6 +5099,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5105,6 +5113,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5118,6 +5127,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5131,6 +5141,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5144,6 +5155,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5157,6 +5169,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5170,6 +5183,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5183,6 +5197,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5196,6 +5211,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5209,6 +5225,7 @@
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5222,6 +5239,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5235,6 +5253,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5248,6 +5267,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5261,6 +5281,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5274,6 +5295,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5287,6 +5309,7 @@
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5300,6 +5323,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5313,6 +5337,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
+1 -1
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.11.0",
"version": "9.11.2",
"type": "module",
"author": {
"name": "shakespeare.diy",
+18
View File
@@ -1,5 +1,23 @@
# Changelog
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
+3 -11
View File
@@ -138,18 +138,10 @@ self.addEventListener("fetch", (event) => {
return;
}
// Let iframe client system files be handled normally
if (url.pathname.startsWith("/_") || url.pathname === "/sw.js") {
return;
}
// Let root path be handled normally (loads the iframe client page)
if (url.pathname === "/") {
return;
}
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
// Let iframe client system files and common assets be handled normally
if (url.pathname.startsWith("/_iframe-client/") ||
url.pathname === "/sw.js" ||
url.pathname === "/" ||
url.pathname === "/favicon.ico" ||
url.pathname === "/manifest.webmanifest") {
return;
+33 -2
View File
@@ -36,17 +36,27 @@ describe('AISettingsProvider', () => {
});
});
it('should initialize with empty recentlyUsedModels array', async () => {
it('should initialize with OpenCode defaults for new users (no providers)', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
// New users with no providers get OPENCODE_DEFAULT_SETTINGS with big-pickle
expect(result.current.settings.providers).toHaveLength(1);
expect(result.current.settings.providers[0].id).toBe('opencode');
expect(result.current.settings.recentlyUsedModels).toEqual(['opencode/big-pickle']);
});
});
it('should add recently used models correctly', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -65,6 +75,13 @@ describe('AISettingsProvider', () => {
});
it('should move existing model to front when used again', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -99,6 +116,13 @@ describe('AISettingsProvider', () => {
});
it('should limit recently used models to 10 items', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -147,6 +171,13 @@ describe('AISettingsProvider', () => {
});
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
+10 -10
View File
@@ -4,33 +4,33 @@ import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, ty
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
import { EMPTY_AI_SETTINGS, OPENCODE_DEFAULT_SETTINGS } from '@/lib/opencode-defaults';
interface AISettingsProviderProps {
children: ReactNode;
}
const DEFAULT_SETTINGS: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const queryClient = useQueryClient();
const { fs } = useFS();
const { configPath } = useFSPaths();
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
const [settings, setSettings] = useState<AISettings>(EMPTY_AI_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readAISettings(fs, configPath);
setSettings(settings);
const loaded = await readAISettings(fs, configPath);
// Only apply OpenCode defaults for genuinely new users (no providers configured)
if (loaded.providers.length === 0) {
setSettings(OPENCODE_DEFAULT_SETTINGS);
} else {
setSettings(loaded);
}
} catch (error) {
console.error('Failed to initialize AI settings:', error);
setSettings(DEFAULT_SETTINGS);
setSettings(EMPTY_AI_SETTINGS);
} finally {
setIsInitialized(true);
}
+4 -4
View File
@@ -84,9 +84,9 @@ export function AddCustomProviderDialog({
provider = {
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'nsite.lol',
gateway: customGateway.trim() || 'shakespeare.to',
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
@@ -252,7 +252,7 @@ export function AddCustomProviderDialog({
<Label htmlFor="custom-gateway">Gateway</Label>
<Input
id="custom-gateway"
placeholder="nsite.lol"
placeholder="shakespeare.to"
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
@@ -269,7 +269,7 @@ export function AddCustomProviderDialog({
items={customBlossomServers}
onChange={setCustomBlossomServers}
protocol="https"
placeholder="blossom.primal.net"
placeholder="blossom.ditto.pub"
/>
</>
) : (
+2 -1
View File
@@ -3,9 +3,10 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
providers: [DEFAULT_NSITE_PROVIDER],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
+2 -2
View File
@@ -134,7 +134,7 @@ export function ProviderConfigDialog({
</Label>
<Input
id="provider-gateway"
placeholder="nsite.lol"
placeholder="shakespeare.to"
value={localProvider.gateway || ''}
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
@@ -152,7 +152,7 @@ export function ProviderConfigDialog({
items={localProvider.blossomServers ?? []}
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
protocol="https"
placeholder="blossom.primal.net"
placeholder="blossom.ditto.pub"
required
/>
</>
+92 -29
View File
@@ -1,5 +1,5 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
@@ -25,6 +25,8 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
import { isMediaFile } from '@/lib/fileUtils';
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
interface PreviewPaneProps {
projectId: string;
@@ -67,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
// Derive a private, stable subdomain from a device-local seed + the project ID.
// This prevents malicious project names from colliding with another project's
// origin on iframe.diy, protecting localStorage/IndexedDB isolation.
const previewSubdomain = useMemo(() => deriveIframeSubdomain('preview', projectId), [projectId]);
const previewOrigin = useMemo(() => `https://${previewSubdomain}.${previewDomain}`, [previewSubdomain, previewDomain]);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
@@ -182,18 +191,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
@@ -248,6 +254,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [historyIndex, navigationHistory]);
const sendNotification = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
jsonrpc: '2.0' as const,
method,
params: params || {},
};
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [previewOrigin]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
@@ -256,10 +273,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
params: params || {},
id: Date.now()
};
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
@@ -275,6 +291,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
setIsFullscreen(prev => !prev);
}, []);
/** Virtual path where the injected preview script is served. */
const INJECTED_SCRIPT_PATH = '/__injected__/preview.js';
/** Inject a script tag into an HTML string using DOMParser. */
const injectScript = useCallback((html: string): string => {
const doc = new DOMParser().parseFromString(html, 'text/html');
const tag = doc.createElement('script');
tag.src = INJECTED_SCRIPT_PATH;
doc.head.insertBefore(tag, doc.head.firstChild);
return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -282,16 +310,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
if (url.origin !== previewOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
sendError({
jsonrpc: '2.0',
error: {
code: -32003,
message: 'Invalid URL - origin mismatch',
data: { url: fetchRequest.url, expectedOrigin }
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
},
id
});
@@ -301,24 +328,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const path = url.pathname;
const filePath = path;
// Serve the injected preview script at its virtual path
if (path === INJECTED_SCRIPT_PATH) {
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'no-cache',
},
body: encodeBase64(new TextEncoder().encode(getPreviewInjectedScript())),
},
id
});
return;
}
// Skip SPA fallback for static assets (files with extensions)
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
// SPA routing: try to serve the exact file first
try {
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
const contentType = getContentType(filePath);
console.log(`Serving file: ${filePath}`);
// Inject preview script into HTML responses
let body: string;
if (contentType === 'text/html') {
const html = new TextDecoder().decode(bytes);
body = encodeBase64(new TextEncoder().encode(injectScript(html)));
} else {
body = encodeBase64(bytes);
}
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': getContentType(filePath),
'Content-Type': contentType,
'Cache-Control': 'no-cache',
},
body: encodeBase64(bytes),
body,
},
id
});
@@ -349,6 +404,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
// Inject preview script into SPA fallback HTML
const html = new TextDecoder().decode(bytes);
const body = encodeBase64(new TextEncoder().encode(injectScript(html)));
sendResponse({
jsonrpc: '2.0',
result: {
@@ -358,7 +417,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
},
body: encodeBase64(bytes),
body,
},
id
});
@@ -389,32 +448,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
id
});
}
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
// Setup messaging protocol for iframe communication
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
if (event.origin !== previewOrigin) {
return;
}
const message = event.data;
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
// Handle iframe.diy handshake: respond to "ready" with "init"
if (message.method === 'ready') {
sendNotification('init', { version: 1 });
return;
}
if (message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
} else if (message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
} else if (message.method === 'updateNavigationState') {
handleUpdateNavigationState(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
useEffect(() => {
if (selectedFile) {
@@ -647,10 +711,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
src={`${previewOrigin}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
+2
View File
@@ -612,6 +612,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<span className="font-medium">{nsiteVfsConfig.title}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Relays</span>
<span className="font-medium">{relayCount} configured</span>
@@ -798,6 +799,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
+1 -1
View File
@@ -44,7 +44,7 @@ export interface AppConfig {
faviconUrl: string;
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
ngitWebUrl: string;
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
previewDomain: string;
/** Selected language */
language?: string;
+2 -1
View File
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query';
import { nip19 } from 'nostr-tools';
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
import { useAppContext } from '@/hooks/useAppContext';
import { NostrURI } from '@/lib/NostrURI';
export interface AppSubmission extends NostrEvent {
appName: string;
@@ -79,7 +80,7 @@ function repositoryUrlFromATag(aTagValue: string): string {
const parts = aTagValue.split(':');
if (parts.length < 3) return '';
const [, pubkey, identifier] = parts;
return `nostr://${pubkey}/${identifier}`;
return new NostrURI({ pubkey, identifier }).toString();
}
export function useAppSubmissions() {
+2 -2
View File
@@ -66,7 +66,7 @@ describe('useGenerateProjectInfo', () => {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
showcaseEnabled: true,
showcaseCurator: '',
graspMetadata: {
@@ -230,7 +230,7 @@ describe('useGenerateProjectInfo', () => {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
showcaseEnabled: true,
showcaseCurator: '',
graspMetadata: {
+2 -1
View File
@@ -14,8 +14,9 @@ export function useUploadFile() {
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
'https://blossom.ditto.pub/',
'https://blossom.dreamith.to/',
'https://blossom.primal.net/',
],
signer: user.signer,
});
+1 -1
View File
@@ -46,7 +46,7 @@ const testConfig: AppConfig = {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
language: 'en',
showcaseEnabled: true,
showcaseCurator: '',
+38
View File
@@ -396,6 +396,41 @@ export class SessionManager {
});
};
// Replace large tool result content with a truncated prefix for messages the
// model has already seen and responded to at least twice. Like evictSeenImages,
// this is a send-time transformation only — session.messages stays intact for
// the UI. We keep the first TOOL_OUTPUT_EVICTION_THRESHOLD bytes so the model
// retains partial context and can decide whether to re-fetch the full output.
const TOOL_OUTPUT_EVICTION_THRESHOLD = 1024; // 1 KiB
const TOOL_OUTPUT_MIN_ASSISTANT_TURNS = 2; // Only evict after 2+ assistant responses
const evictSeenToolOutputs = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
// Collect indices of all assistant messages.
const assistantIndices: number[] = [];
for (let i = 0; i < msgs.length; i++) {
if (msgs[i].role === 'assistant') {
assistantIndices.push(i);
}
}
// Need at least TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1 assistant messages:
// the ones that have "seen" the tool output, plus the current pending turn.
if (assistantIndices.length < TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1) return msgs;
// The eviction cutoff is the assistant message N turns back from the end.
// Tool results before this index have been processed by at least N assistant
// turns, so truncating them is safe.
const cutoffIdx = assistantIndices[assistantIndices.length - TOOL_OUTPUT_MIN_ASSISTANT_TURNS];
return msgs.map((msg, idx) => {
if (idx >= cutoffIdx) return msg;
if (msg.role !== 'tool') return msg;
if (typeof msg.content !== 'string') return msg;
if (msg.content.length <= TOOL_OUTPUT_EVICTION_THRESHOLD) return msg;
return { ...msg, content: msg.content.slice(0, TOOL_OUTPUT_EVICTION_THRESHOLD) + '\n\n[… truncated]' };
});
};
// Prepare messages for AI
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
@@ -403,6 +438,9 @@ export class SessionManager {
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Evict large tool outputs the model has already processed.
messages = evictSeenToolOutputs(messages);
// Evict images the model has already seen (all except the last user message).
// This is a send-time transformation only — session.messages stays intact for the UI.
messages = evictSeenImages(messages);
+10
View File
@@ -36,6 +36,16 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
request = new Request(request, { headers });
}
// Add OpenCode headers for higher rate limit
if (provider.id === 'opencode' || provider.baseURL === 'https://opencode.ai/zen/v1') {
const headers = new Headers(request.headers);
headers.set('x-opencode-project', 'shakespeare');
headers.set('x-opencode-session', 'shakespeare');
headers.set('x-opencode-request', crypto.randomUUID());
headers.set('x-opencode-client', 'shakespeare');
request = new Request(request, { headers });
}
// If Nostr authentication is required and we have a user, use NIP-98
if (provider.nostr && user?.signer) {
// Create the NIP98 token
+5 -12
View File
@@ -7,6 +7,7 @@ import {
readDeploySettings,
writeDeploySettings
} from './configUtils';
import { EMPTY_AI_SETTINGS } from './opencode-defaults';
import type { JSRuntimeFS } from './JSRuntime';
import type { AISettings } from '@/contexts/AISettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
@@ -89,30 +90,22 @@ describe('configUtils', () => {
});
});
it('should return default settings if file does not exist and no localStorage data', async () => {
it('should return empty settings if file does not exist and no localStorage data', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
mockLocalStorage.getItem.mockReturnValue(null);
const result = await readAISettings(mockFS);
expect(result).toEqual({
providers: [],
recentlyUsedModels: [],
mcpServers: {},
});
expect(result).toEqual(EMPTY_AI_SETTINGS);
});
it('should return default settings if JSON is invalid and no localStorage data', async () => {
it('should return empty settings if JSON is invalid and no localStorage data', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
mockLocalStorage.getItem.mockReturnValue(null);
const result = await readAISettings(mockFS);
expect(result).toEqual({
providers: [],
recentlyUsedModels: [],
mcpServers: {},
});
expect(result).toEqual(EMPTY_AI_SETTINGS);
});
});
+2 -7
View File
@@ -1,6 +1,7 @@
import z from 'zod';
import { filteredArray } from '@/lib/schema';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import { EMPTY_AI_SETTINGS } from '@/lib/opencode-defaults';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
@@ -169,12 +170,6 @@ async function ensureConfigDir(fs: JSRuntimeFS, configPath = '/config'): Promise
* @param configPath - Custom config path (default: /config)
*/
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
const defaultSettings: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
try {
const aiConfigPath = getAIConfigPath(configPath);
const content = await fs.readFile(aiConfigPath, 'utf8');
@@ -210,7 +205,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
if (error instanceof z.ZodError) {
console.error('AI settings parsing error:', error.issues);
}
return defaultSettings;
return EMPTY_AI_SETTINGS;
}
}
+91 -2
View File
@@ -76,6 +76,84 @@ async function createBatchUploadAuth(
return `Nostr ${btoa(JSON.stringify(signed))}`;
}
/**
* Vanity subdomain name rules from VANITY.md:
* - 1–49 characters long
* - lowercase letters, digits, and hyphens only
* - cannot start or end with a hyphen
*/
const VANITY_NAME_REGEX = /^[a-z0-9]([a-z0-9-]{0,47}[a-z0-9])?$/;
const VANITY_RESERVED_NAMES = new Set([
'www', 'api', 'status', 'admin', 'mail', 'smtp', 'imap', 'pop', 'ftp',
'ns1', 'ns2', 'ns3', 'ns4', 'localhost', 'autoconfig', 'autodiscover', '_dmarc',
]);
/**
* Check whether a site identifier qualifies as a valid vanity name candidate.
* This is a client-side pre-check — the gateway is the source of truth.
*/
function isVanityCandidate(name: string): boolean {
return (
name.length >= 1 &&
name.length <= 49 &&
VANITY_NAME_REGEX.test(name) &&
!VANITY_RESERVED_NAMES.has(name)
);
}
/**
* After a named-site deploy, probe the gateway to see if a vanity subdomain was
* assigned. Not all gateways support vanity subdomains, so this is best-effort.
*
* Returns the vanity URL (e.g. "https://ditto.shakespeare.wtf") if the gateway
* confirms the vanity name belongs to this pubkey, or `undefined` otherwise.
*/
async function probeVanityUrl(
gateway: string,
siteIdentifier: string,
pubkey: string,
): Promise<string | undefined> {
// Quick client-side guard — skip the network request if the name is obviously invalid
if (!isVanityCandidate(siteIdentifier)) {
return undefined;
}
const vanityOrigin = `https://${siteIdentifier}.${gateway}`;
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const resp = await fetch(`${vanityOrigin}/`, {
method: 'HEAD',
signal: controller.signal,
});
// Check for the X-Nsite-* headers that indicate vanity support
const nsitePubkey = resp.headers.get('x-nsite-pubkey');
const nsiteName = resp.headers.get('x-nsite-name');
// Vanity name is confirmed when the gateway returns the name header
// AND the pubkey matches ours (i.e. we own this vanity name).
if (nsiteName && nsitePubkey === pubkey) {
return vanityOrigin;
}
// If the response is a 404 with X-Nsite-Available: true, the name hasn't
// been reserved yet. It will likely be claimed once the gateway processes
// our manifest, but we can't confirm it right now — return undefined and
// let the next deploy pick it up.
return undefined;
} finally {
clearTimeout(timer);
}
} catch {
// Network error, gateway doesn't support vanity, CORS blocked, etc.
return undefined;
}
}
/**
* Check whether a blob already exists on a Blossom server.
* Returns true if the server responds 2xx to a HEAD request.
@@ -327,7 +405,7 @@ export class NsiteAdapter implements DeployAdapter {
// no separate kind 10002 or kind 10063 events are published.
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
// Build the deployed URL
// Build the canonical deployed URL (always the long-form base36 or npub URL)
const siteUrl = buildNsiteUrl({
pubkeyHex: pubkey,
npub,
@@ -335,8 +413,17 @@ export class NsiteAdapter implements DeployAdapter {
siteIdentifier: this.siteIdentifier,
});
// For named sites, probe whether the gateway assigned a vanity subdomain.
// This is best-effort — if the gateway doesn't support vanity, we just
// return the canonical URL and move on.
let vanityUrl: string | undefined;
if (isNamedSite && this.siteIdentifier) {
vanityUrl = await probeVanityUrl(this.gateway, this.siteIdentifier, pubkey);
}
return {
url: siteUrl,
// Prefer the short vanity URL when confirmed by the gateway
url: vanityUrl ?? siteUrl,
metadata: {
pubkey,
npub,
@@ -344,6 +431,8 @@ export class NsiteAdapter implements DeployAdapter {
provider: 'nsite',
siteIdentifier: this.siteIdentifier,
manifestKind,
vanityUrl,
canonicalUrl: siteUrl,
},
};
}
+22
View File
@@ -1,5 +1,27 @@
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from './deploy/types';
/** Default nsite provider configuration, pre-configured for new users. */
export const DEFAULT_NSITE_PROVIDER: NsiteProvider = {
id: 'nsite',
name: 'nsite',
type: 'nsite',
gateway: 'shakespeare.to',
relayUrls: [
'wss://relay.ditto.pub',
'wss://relay.dreamith.to',
'wss://relay.nsite.lol',
'wss://relay.nosto.re',
'wss://relay.primal.net',
],
blossomServers: [
'https://blossom.ditto.pub',
'https://blossom.dreamith.to',
'https://blossom.primal.net',
'https://cdn.sovbit.host',
],
};
export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
{
id: 'shakespeare',
+54
View File
@@ -0,0 +1,54 @@
import { hmac } from '@noble/hashes/hmac';
import { sha256 } from '@noble/hashes/sha256';
import { bytesToHex } from '@noble/hashes/utils';
const SEED_STORAGE_KEY = 'shakespeare:seed';
/**
* Encode a hex string as a zero-padded 50-character base36 string.
* Replicates the encoding used for nsite subdomains.
*/
function hexToBase36(hex: string): string {
let n = 0n;
for (let i = 0; i < hex.length; i++) {
n = n * 16n + BigInt(parseInt(hex[i], 16));
}
return n.toString(36).padStart(50, '0');
}
/**
* Get or create a device-local random seed persisted in localStorage.
* This is a general-purpose secret used to derive private identifiers
* (e.g. iframe.diy subdomains) that must not be predictable by third parties.
*/
function getSeed(): string {
const stored = localStorage.getItem(SEED_STORAGE_KEY);
if (stored) return stored;
const seed = crypto.randomUUID();
localStorage.setItem(SEED_STORAGE_KEY, seed);
return seed;
}
/**
* Derive a stable, private subdomain label for an iframe.diy iframe.
*
* Uses HMAC-SHA256 with the device-local seed as the key and
* `prefix|identifier` as the message. Because the seed is secret to
* this device, a third party cannot predict or collide with another
* app's subdomain, preventing cross-app localStorage/IndexedDB access
* on iframe.diy.
*
* The `prefix` acts as a domain separator so that different use-cases
* (e.g. "preview", "sandbox") produce distinct subdomains even for the
* same identifier.
*
* The result is a 50-character base36 string (256 bits of entropy) that
* fits within the 63-character subdomain label limit.
*/
export function deriveIframeSubdomain(prefix: string, identifier: string): string {
const seed = getSeed();
const enc = new TextEncoder();
const mac = hmac(sha256, enc.encode(seed), enc.encode(`${prefix}|${identifier}`));
return hexToBase36(bytesToHex(mac));
}
+25
View File
@@ -0,0 +1,25 @@
import type { AISettings } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
const opencodePreset = AI_PROVIDER_PRESETS.find((p) => p.id === 'opencode')!;
/** Empty AI settings used as initial state and error fallback. Won't overwrite user data. */
export const EMPTY_AI_SETTINGS: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
/** Default AI settings with OpenCode Zen pre-configured and big-pickle selected. Only for genuinely new users. */
export const OPENCODE_DEFAULT_SETTINGS: AISettings = {
providers: [
{
id: opencodePreset.id,
name: opencodePreset.name,
baseURL: opencodePreset.baseURL,
proxy: opencodePreset.proxy,
},
],
recentlyUsedModels: ['opencode/big-pickle'],
mcpServers: {},
};
+297
View File
@@ -0,0 +1,297 @@
/**
* Script injected into preview iframe HTML responses.
*
* When using iframe.diy as the preview domain, the outer frame handles
* service worker registration and document loading. However, Shakespeare
* needs additional capabilities inside the rendered app:
*
* 1. Console interception - forward console.log/warn/error/info/debug to parent
* 2. Navigation handling - track SPA navigation and handle navigate/refresh commands
* 3. Global error handlers - capture uncaught errors and unhandled rejections
*
* This script is injected into <head> of HTML responses served by the fetch handler.
* It communicates with the parent via window.parent.postMessage using JSON-RPC 2.0.
*
* Note: In iframe.diy's architecture, the "parent" of the inner iframe is the
* outer frame, which transparently relays non-runtime JSON-RPC messages to the
* actual parent (Shakespeare). So posting to window.parent works correctly.
*/
/**
* Returns the injectable script as a string.
* This runs inside the inner iframe of iframe.diy.
*/
export function getPreviewInjectedScript(): string {
return `(function() {
'use strict';
// =========================================================================
// Path normalization
//
// iframe.diy loads the inner iframe at /index.html. Normalize this to /
// before any SPA router initializes, so React Router etc. see the correct
// path.
// =========================================================================
if (window.location.pathname === '/index.html') {
history.replaceState(null, '', '/');
}
// =========================================================================
// JSON-RPC ID generator
//
// iframe.diy's outer frame only relays JSON-RPC *requests* (messages with
// an "id" field) between inner iframe and parent. Notifications (no "id")
// are silently dropped. So all messages to the parent must include an id.
// =========================================================================
function rpcId() {
return crypto.randomUUID();
}
// =========================================================================
// Console Interceptor
// =========================================================================
var originalConsole = {};
var consoleMethods = ['log', 'warn', 'error', 'info', 'debug'];
consoleMethods.forEach(function(method) {
if (typeof console[method] === 'function') {
originalConsole[method] = console[method];
console[method] = function() {
var args = Array.prototype.slice.call(arguments);
// Call original method
try {
originalConsole[method].apply(console, args);
} catch (e) {
// Continue if original fails
}
// Serialize arguments
var message = args.map(function(arg) {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, function(key, value) {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch (e) {
return String(arg);
}
}
return String(arg);
}).join(' ');
// Send to parent (must include id for iframe.diy relay)
try {
window.parent.postMessage({
jsonrpc: '2.0',
id: rpcId(),
method: 'console',
params: { level: method, message: message }
}, '*');
} catch (e) {
// Ignore postMessage errors
}
};
}
});
// =========================================================================
// Navigation Handler
// =========================================================================
var currentSemanticPath = '/';
// Try to restore initial path from sessionStorage (after refresh)
try {
var storedPath = sessionStorage.getItem('iframe_initial_path');
if (storedPath) {
currentSemanticPath = storedPath;
sessionStorage.removeItem('iframe_initial_path');
}
} catch (e) {
// Ignore sessionStorage errors
}
function extractSemanticPath(urlOrString) {
try {
var url = typeof urlOrString === 'string'
? new URL(urlOrString, window.location.origin)
: urlOrString;
return url.pathname + url.search + url.hash;
} catch (e) {
return window.location.pathname + window.location.search + window.location.hash;
}
}
function updateNavigationState() {
var semanticPath = currentSemanticPath || extractSemanticPath(window.location);
try {
window.parent.postMessage({
jsonrpc: '2.0',
id: ++rpcId,
method: 'updateNavigationState',
params: {
currentUrl: semanticPath,
canGoBack: false,
canGoForward: false
}
}, '*');
} catch (e) {
// Ignore postMessage errors
}
}
function handleNavigate(url) {
try {
var targetUrl = new URL(url, window.location.origin);
if (targetUrl.origin !== window.location.origin) {
return;
}
var semanticPath = extractSemanticPath(targetUrl);
currentSemanticPath = semanticPath;
updateNavigationState();
// Use the original pushState to trigger SPA navigation
originalPushState.call(window.history, {}, '', semanticPath);
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
} catch (e) {
// Ignore invalid URLs
}
}
function handleRefresh() {
var path = currentSemanticPath || '/';
try {
sessionStorage.setItem('iframe_initial_path', path);
} catch (e) {
// Ignore sessionStorage errors
}
window.location.reload();
}
// Listen for commands from parent (navigate, refresh)
window.addEventListener('message', function(event) {
// Only accept messages from parent window
if (event.source !== window.parent) return;
var message = event.data;
if (message && message.jsonrpc === '2.0') {
switch (message.method) {
case 'navigate':
handleNavigate(message.params.url);
break;
case 'refresh':
handleRefresh();
break;
}
}
});
// Listen for popstate events (back/forward navigation)
window.addEventListener('popstate', function() {
currentSemanticPath = extractSemanticPath(window.location);
updateNavigationState();
});
// Listen for hash changes
window.addEventListener('hashchange', function() {
currentSemanticPath = extractSemanticPath(window.location);
updateNavigationState();
});
// Override history.pushState and history.replaceState to detect SPA navigation
var originalPushState = window.history.pushState;
var originalReplaceState = window.history.replaceState;
window.history.pushState = function() {
var result = originalPushState.apply(window.history, arguments);
var semanticPath = arguments[2]
? extractSemanticPath(arguments[2])
: extractSemanticPath(window.location);
currentSemanticPath = semanticPath;
updateNavigationState();
return result;
};
window.history.replaceState = function() {
var result = originalReplaceState.apply(window.history, arguments);
var semanticPath = arguments[2]
? extractSemanticPath(arguments[2])
: extractSemanticPath(window.location);
currentSemanticPath = semanticPath;
updateNavigationState();
return result;
};
// Send initial navigation state
updateNavigationState();
// After a short delay, navigate to initial path if needed (for refresh support)
if (currentSemanticPath && currentSemanticPath !== '/') {
setTimeout(function() {
var current = window.location.pathname + window.location.search + window.location.hash;
if (current !== currentSemanticPath) {
handleNavigate(currentSemanticPath);
}
}, 150);
}
// =========================================================================
// Global Error Handlers
// =========================================================================
window.addEventListener('error', function(event) {
try {
window.parent.postMessage({
jsonrpc: '2.0',
id: ++rpcId,
method: 'console',
params: {
level: 'error',
message: 'Uncaught Error: ' + event.message,
source: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error ? event.error.stack : undefined
}
}, '*');
} catch (e) {
// Ignore postMessage errors
}
});
window.addEventListener('unhandledrejection', function(event) {
try {
window.parent.postMessage({
jsonrpc: '2.0',
id: ++rpcId,
method: 'console',
params: {
level: 'error',
message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
}
}, '*');
} catch (e) {
// Ignore postMessage errors
}
});
})();`;
}
+1 -1
View File
@@ -33,7 +33,7 @@ const testConfig: AppConfig = {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
language: 'en',
showcaseEnabled: true,
showcaseCurator: '',
+1 -1
View File
@@ -45,7 +45,7 @@ export class BlossomUploadTool implements Tool<BlossomUploadParams> {
});
const uploader = new BlossomUploader({
servers: ['https://blossom.primal.net/', 'https://blossom.ditto.pub/'],
servers: ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/', 'https://blossom.primal.net/'],
signer: this.signer,
});
+2 -19
View File
@@ -9,7 +9,7 @@ import { useVercelOAuth } from '@/hooks/useVercelOAuth';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
@@ -202,24 +202,7 @@ export function DeploySettings() {
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'nsite') {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'nsite',
gateway: 'nosto.re',
relayUrls: [
'wss://relay.ditto.pub',
'wss://relay.nsite.lol',
'wss://relay.nosto.re',
'wss://relay.primal.net',
'wss://relay.damus.io',
'wss://purplerelay.com',
],
blossomServers: [
'https://blossom.primal.net',
'https://cdn.sovbit.host',
],
};
newProvider = { ...DEFAULT_NSITE_PROVIDER };
} else if (preset.type === 'netlify') {
newProvider = {
id: preset.id, // Use preset ID for presets
+5
View File
@@ -389,6 +389,11 @@ export function ProjectView() {
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
/>
<AppDialog
projectId={project.id}
open={appDialogOpen}
onOpenChange={setAppDialogOpen}
/>
</>
)}
</div>