Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6385: feat(chat): add editable live HTML preview (#7188)
Azmandious0c9f50d1f47a
diff --git a/e2e/live-html-preview.spec.ts b/e2e/live-html-preview.spec.tsnew file mode 100644index 0000000000..e77f4075f5--- /dev/null+++ b/e2e/live-html-preview.spec.ts@@ -0,0 +1,219 @@+import "./env";++import { expect, test } from "@playwright/test";+import pg from "pg";++import { createTestApi } from "./helpers";+import type { TestApiClient } from "./fixtures";++const DATABASE_URL =+ process.env.DATABASE_URL ??+ "postgres://multica:***@localhost:5432/multica?sslmode=disable";++const ORIGINAL_HTML = [+ "<!doctype html>",+ '<html lang="en">',+ "<head>",+ ' <meta charset="utf-8">',+ " <title>Live preview fixture</title>",+ "</head>",+ "<body>",+ " <main>",+ " <h1>Original preview</h1>",+ " <p>Assistant generated HTML.</p>",+ " </main>",+ "</body>",+ "</html>",+].join("\n");++const EDITED_HTML = ORIGINAL_HTML.replace("Original preview", "Edited live preview");++async function horizontalOverflowPx(page: import("@playwright/test").Page) {+ return page.evaluate(() => {+ const viewportWidth = document.documentElement.clientWidth;+ return Math.max(+ 0,+ ...Array.from(document.querySelectorAll<HTMLElement>("body *"))+ .filter((element) => {+ const style = window.getComputedStyle(element);+ return style.display !== "none" && style.visibility !== "hidden";+ })+ .map((element) => Math.ceil(element.getBoundingClientRect().right - viewportWidth)),+ );+ });+}++test("edits an assistant HTML preview live without mutating message history", async ({+ page,+}) => {+ const api: TestApiClient = await createTestApi();+ const db = new pg.Client(DATABASE_URL);+ await db.connect();++ let sessionId: string | null = null;+ let agentId: string | null = null;+ let runtimeId: string | null = null;++ try {+ const workspace = (await api.getWorkspaces())[0];+ if (!workspace) throw new Error("E2E workspace missing");+ api.setWorkspaceId(workspace.id);+ api.setWorkspaceSlug(workspace.slug);++ const user = await db.query<{ id: string }>(+ `SELECT id::text FROM "user" WHERE email = $1 LIMIT 1`,+ [api.getEmail()],+ );+ const userId = user.rows[0]?.id;+ if (!userId) throw new Error("E2E user missing");++ const runtime = await db.query<{ id: string }>(+ `INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status,+ device_info, metadata, last_seen_at+ )+ VALUES ($1, NULL, $2, 'cloud', 'e2e_live_preview', 'online', $3, '{}'::jsonb, now())+ RETURNING id::text`,+ [workspace.id, `Live preview ${Date.now()}`, "Live preview E2E"],+ );+ runtimeId = runtime.rows[0]!.id;++ const agent = await db.query<{ id: string }>(+ `INSERT INTO agent (+ workspace_id, name, description, instructions, runtime_mode,+ runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id+ )+ VALUES ($1, 'Live Preview Agent', 'Generates preview fixtures', '', 'cloud',+ '{}'::jsonb, $2, 'workspace', 1, $3)+ RETURNING id::text`,+ [workspace.id, runtimeId, userId],+ );+ agentId = agent.rows[0]!.id;++ const session = await db.query<{ id: string }>(+ `INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)+ VALUES ($1, $2, $3, 'Live preview workspace', 'active')+ RETURNING id::text`,+ [workspace.id, agentId, userId],+ );+ sessionId = session.rows[0]!.id;++ await db.query(+ `INSERT INTO chat_message (chat_session_id, role, content, created_at)+ VALUES+ ($1, 'user', 'Build a reviewable HTML concept.', now() - interval '1 second'),+ ($1, 'assistant', $2, now())`,+ [sessionId, ["```html", ORIGINAL_HTML, "```"].join("\n")],+ );++ const token = api.getToken();+ if (!token) throw new Error("E2E token missing");+ await page.addInitScript(+ ({ authToken, activeSessionId }) => {+ localStorage.setItem("multica_token", authToken);+ localStorage.setItem("multica:chat:activeSessionId", activeSessionId);+ localStorage.setItem("multica:chat:isOpen", "false");+ },+ { authToken: token, activeSessionId: sessionId },+ );++ await page.setViewportSize({ width: 1440, height: 960 });+ await page.goto(`/${workspace.slug}/chat?session=${sessionId}`, {+ waitUntil: "domcontentloaded",+ });++ const htmlBlock = page.locator(".code-block-wrapper").filter({+ has: page.locator('iframe[title="HTML preview"]'),+ });+ await expect(htmlBlock).toBeVisible({ timeout: 30_000 });+ await htmlBlock.hover();+ await page.getByRole("button", { name: "Edit live preview" }).click();++ const editor = page.getByRole("textbox", { name: "HTML editor" });+ await expect(editor).toHaveValue(ORIGINAL_HTML);+ await expect(page.getByText("Original", { exact: true })).toBeVisible();++ await editor.fill(EDITED_HTML);+ await expect(page.getByText("Local draft", { exact: true })).toBeVisible();+ const liveFrame = page.frameLocator('iframe[title="Live preview workspace"]');+ await expect(liveFrame.getByRole("heading", { name: "Edited live preview" })).toBeVisible();++ if (process.env.LIVE_PREVIEW_DESKTOP_SCREENSHOT_PATH) {+ await page.screenshot({+ path: process.env.LIVE_PREVIEW_DESKTOP_SCREENSHOT_PATH,+ fullPage: true,+ });+ }++ await page.getByRole("button", { name: "Reset changes" }).click();+ await expect(editor).toHaveValue(ORIGINAL_HTML);+ await expect(page.getByText("Original", { exact: true })).toBeVisible();+ await expect(liveFrame.getByRole("heading", { name: "Original preview" })).toBeVisible();++ await page.keyboard.press("Escape");+ await page.setViewportSize({ width: 390, height: 844 });+ await htmlBlock.hover();+ await page.getByRole("button", { name: "Edit live preview" }).click();+ const mobileEditor = page.getByRole("textbox", { name: "HTML editor" });+ await mobileEditor.fill(EDITED_HTML);+ const mobileFrame = page.frameLocator('iframe[title="Live preview workspace"]');+ await expect(mobileEditor).toBeVisible();+ await expect(mobileFrame.getByRole("heading", { name: "Edited live preview" })).toBeVisible();+ expect(await horizontalOverflowPx(page)).toBe(0);++ if (process.env.LIVE_PREVIEW_MOBILE_SCREENSHOT_PATH) {+ await page.screenshot({+ path: process.env.LIVE_PREVIEW_MOBILE_SCREENSHOT_PATH,+ fullPage: true,+ });+ }++ await page.keyboard.press("Escape");+ await page.setViewportSize({ width: 390, height: 430 });+ await htmlBlock.hover();+ await page.getByRole("button", { name: "Edit live preview" }).click();+ const shortEditor = page.getByRole("textbox", { name: "HTML editor" });+ await shortEditor.fill(EDITED_HTML);++ const shortPreviewElement = page.locator('iframe[title="Live preview workspace"]');+ await shortPreviewElement.scrollIntoViewIfNeeded();+ const shortFrame = page.frameLocator('iframe[title="Live preview workspace"]');+ await expect(+ shortFrame.getByRole("heading", { name: "Edited live preview" }),+ ).toBeVisible();++ if (process.env.LIVE_PREVIEW_SHORT_SCREENSHOT_PATH) {+ await page.screenshot({+ path: process.env.LIVE_PREVIEW_SHORT_SCREENSHOT_PATH,+ fullPage: true,+ });+ }++ await shortEditor.scrollIntoViewIfNeeded();+ await expect(shortEditor).toBeVisible();+ await shortEditor.fill(ORIGINAL_HTML);+ await expect(shortEditor).toHaveValue(ORIGINAL_HTML);+ expect(await horizontalOverflowPx(page)).toBe(0);++ const persisted = await db.query<{ content: string }>(+ `SELECT content FROM chat_message+ WHERE chat_session_id = $1 AND role = 'assistant'+ ORDER BY created_at DESC LIMIT 1`,+ [sessionId],+ );+ expect(persisted.rows[0]?.content).toContain("Original preview");+ expect(persisted.rows[0]?.content).not.toContain("Edited live preview");+ } finally {+ if (sessionId) {+ await db.query(`DELETE FROM agent_task_queue WHERE chat_session_id = $1`, [+ sessionId,+ ]);+ await db.query(`DELETE FROM chat_session WHERE id = $1`, [sessionId]);+ }+ if (agentId) await db.query(`DELETE FROM agent WHERE id = $1`, [agentId]);+ if (runtimeId)+ await db.query(`DELETE FROM agent_runtime WHERE id = $1`, [runtimeId]);+ await db.end();+ await api.cleanup();+ }+});diff --git a/packages/views/editor/html-block-preview.test.tsx b/packages/views/editor/html-block-preview.test.tsxindex 0d9ab6a399..8f25f5af12 100644--- a/packages/views/editor/html-block-preview.test.tsx+++ b/packages/views/editor/html-block-preview.test.tsx@@ -10,6 +10,13 @@ vi.mock("../i18n", () => ({show_preview: "Show preview",show_source: "Show source",fullscreen: "Fullscreen",+ edit_preview: "Edit live preview",+ live_workspace: "Live preview workspace",+ editor_label: "HTML editor",+ local_draft: "Local draft",+ original: "Original",+ reset_changes: "Reset changes",+ copy_changes: "Copy changes",},}),}),@@ -87,3 +94,36 @@ describe("HtmlBlockPreview — Maximize → Dialog", () => {}});});++describe("HtmlBlockPreview — live preview workspace", () => {+ it("opens an editable split view and updates the sandboxed preview live", () => {+ render(<HtmlBlockPreview html="<p>original</p>" />);++ fireEvent.click(screen.getByTitle("Edit live preview"));++ const editor = screen.getByLabelText("HTML editor") as HTMLTextAreaElement;+ expect(editor.value).toBe("<p>original</p>");+ expect(screen.getByText("Original")).toBeTruthy();++ fireEvent.change(editor, { target: { value: "<h1>changed</h1>" } });++ expect(editor.value).toBe("<h1>changed</h1>");+ expect(screen.getByText("Local draft")).toBeTruthy();+ const frames = document.querySelectorAll("iframe");+ const liveFrame = frames[frames.length - 1]!;+ expect(liveFrame.getAttribute("srcdoc")?.startsWith("<h1>changed</h1>")).toBe(true);+ expect(liveFrame.getAttribute("sandbox")).toBe("allow-scripts");+ });++ it("resets a local edit to the assistant's original HTML", () => {+ render(<HtmlBlockPreview html="<p>original</p>" />);+ fireEvent.click(screen.getByTitle("Edit live preview"));++ const editor = screen.getByLabelText("HTML editor") as HTMLTextAreaElement;+ fireEvent.change(editor, { target: { value: "<p>draft</p>" } });+ fireEvent.click(screen.getByRole("button", { name: "Reset changes" }));++ expect(editor.value).toBe("<p>original</p>");+ expect(screen.getByText("Original")).toBeTruthy();+ });+});diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsxindex ed3f854861..228e9a224d 100644--- a/packages/views/editor/html-block-preview.tsx+++ b/packages/views/editor/html-block-preview.tsx@@ -21,6 +21,8 @@ import {Check,Code as CodeIcon,Copy,+ Pencil,+ RotateCcw,Eye,Maximize2,} from "lucide-react";@@ -57,7 +59,9 @@ export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {const { t } = useT("editor");const [view, setView] = useState<"preview" | "source">("preview");const [copied, setCopied] = useState(false);- const [fullscreen, setFullscreen] = useState(false);+ const [dialogMode, setDialogMode] = useState<"preview" | "edit" | null>(null);+ const [draftHtml, setDraftHtml] = useState(html);+ const isDirty = draftHtml !== html;const handleCopy = async () => {if (!html) return;@@ -70,6 +74,19 @@ export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {const toggleView = () =>setView((v) => (v === "preview" ? "source" : "preview"));+ const openEditor = () => {+ setDraftHtml(html);+ setDialogMode("edit");+ };++ const handleCopyDraft = async () => {+ if (!draftHtml) return;+ if (await copyText(draftHtml)) {+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }+ };+return (<div className={cn("code-block-wrapper group/code relative my-3", className)}><div@@ -98,15 +115,26 @@ export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {)}</button>{view === "preview" && (- <button- type="button"- onClick={() => setFullscreen(true)}- className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"- title={t(($) => $.code_block.fullscreen)}- aria-label={t(($) => $.code_block.fullscreen)}- >- <Maximize2 className="h-3.5 w-3.5" />- </button>+ <>+ <button+ type="button"+ onClick={openEditor}+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"+ title={t(($) => $.code_block.edit_preview)}+ aria-label={t(($) => $.code_block.edit_preview)}+ >+ <Pencil className="h-3.5 w-3.5" />+ </button>+ <button+ type="button"+ onClick={() => setDialogMode("preview")}+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"+ title={t(($) => $.code_block.fullscreen)}+ aria-label={t(($) => $.code_block.fullscreen)}+ >+ <Maximize2 className="h-3.5 w-3.5" />+ </button>+ </>)}<buttontype="button"@@ -131,17 +159,85 @@ export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {) : (<CodeBlockStatic language="xml" body={html} />)}- <Dialog open={fullscreen} onOpenChange={setFullscreen}>+ <Dialog+ open={dialogMode !== null}+ onOpenChange={(open) => {+ if (!open) setDialogMode(null);+ }}+ ><DialogContentclassName="!max-w-6xl !h-[min(90vh,calc(100vh-2rem))] w-full p-0 gap-0 overflow-hidden"- aria-label={t(($) => $.code_block.fullscreen)}+ aria-label={+ dialogMode === "edit"+ ? t(($) => $.code_block.live_workspace)+ : t(($) => $.code_block.fullscreen)+ }>- <HtmlPreviewBody- source={{ kind: "inline", html }}- title="HTML preview"- className="h-full w-full"- iframeClassName="rounded-none border-0"- />+ {dialogMode === "edit" ? (+ <div className="flex h-full min-h-0 flex-col bg-background">+ <div className="flex min-h-12 items-center gap-3 border-b border-border px-4 pr-12">+ <div className="min-w-0 flex-1">+ <p className="truncate text-body font-medium text-foreground">+ {t(($) => $.code_block.live_workspace)}+ </p>+ <p className="text-caption text-muted-foreground">+ {isDirty+ ? t(($) => $.code_block.local_draft)+ : t(($) => $.code_block.original)}+ </p>+ </div>+ <button+ type="button"+ onClick={() => setDraftHtml(html)}+ disabled={!isDirty}+ className="flex h-8 items-center gap-1.5 rounded-md px-2.5 text-caption text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40"+ aria-label={t(($) => $.code_block.reset_changes)}+ >+ <RotateCcw className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">+ {t(($) => $.code_block.reset_changes)}+ </span>+ </button>+ <button+ type="button"+ onClick={handleCopyDraft}+ className="flex h-8 items-center gap-1.5 rounded-md bg-foreground px-2.5 text-caption text-background transition-opacity hover:opacity-85"+ aria-label={t(($) => $.code_block.copy_changes)}+ >+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ <span className="hidden sm:inline">+ {t(($) => $.code_block.copy_changes)}+ </span>+ </button>+ </div>+ <div className="grid min-h-0 flex-1 grid-rows-[minmax(220px,0.8fr)_minmax(260px,1.2fr)] overflow-y-auto overscroll-contain md:grid-cols-[minmax(320px,0.85fr)_minmax(0,1.15fr)] md:grid-rows-1 md:overflow-hidden">+ <div className="min-h-0 border-b border-border bg-muted/20 md:border-r md:border-b-0">+ <textarea+ value={draftHtml}+ onChange={(event) => setDraftHtml(event.target.value)}+ aria-label={t(($) => $.code_block.editor_label)}+ className="h-full min-h-[220px] w-full resize-none bg-transparent p-4 font-mono text-caption leading-relaxed text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"+ spellCheck={false}+ />+ </div>+ <div className="min-h-0 bg-background">+ <HtmlPreviewBody+ source={{ kind: "inline", html: draftHtml }}+ title={t(($) => $.code_block.live_workspace)}+ className="h-full min-h-[260px] w-full"+ iframeClassName="rounded-none border-0"+ />+ </div>+ </div>+ </div>+ ) : (+ <HtmlPreviewBody+ source={{ kind: "inline", html }}+ title="HTML preview"+ className="h-full w-full"+ iframeClassName="rounded-none border-0"+ />+ )}</DialogContent></Dialog></div>diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 6784647467..1182a51640 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -91,7 +91,14 @@"copy_code": "Copy code","show_preview": "Show preview","show_source": "Show source",- "fullscreen": "Fullscreen"+ "fullscreen": "Fullscreen",+ "edit_preview": "Edit live preview",+ "live_workspace": "Live preview workspace",+ "editor_label": "HTML editor",+ "local_draft": "Local draft",+ "original": "Original",+ "reset_changes": "Reset changes",+ "copy_changes": "Copy changes"},"file_card": {"uploading": "Uploading {{filename}}"diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 630d0e06f9..5fe9ba2c12 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -84,7 +84,14 @@"copy_code": "コードをコピー","show_preview": "プレビューを表示","show_source": "ソースを表示",- "fullscreen": "全画面"+ "fullscreen": "全画面",+ "edit_preview": "ライブプレビューを編集",+ "live_workspace": "ライブプレビュー",+ "editor_label": "HTML エディター",+ "local_draft": "ローカル下書き",+ "original": "元の内容",+ "reset_changes": "変更をリセット",+ "copy_changes": "変更をコピー"},"file_card": {"uploading": "{{filename}} をアップロード中"diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex db3caf56cc..227cfe3ba3 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -84,7 +84,14 @@"copy_code": "코드 복사","show_preview": "미리보기 표시","show_source": "소스 표시",- "fullscreen": "전체 화면"+ "fullscreen": "전체 화면",+ "edit_preview": "실시간 미리보기 편집",+ "live_workspace": "실시간 미리보기 작업공간",+ "editor_label": "HTML 편집기",+ "local_draft": "로컬 초안",+ "original": "원본",+ "reset_changes": "변경 사항 초기화",+ "copy_changes": "변경 사항 복사"},"file_card": {"uploading": "{{filename}} 업로드 중"diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 93eea6c69d..655c35336c 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -91,7 +91,14 @@"copy_code": "复制代码","show_preview": "显示预览","show_source": "显示源码",- "fullscreen": "放大"+ "fullscreen": "放大",+ "edit_preview": "编辑实时预览",+ "live_workspace": "实时预览工作区",+ "editor_label": "HTML 编辑器",+ "local_draft": "本地草稿",+ "original": "原始版本",+ "reset_changes": "重置更改",+ "copy_changes": "复制更改"},"file_card": {"uploading": "正在上传 {{filename}}"