feat(preview): embedded dev-server preview pane + dev shutdown controls (#1062)

* 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>
This commit is contained in:
wpbiggs
2026-04-30 00:03:38 +03:00
committed by GitHub
co-authored by William Biggers Bohdan Triapitsyn
parent 67d05a23fc
commit bd9a91335c
37 changed files with 4238 additions and 399 deletions
+209
View File
@@ -0,0 +1,209 @@
import type { OpenChamberProjectAction } from './openchamberConfig';
import { getRegisteredRuntimeAPIs } from '@/contexts/runtimeAPIRegistry';
type DevServerInfo = {
command: string;
label: string;
actionId?: string;
previewUrlHint?: string;
};
type PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';
const DEV_COMMAND_PATTERNS = [
{ pattern: /^dev(:.*)?$/i },
{ pattern: /^start(:.*)?$/i },
{ pattern: /^preview(:.*)?$/i },
{ pattern: /^serve(:.*)?$/i },
{ pattern: /^develop(:.*)?$/i },
];
const COMMON_DEV_COMMANDS = [
'dev',
'start',
'preview',
'serve',
];
/**
* Detect the dev server command from project actions or package.json scripts
*/
export async function detectDevServerCommand(
directory: string,
projectActions: OpenChamberProjectAction[],
packageJsonScripts: Record<string, string> | null,
): Promise<DevServerInfo | null> {
if (!directory) return null;
// First, check if there's a project action that looks like a dev server
const devAction = findDevServerAction(projectActions);
if (devAction) {
return {
command: devAction.command,
label: devAction.name || 'Start Preview',
actionId: devAction.id,
};
}
// Then, check package.json scripts
if (packageJsonScripts) {
const devScript = findDevScript(packageJsonScripts);
if (devScript) {
// Determine the package manager command
const pm = await detectPackageManager(directory);
const pmCommand = pm === 'npm' ? 'npm run' : pm === 'yarn' ? 'yarn' : pm === 'pnpm' ? 'pnpm' : pm === 'bun' ? 'bun' : 'npm run';
return {
command: `${pmCommand} ${devScript}`,
label: `Start (${devScript})`,
};
}
}
// Fallback: static sites (no package.json) can be previewed via a simple file server.
// This keeps Start Preview usable for non-Node projects.
if (await hasStaticIndexHtml(directory)) {
const port = await allocatePreviewPort();
const resolvedPort = typeof port === 'number' && Number.isFinite(port) && port > 0 ? port : 8000;
return {
command: `python3 -m http.server ${resolvedPort}`,
label: 'Static preview',
previewUrlHint: `http://127.0.0.1:${resolvedPort}/`,
};
}
return null;
}
async function hasStaticIndexHtml(directory: string): Promise<boolean> {
const target = `${directory}/index.html`;
const content = await readOptionalTextFile(target);
return typeof content === 'string' && content.trim().length > 0;
}
async function allocatePreviewPort(): Promise<number | null> {
try {
const response = await fetch('/api/system/free-port', { cache: 'no-store' });
if (!response.ok) return null;
const body = await response.json().catch(() => null) as { port?: unknown } | null;
const port = typeof body?.port === 'number' ? body.port : null;
return port && Number.isFinite(port) ? port : null;
} catch {
return null;
}
}
/**
* Find a project action that looks like a dev server
*/
function findDevServerAction(actions: OpenChamberProjectAction[]): OpenChamberProjectAction | null {
// Look for actions with "dev", "preview", "start" in the name or command
for (const action of actions) {
const nameAndCommand = `${action.name} ${action.command}`.toLowerCase();
// Check if it's likely a dev server action
const isDevAction = COMMON_DEV_COMMANDS.some(cmd =>
nameAndCommand.includes(cmd)
);
if (isDevAction) {
return action;
}
}
// Fallback: return the first action if there's only one
if (actions.length === 1) {
return actions[0];
}
return null;
}
/**
* Find a dev script in package.json scripts
*/
function findDevScript(scripts: Record<string, string>): string | null {
for (const { pattern } of DEV_COMMAND_PATTERNS) {
for (const scriptName of Object.keys(scripts)) {
if (pattern.test(scriptName)) {
return scriptName;
}
}
}
return null;
}
/**
* Simple package manager detection based on lock files
* Note: This is intentionally a simple client-side check.
* For server-side operations, the server's package-manager.js is used.
*/
async function detectPackageManager(directory: string): Promise<PackageManager> {
const packageJsonContent = await readOptionalTextFile(`${directory}/package.json`);
if (packageJsonContent) {
try {
const pkg = JSON.parse(packageJsonContent) as { packageManager?: unknown };
const packageManager = typeof pkg.packageManager === 'string' ? pkg.packageManager.toLowerCase() : '';
if (packageManager.startsWith('bun@')) return 'bun';
if (packageManager.startsWith('pnpm@')) return 'pnpm';
if (packageManager.startsWith('yarn@')) return 'yarn';
if (packageManager.startsWith('npm@')) return 'npm';
} catch {
// Ignore malformed package.json here; readPackageJsonScripts handles it separately.
}
}
const lockfiles: Array<[string, PackageManager]> = [
['bun.lock', 'bun'],
['bun.lockb', 'bun'],
['pnpm-lock.yaml', 'pnpm'],
['yarn.lock', 'yarn'],
['package-lock.json', 'npm'],
];
for (const [fileName, packageManager] of lockfiles) {
const content = await readOptionalTextFile(`${directory}/${fileName}`);
if (typeof content === 'string' && content.trim().length > 0) {
return packageManager;
}
}
return 'npm';
}
async function readOptionalTextFile(path: string): Promise<string | null> {
const runtimeFiles = getRegisteredRuntimeAPIs()?.files;
if (runtimeFiles?.readFile) {
try {
const result = await runtimeFiles.readFile(path, { optional: true });
return typeof result?.content === 'string' ? result.content : null;
} catch {
return null;
}
}
try {
const response = await fetch(`/api/fs/read?path=${encodeURIComponent(path)}&optional=true`, {
cache: 'no-store',
});
if (!response.ok) return null;
return response.text();
} catch {
return null;
}
}
/**
* Read package.json scripts from a directory
*/
export async function readPackageJsonScripts(directory: string): Promise<Record<string, string> | null> {
try {
const content = await readOptionalTextFile(`${directory}/package.json`);
if (content == null) return null;
const pkg = JSON.parse(content);
return pkg.scripts || null;
} catch {
return null;
}
}