* feat: embedded preview proxy for local dev servers Add a same-origin server proxy under /api/preview/proxy/:id and matching UI surfaces so local dev servers (Vite, Next, etc.) can be embedded inside OpenChamber. Server (packages/web/server): - New lib/preview/proxy-runtime.js: cookie-gated HTTP+WebSocket proxy to loopback hosts only, with TTL'd targets and SSRF allowlist. - index.js wires the runtime alongside terminal/event-stream. UI (packages/ui): - ContextPanel preview tab with iframe, reload, and open-in-browser. - Inline html code-block preview in MarkdownRenderer. - Terminal auto-detects loopback URLs and offers to open them. - i18n keys across en, es, pt-BR, uk, zh-CN. * perf(preview): cache proxy targets across PreviewPane remounts Module-scoped Map keyed by upstream URL so tab switches and component remounts within the same page session reuse the existing proxy registration instead of POSTing a fresh target each time. In-memory only by design: the server holds the target map in memory and the auth cookie is HttpOnly + scoped to the proxy id, so a stale persisted entry would 404 after a server restart. Entries are evicted on registration error and on a 30s safety margin before TTL expiry. * feat(preview): surface dev-server-down state with retry overlay Iframes don't expose HTTP status to the parent, so when the proxy returns a 502 (upstream dev server is offline) the iframe just renders the raw JSON error body. Probe the proxy URL out-of-band with HEAD (falling back to GET on 404/405) and replace the iframe with a friendly 'Dev server is not responding' overlay + retry button when the upstream is unreachable. Re-probes on reload, on URL change, and on proxy re-registration. * feat(preview): strip frame-busting response headers Many dev servers (Next.js, others) send X-Frame-Options: SAMEORIGIN and/or a CSP with frame-ancestors that block embedding inside the OpenChamber iframe. The proxy is same-origin and already authenticated per-target, so embedding is otherwise safe. - Drop X-Frame-Options outright on proxied responses. - Surgically remove only the frame-ancestors directive from Content-Security-Policy and Content-Security-Policy-Report-Only, preserving every other directive. Drops the header entirely if no directives remain. - Verified end-to-end: upstream sending both headers comes through with X-Frame-Options removed, CSP retaining default-src/script-src but no frame-ancestors, and unrelated headers untouched. * docs(preview): design for remote-host relay agent Design-only doc for the next phase of the embedded preview feature: when OpenChamber runs remotely (cloud/shared/tunnel) and the user's dev server runs on their local machine. Covers architecture (local agent + outbound control WebSocket + server dispatch), pairing flow, wire protocol, security model, failure modes, open questions, and implementation milestones. No code changes. * feat(preview): auto-open preview pane for loopback URLs in chat Detect http(s) loopback URLs in incoming assistant messages and open the preview pane automatically, deduped per (session, url) pair so re-renders or repeated mentions do not steal focus. Add an inline Preview button next to loopback links in chat markdown as a manual fallback when the auto-open was dismissed or the URL appeared in an older message. - url.ts: isLoopbackHttpUrl / extractLoopbackUrls helpers - ChatContainer: module-level dedupe Set + effect on active session tail - MarkdownRendererImpl: optional onPreviewLoopback in main renderer only (SimpleMarkdownRenderer for tool diffs is intentionally untouched) - Reuses existing terminalView.preview.open i18n keys * feat: preview enhancements, dev shutdown, and reliability fixes Add preview start/stop UI in ContextPanel/Header, improve URL detection (Python HTTP server logs, trailing punctuation, IPv6 loopback), fix proxy path filtering to avoid disrupting non-preview WebSockets. Add dev-only /api/system/dev-shutdown endpoint and Header button to terminate local dev processes and orphaned preview servers. Improve terminal cleanup with process group killing, event pipeline reconnect backoff. Update file read APIs with optional flag and cache control. Add /api/system/free-port endpoint, detectDevServer.ts utility, and preview/shutdown i18n strings for 5 languages. * fix: harden preview support * fix: keep terminal toolbar interactive * fix: keep expanded terminal below header * fix: keep preview iframe under proxy path * fix: respect project action preview urls * fix: rewrite preview asset urls * feat: capture preview console logs * feat: annotate preview elements * feat: attach preview annotation screenshots * fix: improve proxied preview hmr * feat: refine preview action UX * fix: address preview review feedback * fix: show auto-discover preview wait state --------- Co-authored-by: William Biggers <will@Williams-MacBook-Pro.local> Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
138 lines
3.5 KiB
TypeScript
138 lines
3.5 KiB
TypeScript
import { getRegisteredRuntimeAPIs } from '@/contexts/runtimeAPIRegistry';
|
|
|
|
/**
|
|
* Utility for opening external URLs with Tauri shell support.
|
|
* In desktop runtime, uses tauri.shell.open() for proper system browser handling.
|
|
* Falls back to window.open() for web runtime.
|
|
*/
|
|
|
|
type TauriShell = {
|
|
shell?: {
|
|
open?: (url: string) => Promise<unknown>;
|
|
};
|
|
};
|
|
|
|
const parseUrlSafely = (value: string): URL | null => {
|
|
try {
|
|
return new URL(value);
|
|
} catch {
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const isExternalHttpUrl = (url: string): boolean => {
|
|
const parsed = parseUrlSafely(url.trim());
|
|
if (!parsed) {
|
|
return false;
|
|
}
|
|
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
|
};
|
|
|
|
const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1']);
|
|
|
|
/**
|
|
* Returns true when the URL is an http(s) URL pointing at a loopback host
|
|
* (localhost, 127.0.0.1, 0.0.0.0, ::1). Used to decide whether to offer an in-app
|
|
* preview pane instead of opening the system browser.
|
|
*/
|
|
export const isLoopbackHttpUrl = (url: string): boolean => {
|
|
const parsed = parseUrlSafely(url.trim());
|
|
if (!parsed) {
|
|
return false;
|
|
}
|
|
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
return false;
|
|
}
|
|
return LOOPBACK_HOSTNAMES.has(parsed.hostname.toLowerCase());
|
|
};
|
|
|
|
const LOOPBACK_URL_PATTERN
|
|
// eslint-disable-next-line no-control-regex
|
|
= /\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi;
|
|
|
|
/**
|
|
* Extracts loopback http(s) URLs from a free-text string. Returns unique URLs
|
|
* in order of first appearance. Trailing punctuation that is unlikely to be
|
|
* part of a real URL is stripped.
|
|
*/
|
|
export const extractLoopbackUrls = (text: string): string[] => {
|
|
if (!text) {
|
|
return [];
|
|
}
|
|
const matches = text.match(LOOPBACK_URL_PATTERN);
|
|
if (!matches || matches.length === 0) {
|
|
return [];
|
|
}
|
|
const seen = new Set<string>();
|
|
const out: string[] = [];
|
|
for (const raw of matches) {
|
|
const cleaned = raw.replace(/[),.;:!?'"`]+$/g, '');
|
|
if (!cleaned || !isLoopbackHttpUrl(cleaned)) {
|
|
continue;
|
|
}
|
|
if (seen.has(cleaned)) {
|
|
continue;
|
|
}
|
|
seen.add(cleaned);
|
|
out.push(cleaned);
|
|
}
|
|
return out;
|
|
};
|
|
|
|
/**
|
|
* Opens an external URL in the system browser.
|
|
* In Tauri desktop runtime, uses tauri.shell.open() for proper handling.
|
|
* Falls back to window.open() for web runtime.
|
|
*
|
|
* @param url - The URL to open
|
|
* @returns Promise<boolean> - true if the URL was opened successfully
|
|
*/
|
|
export const openExternalUrl = async (url: string): Promise<boolean> => {
|
|
if (typeof window === 'undefined') {
|
|
return false;
|
|
}
|
|
|
|
const target = url.trim();
|
|
if (!target) {
|
|
return false;
|
|
}
|
|
|
|
const parsed = parseUrlSafely(target);
|
|
if (!parsed) {
|
|
return false;
|
|
}
|
|
|
|
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
return false;
|
|
}
|
|
|
|
const normalizedTarget = parsed.toString();
|
|
|
|
const runtimeApis = getRegisteredRuntimeAPIs();
|
|
if (runtimeApis?.runtime?.isVSCode && runtimeApis.vscode?.openExternalUrl) {
|
|
try {
|
|
await runtimeApis.vscode.openExternalUrl(normalizedTarget);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
const tauri = (window as unknown as { __TAURI__?: TauriShell }).__TAURI__;
|
|
if (tauri?.shell?.open) {
|
|
try {
|
|
await tauri.shell.open(normalizedTarget);
|
|
return true;
|
|
} catch {
|
|
// Fall through to window.open
|
|
}
|
|
}
|
|
|
|
try {
|
|
window.open(normalizedTarget, '_blank', 'noopener,noreferrer');
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|