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
+59
View File
@@ -696,12 +696,26 @@ export const dict: Record<I18nKey, string> = {
"contextPanel.mode.diff": "Diff",
"contextPanel.mode.plan": "Plan",
"contextPanel.mode.context": "Contexto",
"contextPanel.mode.preview": "Vista previa",
"contextPanel.tab.closeTabAria": "Cerrar pestaña {label}",
"contextPanel.actions.collapsePanel": "Colapsar panel",
"contextPanel.actions.expandPanel": "Expandir panel",
"contextPanel.actions.closePanel": "Cerrar panel",
"contextPanel.actions.resizePanelAria": "Ajustar tamaño del panel de contexto",
"contextPanel.iframe.sessionChatTitle": "Chat de sesión {sessionID}",
"contextPanel.preview.actions.reload": "Recargar vista previa",
"contextPanel.preview.actions.openExternal": "Abrir en el navegador",
"contextPanel.preview.actions.retry": "Reintentar",
"contextPanel.preview.iframeTitle": "Vista previa",
"contextPanel.preview.invalidUrl": "La vista previa necesita una URL http(s) válida.",
"contextPanel.preview.empty": "Sin URL de vista previa",
"contextPanel.preview.loading": "Conectando proxy de vista previa...",
"contextPanel.preview.proxyError": "No se pudo iniciar el proxy de vista previa.",
"contextPanel.preview.upstreamUnreachable": "El servidor de desarrollo no responde.",
"contextPanel.preview.upstreamUnreachableHint": "Verifica que tu servidor de desarrollo siga en ejecución y vuelve a intentarlo.",
"terminalView.preview.open": "Vista previa",
"terminalView.preview.openTitle": "Abrir panel de vista previa",
"sidebarFilesTree.menu.rename": "Cambiar nombre",
"sidebarFilesTree.menu.copyPath": "Copiar ruta",
"sidebarFilesTree.menu.save": "Guardar",
@@ -959,6 +973,7 @@ export const dict: Record<I18nKey, string> = {
"header.services.used": "Usado",
"header.services.remaining": "Restante",
"header.services.modelFamily.other": "Otro",
"header.services.shutdownDev": "Detener OpenChamber",
"header.actions.openPlanAria": "Abrir plan",
"header.actions.planWithShortcut": "Plan ({shortcut})",
"header.actions.terminalPanelWithShortcut": "Panel de terminal ({shortcut})",
@@ -1330,6 +1345,8 @@ export const dict: Record<I18nKey, string> = {
"chat.messageBody.actions.fork": "Bifurcar desde aquí",
"chat.messageBody.actions.copyMessageAria": "Copiar texto del mensaje",
"chat.messageBody.actions.copyMessage": "Copiar mensaje",
"chat.messageBody.actions.openPreviewAria": "Abrir vista previa",
"chat.messageBody.actions.openPreview": "Abrir vista previa",
"chat.messageBody.actions.copyAnswer": "Copiar respuesta",
"chat.messageBody.actions.savingImage": "Guardando imagen...",
"chat.messageBody.actions.saveAsImage": "Guardar como imagen",
@@ -1383,6 +1400,11 @@ export const dict: Record<I18nKey, string> = {
"chat.chatInput.toast.openSessionFirst": "Abre una sesión primero",
"chat.chatInput.toast.togglePermissionAutoAcceptFailed": "No se pudo cambiar la aceptación automática de permisos",
"chat.chatInput.reviewComments": "Comentarios de revisión:",
"chat.chatInput.devServerLogs": "Logs del Dev Server:",
"chat.chatInput.devServerLogsRemove": "Quitar logs del Dev Server",
"chat.chatInput.previewAnnotations": "Anotaciones de vista previa:",
"chat.chatInput.previewContext": "Contexto de vista previa:",
"chat.chatInput.previewContextRemove": "Quitar contexto de vista previa",
"chat.chatInput.projectRoot": "Raíz del proyecto",
"chat.chatInput.branch": "Rama",
"chat.chatInput.worktrees": "Worktrees",
@@ -1763,7 +1785,9 @@ export const dict: Record<I18nKey, string> = {
"projectActions.actions.addActionAria": "Añadir acción",
"projectActions.actions.addAction": "Añadir acción",
"projectActions.actions.addNewAction": "Añadir nueva acción",
"projectActions.actions.autoDiscover": "Autodetectar",
"projectActions.actions.chooseActionAria": "Elegir acción del proyecto",
"projectActions.actions.openPreview": "Abrir Preview",
"projectActions.actions.runNamedAria": "Ejecutar {name}",
"projectActions.actions.stopNamedAria": "Detener {name}",
"projectActions.label.fallbackAction": "Acción",
@@ -2092,4 +2116,39 @@ export const dict: Record<I18nKey, string> = {
"markdownRenderer.mermaid.actions.copySourceTitle": "Copiar fuente",
"markdownRenderer.mermaid.actions.downloadSvgTitle": "Descargar SVG",
"markdownRenderer.mermaid.toast.downloadFailed": "No se pudo descargar el diagrama",
"contextPanel.preview.title": "Vista previa",
"contextPanel.preview.description": "Usa Acciones del proyecto o el botón Preview del terminal para abrir una vista previa.",
"contextPanel.preview.startPreview": "Iniciar vista previa",
"contextPanel.preview.starting": "Iniciando...",
"contextPanel.preview.noDevServer": "No se encontro un comando de servidor de desarrollo. Configura una accion del proyecto o anade un script \"dev\" a package.json.",
"contextPanel.preview.startFailed": "Fallo al iniciar el servidor de vista previa.",
"contextPanel.preview.serverExited": "El servidor de desarrollo se cerro inesperadamente.",
"contextPanel.preview.noUrlDetected": "El servidor de desarrollo se inicio, pero no se detecto ningun URL en su salida. Abre la pestaña de terminal de vista previa para ver los registros.",
"contextPanel.preview.serverExitedWithLog": "El servidor de desarrollo terminó inesperadamente. Última salida:\n\n{log}",
"contextPanel.preview.noUrlDetectedWithLog": "El servidor de desarrollo no respondió. Última salida:\n\n{log}",
"contextPanel.preview.startingServer": "Iniciando servidor de desarrollo...",
"contextPanel.preview.startingServerHint": "Esperando a que el servidor acepte conexiones.",
"contextPanel.preview.console.open": "Abrir consola de vista previa",
"contextPanel.preview.console.waiting": "Esperando la consola de vista previa",
"contextPanel.preview.console.title": "Consola de vista previa",
"contextPanel.preview.console.attach": "Adjuntar",
"contextPanel.preview.console.copy": "Copiar",
"contextPanel.preview.console.clear": "Limpiar",
"contextPanel.preview.console.empty": "Aún no hay eventos de consola de vista previa.",
"contextPanel.preview.console.noFilteredEvents": "Ningún evento coincide con este filtro.",
"contextPanel.preview.console.runtimeError": "Error de ejecución",
"contextPanel.preview.console.copied": "Consola de vista previa copiada",
"contextPanel.preview.console.copyFailed": "No se pudo copiar la consola de vista previa",
"contextPanel.preview.console.attached": "Consola de vista previa adjuntada al chat",
"contextPanel.preview.console.attachNoSession": "Abre una sesión de chat antes de adjuntar logs de vista previa",
"contextPanel.preview.console.attachAnnotation": "Estos son logs de la consola del navegador del servidor de desarrollo que se ejecuta para este proyecto.",
"contextPanel.preview.inspect.toggle": "Inspeccionar elemento de vista previa",
"contextPanel.preview.inspect.attached": "Anotación de vista previa adjuntada al chat",
"contextPanel.preview.inspect.attachNoSession": "Abre una sesión de chat antes de adjuntar anotaciones de vista previa",
"contextPanel.preview.inspect.attachAnnotation": "Este es un elemento DOM seleccionado de la vista previa integrada.",
"contextPanel.preview.inspect.attachAnnotationWithScreenshot": "Este es un elemento DOM seleccionado de la vista previa integrada. Se adjunta una captura del área visible de la vista previa con el elemento resaltado.",
"contextPanel.preview.console.filter.all": "Todo",
"contextPanel.preview.console.filter.errors": "Errores",
"contextPanel.preview.console.filter.warnings": "Advertencias",
"contextPanel.preview.console.filter.logs": "Registros",
};