Repository navigation
Agent chat: a reply's html/svg fence draws as a sandboxed inline preview #30673
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c4f9351
Agent chat: draw a reply's closed html/svg fence as a sandboxed inlin…
teamleaderleo bfce631
Merge remote-tracking branch 'origin/feat-cmux-next' into inline-html…
teamleaderleo c6ba4ce
Inline preview: keep frames on their document; no network hints; scri…
teamleaderleo 74ebf5a
Inline preview: links that leave the document point to # (no speculat…
teamleaderleo 9936b66
Inline preview: draw in the native artifact frame in the app; fix the…
teamleaderleo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
122 changes: 122 additions & 0 deletions
122
webviews/src/agent-session/acpmux/conversation/InlinePreview.gallery.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| // l10n-allow-file: gallery fixtures (sample prompts, replies and documents), not shipped UI. | ||
| // A reply's closed ```html or ```svg fence drawn inline as its document (InlinePreview.tsx), in a frame | ||
| // sandboxed with allow-scripts and no same-origin, behind a policy with no network. Code shows the | ||
| // source card (Copy stays); Open puts it in the side panel. An open fence stays plain code, and a | ||
| // document that carries script stays the code card; Open puts it in the side panel, where Run is. | ||
| import { agentPaneEntry } from "../../../gallery/format"; | ||
| import { assistant, chat, summary, user } from "../../../gallery/fixtures/acpmux"; | ||
| import type { PlayContext } from "../../../gallery/play"; | ||
|
|
||
| const fence = (lang: string, code: string, close = true) => "```" + lang + "\n" + code + (close ? "\n```" : "\n"); | ||
|
|
||
| const reply = (prompt: string, text: string, streaming = false) => | ||
| chat( | ||
| streaming | ||
| ? [user(prompt, 6), assistant(text, 0.5, { streaming: true })] | ||
| : [user(prompt, 6), assistant(text, 5), summary(5, { status: "completed", durationMs: 24_000 })], | ||
| ); | ||
|
|
||
| const bars: [string, number][] = [ | ||
| ["Mon", 42], | ||
| ["Tue", 58], | ||
| ["Wed", 35], | ||
| ["Thu", 71], | ||
| ["Fri", 64], | ||
| ]; | ||
|
|
||
| /// A bar chart as one SVG image: bars, values and day labels, in the chat's text colour. | ||
| const barChart = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 200" width="360" height="200" font-family="system-ui" font-size="11"> | ||
| <title>Builds per day</title> | ||
| <line x1="30" y1="170" x2="350" y2="170" stroke="currentColor" stroke-opacity="0.3"/> | ||
| ${bars | ||
| .map(([day, value], index) => { | ||
| const x = 44 + index * 62; | ||
| const height = value * 2; | ||
| return ` <rect x="${x}" y="${170 - height}" width="36" height="${height}" rx="4" fill="#3b82f6"/> | ||
| <text x="${x + 18}" y="${164 - height}" text-anchor="middle" fill="currentColor">${value}</text> | ||
| <text x="${x + 18}" y="186" text-anchor="middle" fill="currentColor" fill-opacity="0.6">${day}</text>`; | ||
| }) | ||
| .join("\n")} | ||
| </svg>`; | ||
|
|
||
| const rows: [string, number, number][] = [ | ||
| ["1st year", 5, 7], | ||
| ["2nd year", 5, 9], | ||
| ["3rd year", 6, 8], | ||
| ]; | ||
|
|
||
| /// A study-guide section: a table of hours and the same numbers as a line chart, side by side. | ||
| const tableAndChart = `<!doctype html> | ||
| <html> | ||
| <head><title>Study hours by year</title> | ||
| <style> | ||
| .grid { display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap; } | ||
| th, td { padding: 4px 10px; text-align: right; } | ||
| th:first-child, td:first-child { text-align: left; } | ||
| </style></head> | ||
| <body> | ||
| <h3>Study hours by year</h3> | ||
| <div class="grid"> | ||
| <table> | ||
| <thead><tr><th>Year</th><th>Psych</th><th>Neuro</th></tr></thead> | ||
| <tbody> | ||
| ${rows.map(([year, psych, neuro]) => ` <tr><td>${year}</td><td>${psych}</td><td>${neuro}</td></tr>`).join("\n")} | ||
| </tbody> | ||
| </table> | ||
| <svg viewBox="0 0 240 140" width="240" height="140" font-size="10" font-family="system-ui"> | ||
| <line x1="20" y1="120" x2="230" y2="120" stroke="currentColor" stroke-opacity="0.3"/> | ||
| <polyline fill="none" stroke="#3b82f6" stroke-width="2" points="${rows.map(([, psych], index) => `${40 + index * 80},${120 - psych * 10}`).join(" ")}"/> | ||
| <polyline fill="none" stroke="#ef4444" stroke-width="2" stroke-dasharray="4 3" points="${rows.map(([, , neuro], index) => `${40 + index * 80},${120 - neuro * 10}`).join(" ")}"/> | ||
| ${rows.map(([year], index) => ` <text x="${40 + index * 80}" y="134" text-anchor="middle" fill="currentColor" fill-opacity="0.6">${year}</text>`).join("\n")} | ||
| <text x="230" y="20" text-anchor="end" fill="#3b82f6">Psych</text> | ||
| <text x="230" y="34" text-anchor="end" fill="#ef4444">Neuro</text> | ||
| </svg> | ||
| </div> | ||
| </body> | ||
| </html>`; | ||
|
|
||
| const counter = `<title>Counter</title> | ||
| <button onclick="this.textContent = Number(this.textContent) + 1">0</button>`; | ||
|
|
||
| export default agentPaneEntry({ | ||
| id: "agent-pane.inline-preview", | ||
| title: "Inline HTML and SVG preview", | ||
| area: "Agent pane", | ||
| height: 640, | ||
| covers: [ | ||
| "agent-session/acpmux/conversation/InlinePreview.tsx", | ||
| "agent-session/acpmux/conversation/previewDocument.ts", | ||
| ], | ||
| variants: { | ||
| "svg-bar-chart": { | ||
| note: "An SVG bar chart in a reply draws as the chart.", | ||
| snapshot: reply( | ||
| "Chart builds per day this week", | ||
| `Builds per day:\n\n${fence("svg", barChart)}\n\nThursday peaked at 71.`, | ||
| ), | ||
| }, | ||
| "html-table-chart": { | ||
| note: "An HTML section with a table and the same numbers as a line chart.", | ||
| snapshot: reply( | ||
| "Make a study-guide section for these hours", | ||
| `Here is the section:\n\n${fence("html", tableAndChart)}\n\nNeuro rises in the 2nd year.`, | ||
| ), | ||
| }, | ||
| code: { | ||
| note: "Code swaps the preview for the source card, which keeps Copy.", | ||
| snapshot: reply("Chart builds per day this week", `Builds per day:\n\n${fence("svg", barChart)}`), | ||
| play: async (ctx: PlayContext) => { | ||
| await ctx.click({ role: "button", name: "Code" }); | ||
| await ctx.waitFor(() => ctx.document.querySelector(".cv-codeblock")); | ||
| }, | ||
| }, | ||
| streaming: { | ||
| note: "A fence still arriving stays plain code: nothing renders until it closes.", | ||
| snapshot: reply("Chart builds per day this week", `Builds per day:\n\n${fence("svg", barChart, false)}`, true), | ||
| }, | ||
| scripted: { | ||
| note: "A document with script stays the code card; Open takes it to the side panel, where Run is.", | ||
| snapshot: reply("Make a counter", fence("html", counter)), | ||
| }, | ||
| }, | ||
| }); |
177 changes: 177 additions & 0 deletions
177
webviews/src/agent-session/acpmux/conversation/InlinePreview.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,177 @@ | ||
| // A closed ```html or ```svg fence in a reply, drawn as the document it holds (leo-workspace | ||
| // design/artifacts.md). The preview is an iframe sandboxed with `allow-scripts` and no | ||
| // `allow-same-origin`, whose `srcdoc` starts with the artifact policy: no network, and no script but | ||
| // the client's own nonce'd frame script (previewDocument.ts), which reports the height and keeps the | ||
| // frame on its document. Its height follows the frame's report, accepted only from that frame's | ||
| // window, capped at 480 px (Expand lifts the cap), and the document scrolls past it. A document that | ||
| // carries script stays the code card, whose Open puts it in the side panel, where Run is (#26216). | ||
| // Code shows the source card, which keeps Copy. Markdown.tsx draws this only once the fence has | ||
| // closed: an open fence stays plain code, so no frame is made or reloaded per token. The frame mounts | ||
| // once the card nears the viewport, so a long chat does not start every frame at once. | ||
| import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; | ||
| import { useT } from "../i18n"; | ||
| import { useNearViewport } from "../useNearViewport"; | ||
| import { artifactNeedsRun } from "./artifactSandbox"; | ||
| import { CodeBlock, languageLabel } from "./CodeBlock"; | ||
| import { CopyButton } from "./CopyButton"; | ||
| import { OpenPreview } from "./OpenPreview"; | ||
| import { renderFrameCSS } from "./renderBase"; | ||
| import { | ||
| INLINE_PREVIEW_EXPANDED_MAX_HEIGHT, | ||
| INLINE_PREVIEW_MAX_HEIGHT, | ||
| INLINE_PREVIEW_MIN_HEIGHT, | ||
| INLINE_PREVIEW_SANDBOX, | ||
| inlinePreviewDocument, | ||
| previewNonce, | ||
| reportedHeight, | ||
| } from "./previewDocument"; | ||
|
|
||
| export function InlinePreview({ | ||
| kind, | ||
| code, | ||
| lang, | ||
| actions, | ||
| }: { | ||
| kind: "html" | "svg"; | ||
| code: string; | ||
| lang: string; | ||
| actions?: ReactNode; | ||
| }) { | ||
| const t = useT(); | ||
| const [showCode, setShowCode] = useState(false); | ||
| const [expanded, setExpanded] = useState(false); | ||
| // The frame left its document (its frame counts its loads): the card shows the source. | ||
| const [left, setLeft] = useState(false); | ||
| const scripted = useMemo(() => artifactNeedsRun(code), [code]); | ||
| if (scripted || left) return <CodeBlock code={code} lang={lang} actions={actions} />; | ||
| const toggle = ( | ||
| <button | ||
| type="button" | ||
| className="cv-codeblock__action cv-codeblock__action--text" | ||
| aria-pressed={showCode} | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3: This toggle changes its label and also sets Prompt for AI agents |
||
| onClick={() => setShowCode((value) => !value)} | ||
| > | ||
| {showCode ? t("artifact.preview") : t("artifact.code")} | ||
| </button> | ||
| ); | ||
| if (showCode) | ||
| return ( | ||
| <CodeBlock | ||
| code={code} | ||
| lang={lang} | ||
| actions={ | ||
| <> | ||
| {toggle} | ||
| {actions} | ||
| </> | ||
| } | ||
| /> | ||
| ); | ||
| return ( | ||
| <FrameCard | ||
| kind={kind} | ||
| code={code} | ||
| lang={lang} | ||
| expanded={expanded} | ||
| onExpand={() => setExpanded((value) => !value)} | ||
| onLeave={() => setLeft(true)} | ||
| head={ | ||
| <> | ||
| {toggle} | ||
| <OpenPreview code={code} lang={lang} /> | ||
| <CopyButton text={code} label={t("code.copy")} /> | ||
| {actions} | ||
| </> | ||
| } | ||
| /> | ||
| ); | ||
| } | ||
|
|
||
| function FrameCard({ | ||
| kind, | ||
| code, | ||
| lang, | ||
| expanded, | ||
| onExpand, | ||
| onLeave, | ||
| head, | ||
| }: { | ||
| kind: "html" | "svg"; | ||
| code: string; | ||
| lang: string; | ||
| expanded: boolean; | ||
| onExpand(): void; | ||
| onLeave(): void; | ||
| head: ReactNode; | ||
| }) { | ||
| const t = useT(); | ||
| const [card, setCard] = useState<HTMLDivElement | null>(null); | ||
| const near = useNearViewport(card); | ||
| const [height, setHeight] = useState(INLINE_PREVIEW_MIN_HEIGHT); | ||
| const max = expanded ? INLINE_PREVIEW_EXPANDED_MAX_HEIGHT : INLINE_PREVIEW_MAX_HEIGHT; | ||
| return ( | ||
| <div ref={setCard} className="acpmux-render-card cv-inline-preview" data-kind={kind}> | ||
| <div className="acpmux-render-card-head"> | ||
| <span className="acpmux-render-card-title">{languageLabel(lang, t)}</span> | ||
| {height > INLINE_PREVIEW_MAX_HEIGHT && ( | ||
| <button type="button" className="acpmux-review-changes" aria-expanded={expanded} onClick={onExpand}> | ||
| {expanded ? t("render.collapse") : t("render.expand")} | ||
| </button> | ||
| )} | ||
| <span className="cv-codeblock__actions">{head}</span> | ||
| </div> | ||
| {near && <PreviewFrame kind={kind} code={code} max={max} onHeight={setHeight} onLeave={onLeave} />} | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| /// The document in srcdoc. The height listener takes only this frame's own messages. A second load | ||
| /// means the frame navigated away from its document (past the frame script's guards, | ||
| /// previewDocument.ts): whatever it loaded runs without the policy, so the frame goes and the card | ||
| /// shows the source. | ||
| function PreviewFrame({ | ||
| kind, | ||
| code, | ||
| max, | ||
| onHeight, | ||
| onLeave, | ||
| }: { | ||
| kind: "html" | "svg"; | ||
| code: string; | ||
| max: number; | ||
| onHeight(height: number): void; | ||
| onLeave(): void; | ||
| }) { | ||
| const t = useT(); | ||
| const frame = useRef<HTMLIFrameElement>(null); | ||
| const loads = useRef(0); | ||
| const [reported, setReported] = useState(INLINE_PREVIEW_MIN_HEIGHT); | ||
| // One nonce per frame: a new document is a new frame (keyed by its text in Markdown.tsx). | ||
| const [nonce] = useState(previewNonce); | ||
| const srcDoc = useMemo(() => inlinePreviewDocument(kind, code, renderFrameCSS(), nonce), [kind, code, nonce]); | ||
| useEffect(() => { | ||
| const onMessage = (event: MessageEvent) => { | ||
| if (!frame.current?.contentWindow || event.source !== frame.current.contentWindow) return; | ||
| const height = reportedHeight(event.data, INLINE_PREVIEW_EXPANDED_MAX_HEIGHT); | ||
| if (height !== undefined) setReported(height); | ||
| }; | ||
| addEventListener("message", onMessage); | ||
| return () => removeEventListener("message", onMessage); | ||
| }, []); | ||
| useEffect(() => onHeight(reported), [onHeight, reported]); | ||
| return ( | ||
| <iframe | ||
| ref={frame} | ||
| className="acpmux-render-card-frame" | ||
| srcDoc={srcDoc} | ||
| onLoad={() => { | ||
| loads.current += 1; | ||
| if (loads.current > 1) onLeave(); | ||
| }} | ||
| title={languageLabel(kind, t)} | ||
| sandbox={INLINE_PREVIEW_SANDBOX} | ||
| referrerPolicy="no-referrer" | ||
| style={{ height: Math.min(reported, max) }} | ||
| /> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: The
artifactssurface omits the files that wire the preview into the transcript:conversation/Markdown.tsx(fence routing) andconversation/conversation.css(the.cv-inline-previewstyles). Add them so spec-check covers changes to the inline preview's integration and look.Prompt for AI agents