Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(markdown): interactive HTML artifacts with sandboxed preview

Akarshan Biswas42acb16a67c6
diff --git a/web-app/src/components/HtmlArtifact.tsx b/web-app/src/components/HtmlArtifact.tsx
new file mode 100644
index 000000000..30906f1f0
--- /dev/null
+++ b/web-app/src/components/HtmlArtifact.tsx
@@ -0,0 +1,145 @@
+import { memo, useMemo, useState } from 'react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { CodeIcon, EyeIcon } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { CodeBlock } from '@/components/ai-elements/code-block'
+
+interface HtmlArtifactProps {
+ code: string
+ className?: string
+ /**
+ * When true the live preview cannot be opened yet (content still streaming).
+ * The toggle stays on the Code view and the Preview tab is disabled.
+ */
+ isStreaming?: boolean
+ /**
+ * Relax the iframe CSP to permit https: scripts/styles/fonts/images and
+ * outbound connections. Off by default: model-generated HTML runs with no
+ * network access so it cannot phone home or pull remote payloads.
+ */
+ allowNetwork?: boolean
+}
+
+type View = 'code' | 'preview'
+
+/**
+ * Strict CSP keeps model HTML inert on the network. The iframe already runs in
+ * an opaque origin (sandbox without allow-same-origin), so this only governs
+ * what the document itself may reach out to.
+ */
+function buildCsp(allowNetwork: boolean): string {
+ if (allowNetwork) {
+ return [
+ "default-src 'none'",
+ "script-src 'unsafe-inline' https:",
+ "style-src 'unsafe-inline' https:",
+ 'img-src data: blob: https:',
+ 'font-src data: https:',
+ 'connect-src https:',
+ ].join('; ')
+ }
+ return [
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "style-src 'unsafe-inline'",
+ 'img-src data: blob:',
+ 'font-src data:',
+ "connect-src 'none'",
+ ].join('; ')
+}
+
+function buildSrcDoc(code: string, allowNetwork: boolean): string {
+ const csp = buildCsp(allowNetwork)
+ const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`
+ if (/<head[\s>]/i.test(code)) {
+ return code.replace(/<head([^>]*)>/i, `<head$1>${meta}`)
+ }
+ if (/<html[\s>]/i.test(code)) {
+ return code.replace(/<html([^>]*)>/i, `<html$1><head>${meta}</head>`)
+ }
+ return `<!doctype html><html><head>${meta}</head><body>${code}</body></html>`
+}
+
+function HtmlArtifactComponent({
+ code,
+ className,
+ isStreaming,
+ allowNetwork = false,
+}: HtmlArtifactProps) {
+ const { t } = useTranslation()
+ const [view, setView] = useState<View>('preview')
+
+ const srcDoc = useMemo(
+ () => (view === 'preview' ? buildSrcDoc(code, allowNetwork) : ''),
+ [view, code, allowNetwork]
+ )
+
+ const previewDisabled = isStreaming ?? false
+ const activeView: View = previewDisabled ? 'code' : view
+
+ const tabClass = (active: boolean) =>
+ cn(
+ 'flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors',
+ active
+ ? 'text-foreground border-b-2 border-primary'
+ : 'text-muted-foreground hover:text-foreground border-b-2 border-transparent'
+ )
+
+ return (
+ <div
+ className={cn(
+ 'my-4 overflow-hidden rounded-xl border border-border bg-background',
+ className
+ )}
+ data-testid="html-artifact"
+ >
+ <div
+ className="flex items-center gap-1 border-b border-border px-2"
+ role="tablist"
+ >
+ <button
+ type="button"
+ role="tab"
+ aria-selected={activeView === 'code'}
+ className={tabClass(activeView === 'code')}
+ onClick={() => setView('code')}
+ >
+ <CodeIcon size={14} />
+ {t('htmlArtifact.code')}
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={activeView === 'preview'}
+ disabled={previewDisabled}
+ title={
+ previewDisabled ? t('htmlArtifact.previewStreaming') : undefined
+ }
+ className={cn(
+ tabClass(activeView === 'preview'),
+ previewDisabled && 'cursor-not-allowed opacity-50'
+ )}
+ onClick={() => setView('preview')}
+ >
+ <EyeIcon size={14} />
+ {t('htmlArtifact.preview')}
+ </button>
+ </div>
+
+ {activeView === 'preview' ? (
+ <iframe
+ title={t('htmlArtifact.preview')}
+ data-testid="html-artifact-iframe"
+ className="h-[600px] max-h-[80vh] min-h-64 w-full resize-y overflow-auto border-0 bg-white"
+ sandbox="allow-scripts"
+ referrerPolicy="no-referrer"
+ srcDoc={srcDoc}
+ />
+ ) : (
+ <CodeBlock code={code} language="html" />
+ )}
+ </div>
+ )
+}
+
+export const HtmlArtifact = memo(HtmlArtifactComponent)
diff --git a/web-app/src/components/__tests__/HtmlArtifact.test.tsx b/web-app/src/components/__tests__/HtmlArtifact.test.tsx
new file mode 100644
index 000000000..df93b8310
--- /dev/null
+++ b/web-app/src/components/__tests__/HtmlArtifact.test.tsx
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { HtmlArtifact } from '../HtmlArtifact'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (_key: string, opts?: { defaultValue?: string }) => opts?.defaultValue ?? _key,
+ }),
+}))
+
+vi.mock('@/components/ai-elements/code-block', () => ({
+ CodeBlock: ({ code, language }: { code: string; language: string }) => (
+ <pre data-testid="code-block" data-language={language}>
+ {code}
+ </pre>
+ ),
+}))
+
+const HTML = '<h1>hi</h1><script>document.title="x"</script>'
+
+describe('HtmlArtifact', () => {
+ it('defaults to the Preview view', () => {
+ render(<HtmlArtifact code={HTML} />)
+ expect(screen.getByTestId('html-artifact-iframe')).toBeInTheDocument()
+ expect(screen.queryByTestId('code-block')).not.toBeInTheDocument()
+ })
+
+ it('switches back to the Code view on demand', async () => {
+ const user = userEvent.setup()
+ render(<HtmlArtifact code={HTML} />)
+ await user.click(screen.getByRole('tab', { name: /code/i }))
+ expect(screen.getByTestId('code-block')).toBeInTheDocument()
+ expect(screen.queryByTestId('html-artifact-iframe')).not.toBeInTheDocument()
+ })
+
+ it('mounts a sandboxed iframe with no allow-same-origin on Preview', () => {
+ render(<HtmlArtifact code={HTML} />)
+ const iframe = screen.getByTestId('html-artifact-iframe') as HTMLIFrameElement
+ expect(iframe.getAttribute('sandbox')).toBe('allow-scripts')
+ expect(iframe.getAttribute('sandbox')).not.toContain('allow-same-origin')
+ expect(iframe.getAttribute('referrerpolicy')).toBe('no-referrer')
+ })
+
+ it('injects a strict CSP that blocks network by default', async () => {
+ const user = userEvent.setup()
+ render(<HtmlArtifact code={HTML} />)
+ await user.click(screen.getByRole('tab', { name: /preview/i }))
+
+ const iframe = screen.getByTestId('html-artifact-iframe') as HTMLIFrameElement
+ const doc = iframe.getAttribute('srcdoc') ?? ''
+ expect(doc).toContain('Content-Security-Policy')
+ expect(doc).toContain("connect-src 'none'")
+ expect(doc).toContain("default-src 'none'")
+ expect(doc).toContain(HTML)
+ })
+
+ it('relaxes CSP for network when allowNetwork is set', async () => {
+ const user = userEvent.setup()
+ render(<HtmlArtifact code={HTML} allowNetwork />)
+ await user.click(screen.getByRole('tab', { name: /preview/i }))
+
+ const iframe = screen.getByTestId('html-artifact-iframe') as HTMLIFrameElement
+ const doc = iframe.getAttribute('srcdoc') ?? ''
+ expect(doc).toContain('connect-src https:')
+ expect(doc).not.toContain("connect-src 'none'")
+ })
+
+ it('disables Preview and stays on Code while streaming', async () => {
+ const user = userEvent.setup()
+ render(<HtmlArtifact code={HTML} isStreaming />)
+
+ const previewTab = screen.getByRole('tab', { name: /preview/i })
+ expect(previewTab).toBeDisabled()
+
+ await user.click(previewTab)
+ expect(screen.queryByTestId('html-artifact-iframe')).not.toBeInTheDocument()
+ expect(screen.getByTestId('code-block')).toBeInTheDocument()
+ })
+
+ it('preserves an existing <head> when injecting CSP', async () => {
+ const user = userEvent.setup()
+ const fullDoc = '<html><head><title>t</title></head><body>x</body></html>'
+ render(<HtmlArtifact code={fullDoc} />)
+ await user.click(screen.getByRole('tab', { name: /preview/i }))
+
+ const iframe = screen.getByTestId('html-artifact-iframe') as HTMLIFrameElement
+ const doc = iframe.getAttribute('srcdoc') ?? ''
+ expect(doc).toContain('<title>t</title>')
+ expect((doc.match(/<head/gi) ?? []).length).toBe(1)
+ })
+})
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx
index 4da24ec5c..2e1b2317e 100644
--- a/web-app/src/containers/RenderMarkdown.tsx
+++ b/web-app/src/containers/RenderMarkdown.tsx
@@ -1,7 +1,13 @@
import { Components } from 'react-markdown'
import { memo, useMemo } from 'react'
-import { cn, disableIndentedCodeBlockPlugin } from '@/lib/utils'
+import {
+ cn,
+ disableIndentedCodeBlockPlugin,
+ splitHtmlArtifacts,
+} from '@/lib/utils'
+import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
+import { HtmlArtifact } from '@/components/HtmlArtifact'
// import 'katex/dist/katex.min.css'
import { defaultRehypePlugins, Streamdown } from 'streamdown'
import { cjk } from '@streamdown/cjk'
@@ -95,6 +101,9 @@ function RenderMarkdownComponent({
isAnimating,
isStreaming,
}: MarkdownProps) {
+ const renderHtmlArtifacts = useInterfaceSettings(
+ (s) => s.renderHtmlArtifacts
+ )
// normalizeLatex is O(n) over the full string and its cache misses every chunk;
// skip it while streaming (LaTeX can't render mid-token) to avoid O(n²) cost.
@@ -120,7 +129,16 @@ function RenderMarkdownComponent({
return { a: Anchor, table: MarkdownTable, ...(components ?? {}) } as Components
}, [components])
- // Render the markdown content
+ // Interactive HTML artifacts: only when the user opted in and the stream is
+ // complete (an incomplete fence must not be torn out mid-token). Splitting the
+ // string keeps Streamdown's code/mermaid/inline handling intact for everything
+ // else — overriding its `code` component would replace all of it.
+ const segments = useMemo(() => {
+ if (isStreaming || !renderHtmlArtifacts) return null
+ const segs = splitHtmlArtifacts(normalizedContent)
+ return segs.some((s) => s.type === 'html') ? segs : null
+ }, [normalizedContent, isStreaming, renderHtmlArtifacts])
+
return (
<div
dir="auto"
@@ -130,49 +148,93 @@ function RenderMarkdownComponent({
className
)}
>
- <Streamdown
- mode={isStreaming ? 'streaming' : 'static'}
- parseIncompleteMarkdown={isStreaming ?? false}
- animate={isStreaming ? false : (isAnimating ?? true)}
- animationDuration={500}
- linkSafety={{
- enabled: false,
- }}
- className={cn(
- 'size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
- className
+ {segments
+ ? segments.map((seg, i) =>
+ seg.type === 'html' ? (
+ <HtmlArtifact key={i} code={seg.content} />
+ ) : (
+ <StreamdownView
+ key={i}
+ content={seg.content}
+ isStreaming={isStreaming}
+ isAnimating={isAnimating}
+ messageId={messageId}
+ className={className}
+ components={mergedComponents}
+ />
+ )
+ )
+ : (
+ <StreamdownView
+ content={normalizedContent}
+ isStreaming={isStreaming}
+ isAnimating={isAnimating}
+ messageId={messageId}
+ className={className}
+ components={mergedComponents}
+ />
)}
- remarkPlugins={[remarkGfm, remarkMath, disableIndentedCodeBlockPlugin]}
- rehypePlugins={[
- rehypeKatex,
- defaultRehypePlugins.harden,
- ]}
- components={mergedComponents}
- plugins={{
- code: code,
- mermaid: mermaid,
- cjk: cjk,
- }}
- controls={{
- mermaid: {
- fullscreen: false,
- },
- }}
- mermaid={
- messageId
- ? {
- errorComponent: (props) => (
- <MermaidError messageId={messageId} {...props} />
- ),
- }
- : {}
- }
- >
- {normalizedContent}
- </Streamdown>
</div>
)
}
+
+interface StreamdownViewProps {
+ content: string
+ components: Components
+ className?: string
+ isStreaming?: boolean
+ isAnimating?: boolean
+ messageId?: string
+}
+
+function StreamdownView({
+ content,
+ components,
+ className,
+ isStreaming,
+ isAnimating,
+ messageId,
+}: StreamdownViewProps) {
+ return (
+ <Streamdown
+ mode={isStreaming ? 'streaming' : 'static'}
+ parseIncompleteMarkdown={isStreaming ?? false}
+ animate={isStreaming ? false : (isAnimating ?? true)}
+ animationDuration={500}
+ linkSafety={{
+ enabled: false,
+ }}
+ className={cn(
+ 'size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
+ className
+ )}
+ remarkPlugins={[remarkGfm, remarkMath, disableIndentedCodeBlockPlugin]}
+ rehypePlugins={[rehypeKatex, defaultRehypePlugins.harden]}
+ components={components}
+ plugins={{
+ code: code,
+ mermaid: mermaid,
+ cjk: cjk,
+ }}
+ controls={{
+ mermaid: {
+ fullscreen: false,
+ },
+ }}
+ mermaid={
+ messageId
+ ? {
+ errorComponent: (props) => (
+ <MermaidError messageId={messageId} {...props} />
+ ),
+ }
+ : {}
+ }
+ >
+ {content}
+ </Streamdown>
+ )
+}
export const RenderMarkdown = memo(
RenderMarkdownComponent,
(prevProps, nextProps) =>
diff --git a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
index d205d80bd..850cbd955 100644
--- a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
+++ b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
@@ -1,6 +1,7 @@
-import { render } from '@testing-library/react'
-import { describe, it, expect, vi } from 'vitest'
+import { render, waitFor, act, cleanup } from '@testing-library/react'
+import { describe, it, expect, vi, afterEach } from 'vitest'
import { RenderMarkdown } from '../RenderMarkdown'
+import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
vi.mock('@i18n/react-i18next-compat', () => ({
useTranslation: () => ({
@@ -366,5 +367,62 @@ describe('RenderMarkdown', () => {
expect(katexContainer).toBeNull()
})
})
+
+ describe('interactive HTML artifacts', () => {
+ const HTML_MSG = 'Here:\n\n```html\n<h1>hi</h1>\n```\n'
+
+ // CodeBlock highlights via async Shiki; await the resulting <pre> so the
+ // post-render state update settles inside the test rather than leaking.
+ const flush = (container: HTMLElement) =>
+ waitFor(() => expect(container.querySelector('pre')).toBeTruthy())
+
+ afterEach(() => {
+ // Unmount before resetting so the store update doesn't re-render a live,
+ // subscribed RenderMarkdown outside act.
+ cleanup()
+ act(() => {
+ useInterfaceSettings.getState().setRenderHtmlArtifacts(false)
+ })
+ })
+
+ it('renders the Streamdown code block (not an artifact) when the setting is off', async () => {
+ const { container } = render(<RenderMarkdown content={HTML_MSG} />)
+ expect(container.querySelector('[data-testid="html-artifact"]')).toBeNull()
+ expect(
+ container.querySelector('[data-streamdown="code-block"]')
+ ).toBeTruthy()
+ await flush(container)
+ })
+
+ it('renders an HtmlArtifact when the setting is on and not streaming', async () => {
+ useInterfaceSettings.getState().setRenderHtmlArtifacts(true)
+ const { container } = render(<RenderMarkdown content={HTML_MSG} />)
+ expect(
+ container.querySelector('[data-testid="html-artifact"]')
+ ).toBeTruthy()
+ // Defaults to the Preview iframe (no async Shiki highlight to flush).
+ expect(
+ container.querySelector('[data-testid="html-artifact-iframe"]')
+ ).toBeTruthy()
+ })
+
+ it('falls through to the code block while streaming even when the setting is on', async () => {
+ useInterfaceSettings.getState().setRenderHtmlArtifacts(true)
+ const { container } = render(
+ <RenderMarkdown content={HTML_MSG} isStreaming />
+ )
+ expect(container.querySelector('[data-testid="html-artifact"]')).toBeNull()
+ await flush(container)
+ })
+
+ it('does not create an artifact for non-html code when the setting is on', async () => {
+ useInterfaceSettings.getState().setRenderHtmlArtifacts(true)
+ const { container } = render(
+ <RenderMarkdown content={'```js\nconst x = 1\n```'} />
+ )
+ expect(container.querySelector('[data-testid="html-artifact"]')).toBeNull()
+ await flush(container)
+ })
+ })
})
diff --git a/web-app/src/hooks/useInterfaceSettings.ts b/web-app/src/hooks/useInterfaceSettings.ts
index f32ef4ce0..7b0da6eaf 100644
--- a/web-app/src/hooks/useInterfaceSettings.ts
+++ b/web-app/src/hooks/useInterfaceSettings.ts
@@ -110,11 +110,13 @@ interface InterfaceSettingsState {
notificationPosition: NotificationPosition
showTokenSpeed: boolean
coloredUserBubble: boolean
+ renderHtmlArtifacts: boolean
setFontSize: (size: FontSize) => void
setAccentColor: (color: AccentColorValue) => void
setNotificationPosition: (position: NotificationPosition) => void
setShowTokenSpeed: (show: boolean) => void
setColoredUserBubble: (colored: boolean) => void
+ setRenderHtmlArtifacts: (render: boolean) => void
resetInterface: () => void
}
@@ -126,6 +128,7 @@ type InterfaceSettingsPersistedSlice = Omit<
| 'setNotificationPosition'
| 'setShowTokenSpeed'
| 'setColoredUserBubble'
+ | 'setRenderHtmlArtifacts'
>
export const fontSizeOptions = [
@@ -145,6 +148,7 @@ const createDefaultInterfaceValues = (): InterfaceSettingsPersistedSlice => {
notificationPosition: getDefaultNotificationPosition(),
showTokenSpeed: true,
coloredUserBubble: true,
+ renderHtmlArtifacts: false,
}
}
@@ -182,6 +186,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
notificationPosition: getDefaultNotificationPosition(),
showTokenSpeed: true,
coloredUserBubble: true,
+ renderHtmlArtifacts: false,
})
},
@@ -213,6 +218,10 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
setColoredUserBubble: (colored) => {
set({ coloredUserBubble: colored })
},
+
+ setRenderHtmlArtifacts: (render) => {
+ set({ renderHtmlArtifacts: render })
+ },
}
},
{
@@ -224,6 +233,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
notificationPosition: state.notificationPosition,
showTokenSpeed: state.showTokenSpeed,
coloredUserBubble: state.coloredUserBubble,
+ renderHtmlArtifacts: state.renderHtmlArtifacts,
}),
// Apply settings when hydrating from storage
onRehydrateStorage: () => (state) => {
@@ -260,6 +270,10 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
if (typeof state.coloredUserBubble !== 'boolean') {
state.coloredUserBubble = true
}
+
+ if (typeof state.renderHtmlArtifacts !== 'boolean') {
+ state.renderHtmlArtifacts = false
+ }
}
// Return the state to be used for hydration
diff --git a/web-app/src/lib/__tests__/utils.test.ts b/web-app/src/lib/__tests__/utils.test.ts
index 8c9aaebdd..2b4523e4c 100644
--- a/web-app/src/lib/__tests__/utils.test.ts
+++ b/web-app/src/lib/__tests__/utils.test.ts
@@ -8,6 +8,7 @@ import {
formatMegaBytes,
formatDuration,
getModelDisplayName,
+ splitHtmlArtifacts,
} from '../utils'
describe('getProviderLogo', () => {
@@ -327,3 +328,58 @@ describe('getModelDisplayName', () => {
expect(getModelDisplayName(model)).toBe('Model (Version 2.0) - Fine-tuned')
})
})
+
+describe('splitHtmlArtifacts', () => {
+ it('returns a single markdown segment when there is no html block', () => {
+ const segs = splitHtmlArtifacts('hello **world**')
+ expect(segs).toEqual([{ type: 'markdown', content: 'hello **world**' }])
+ })
+
+ it('extracts a standalone html block with surrounding prose', () => {
+ const content = 'before\n\n```html\n<h1>hi</h1>\n```\n\nafter'
+ const segs = splitHtmlArtifacts(content)
+ expect(segs.map((s) => s.type)).toEqual(['markdown', 'html', 'markdown'])
+ expect(segs[1].content).toBe('<h1>hi</h1>')
+ expect(segs[0].content).toContain('before')
+ expect(segs[2].content).toContain('after')
+ })
+
+ it('handles an html block as the entire content (no trailing newline)', () => {
+ const segs = splitHtmlArtifacts('```html\n<p>x</p>\n```')
+ expect(segs).toEqual([{ type: 'html', content: '<p>x</p>' }])
+ })
+
+ it('extracts multiple html blocks', () => {
+ const content = '```html\n<a>1</a>\n```\nmid\n```html\n<b>2</b>\n```'
+ const segs = splitHtmlArtifacts(content)
+ expect(segs.map((s) => s.type)).toEqual([
+ 'html',
+ 'markdown',
+ 'html',
+ ])
+ expect(segs[0].content).toBe('<a>1</a>')
+ expect(segs[2].content).toBe('<b>2</b>')
+ })
+
+ it('is case-insensitive on the language tag', () => {
+ const segs = splitHtmlArtifacts('```HTML\n<i>y</i>\n```')
+ expect(segs).toEqual([{ type: 'html', content: '<i>y</i>' }])
+ })
+
+ it('does not match languages that merely start with html', () => {
+ const content = '```html5\n<x/>\n```'
+ const segs = splitHtmlArtifacts(content)
+ expect(segs.map((s) => s.type)).toEqual(['markdown'])
+ })
+
+ it('does not match non-html code fences', () => {
+ const content = '```js\nconst x = 1\n```'
+ const segs = splitHtmlArtifacts(content)
+ expect(segs).toEqual([{ type: 'markdown', content }])
+ })
+
+ it('matches a fence with more than three backticks via the closing backref', () => {
+ const segs = splitHtmlArtifacts('````html\n<p>z</p>\n````')
+ expect(segs).toEqual([{ type: 'html', content: '<p>z</p>' }])
+ })
+})
diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.ts
index 0e85e8070..79224bc62 100644
--- a/web-app/src/lib/utils.ts
+++ b/web-app/src/lib/utils.ts
@@ -57,6 +57,38 @@ export function disableIndentedCodeBlockPlugin() {
}
}
+export interface MarkdownSegment {
+ type: 'markdown' | 'html'
+ content: string
+}
+
+// Top-level fenced ```html block: opening fence (3+ backticks) + html lang,
+// body, matching closing fence on its own line. The \b stops langs like
+// "html5"/"htmlbar" from matching.
+const HTML_FENCE_RE = /(^|\n)(`{3,})[ \t]*html\b[^\n]*\n([\s\S]*?)\n\2[ \t]*(?=\n|$)/gi
+
+/**
+ * Split markdown into alternating prose and standalone HTML-artifact segments.
+ * Used to render interactive HTML previews without replacing Streamdown's code
+ * component (which would lose inline-code, mermaid, and Shiki handling).
+ */
+export function splitHtmlArtifacts(content: string): MarkdownSegment[] {
+ const segments: MarkdownSegment[] = []
+ let lastIndex = 0
+ let match: RegExpExecArray | null
+ HTML_FENCE_RE.lastIndex = 0
+ while ((match = HTML_FENCE_RE.exec(content)) !== null) {
+ const blockStart = match.index + match[1].length
+ const before = content.slice(lastIndex, blockStart)
+ if (before.length) segments.push({ type: 'markdown', content: before })
+ segments.push({ type: 'html', content: match[3] })
+ lastIndex = HTML_FENCE_RE.lastIndex
+ }
+ const rest = content.slice(lastIndex)
+ if (rest.length) segments.push({ type: 'markdown', content: rest })
+ return segments
+}
+
/**
* Get the display name for a model, falling back to the model ID if no display name is set
*/
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 17638ac52..378b8bdbe 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -1,4 +1,9 @@
{
+ "htmlArtifact": {
+ "code": "Code",
+ "preview": "Preview",
+ "previewStreaming": "Available when generation finishes"
+ },
"assistants": "Assistants",
"hardware": "Hardware",
"mcp-servers": "MCP Servers",
diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.json
index 4fde2def6..c7838bb41 100644
--- a/web-app/src/locales/en/settings.json
+++ b/web-app/src/locales/en/settings.json
@@ -98,6 +98,8 @@
"showTokenSpeedDesc": "Display tokens/sec and token count inline below assistant messages. When off, a compact icon shows the details on click.",
"coloredUserBubble": "Colored user message bubble",
"coloredUserBubbleDesc": "Use the accent color as the background of your messages. When off, they match assistant messages with plain text on a neutral background.",
+ "renderHtmlArtifacts": "Render interactive HTML",
+ "renderHtmlArtifactsDesc": "Add a Preview tab to HTML code blocks that runs the model-generated page in a sandboxed frame. The page executes its own scripts but cannot access Jan, your files, or the network. Off by default.",
"windowBackground": "Window Background",
"windowBackgroundDesc": "Set the app window's background color.",
"appMainView": "App Main View",
diff --git a/web-app/src/routes/settings/interface.tsx b/web-app/src/routes/settings/interface.tsx
index 330abdc23..5a26c9dcc 100644
--- a/web-app/src/routes/settings/interface.tsx
+++ b/web-app/src/routes/settings/interface.tsx
@@ -26,6 +26,8 @@ function InterfaceSettings() {
setShowTokenSpeed,
coloredUserBubble,
setColoredUserBubble,
+ renderHtmlArtifacts,
+ setRenderHtmlArtifacts,
} = useInterfaceSettings()
return (
@@ -82,6 +84,16 @@ function InterfaceSettings() {
/>
}
/>
+ <CardItem
+ title={t('settings:interface.renderHtmlArtifacts')}
+ description={t('settings:interface.renderHtmlArtifactsDesc')}
+ actions={
+ <Switch
+ checked={renderHtmlArtifacts}
+ onCheckedChange={setRenderHtmlArtifacts}
+ />
+ }
+ />
<CardItem
title={t('settings:interface.resetToDefault')}
description={t('settings:interface.resetToDefaultDesc')}