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.

fix(cowork): let previewed pages keep state and report why they fail

Akarshan Biswase50f2cf0daef
diff --git a/web-app/src/containers/CoworkPreviewPanel.tsx b/web-app/src/containers/CoworkPreviewPanel.tsx
index 49b01ae3e..8d11c2dab 100644
--- a/web-app/src/containers/CoworkPreviewPanel.tsx
+++ b/web-app/src/containers/CoworkPreviewPanel.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { FolderOpen, Globe, RotateCw, SquareArrowOutUpRight } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
@@ -11,10 +11,12 @@ import { CoworkSidePanel } from '@/containers/CoworkSidePanel'
import { getServiceHub, useServiceHub } from '@/hooks/useServiceHub'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { buildSrcDoc } from '@/lib/htmlSandbox'
+import { previewShimError } from '@/lib/previewShim'
import { cn } from '@/lib/utils'
import {
MAX_PREVIEW_BYTES,
basenameOf,
+ externalRefs,
isAssetKind,
previewKindFor,
resolveInRoot,
@@ -90,6 +92,7 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {
kind,
content,
unresolvedRefs: kind === 'html' ? unresolvedRefs(content) : undefined,
+ externalRefs: kind === 'html' ? externalRefs(content) : undefined,
})
} catch (e) {
if (!alive) return
@@ -170,6 +173,78 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {
)
}
+/** Reports past this many are dropped: the first ones name the cause. */
+const MAX_REPORTED_ERRORS = 5
+
+function HtmlFrame({
+ state,
+ allowNetwork,
+}: {
+ state: Extract<PreviewState, { status: 'ready' }>
+ allowNetwork: boolean
+}) {
+ const { t } = useTranslation()
+ const frame = useRef<HTMLIFrameElement>(null)
+ const [errors, setErrors] = useState<string[]>([])
+ // SVG is static markup, so it runs no scripts; HTML gets them, because an
+ // artifact that draws a chart is inert without them.
+ const scripts = state.kind === 'html'
+ const srcDoc = buildSrcDoc(state.content ?? '', allowNetwork, scripts)
+
+ // A new document starts with a clean slate; the old page's errors are not
+ // this one's.
+ useEffect(() => setErrors([]), [srcDoc])
+
+ // The shim inside the frame posts what the sandbox would otherwise swallow.
+ // Matched on the frame's own window so another preview's report is ignored.
+ useEffect(() => {
+ const onMessage = (e: MessageEvent) => {
+ if (e.source !== frame.current?.contentWindow) return
+ const message = previewShimError(e.data)
+ if (!message) return
+ setErrors((prev) =>
+ prev.includes(message) || prev.length >= MAX_REPORTED_ERRORS
+ ? prev
+ : [...prev, message]
+ )
+ }
+ window.addEventListener('message', onMessage)
+ return () => window.removeEventListener('message', onMessage)
+ }, [])
+
+ const blocked = allowNetwork ? 0 : (state.externalRefs ?? 0)
+ const notice = 'border-b bg-muted/40 px-3 py-2 text-xs text-muted-foreground'
+ return (
+ <div className="flex h-full flex-col">
+ {(state.unresolvedRefs ?? 0) > 0 && (
+ <p className={notice}>
+ {t('common:preview.unresolvedRefs', { count: state.unresolvedRefs })}
+ </p>
+ )}
+ {blocked > 0 && (
+ <p className={notice}>
+ {t('common:preview.externalRefs', { count: blocked })}
+ </p>
+ )}
+ {errors.length > 0 && (
+ <p className={cn(notice, 'text-destructive')} role="alert">
+ {t('common:preview.scriptErrors', {
+ count: errors.length,
+ message: errors[0],
+ })}
+ </p>
+ )}
+ <iframe
+ ref={frame}
+ title={state.path}
+ srcDoc={srcDoc}
+ sandbox={scripts ? 'allow-scripts' : ''}
+ className="min-h-0 w-full flex-1 border-0 bg-white"
+ />
+ </div>
+ )
+}
+
function Notice({ children }: { children: React.ReactNode }) {
return (
<div className="flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground">
@@ -204,28 +279,8 @@ function PreviewBody({
switch (state.kind) {
case 'html':
- case 'svg': {
- // SVG is static markup, so it runs no scripts; HTML gets them, because an
- // artifact that draws a chart is inert without them.
- const scripts = state.kind === 'html'
- return (
- <div className="flex h-full flex-col">
- {(state.unresolvedRefs ?? 0) > 0 && (
- <p className="border-b bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
- {t('common:preview.unresolvedRefs', {
- count: state.unresolvedRefs,
- })}
- </p>
- )}
- <iframe
- title={state.path}
- srcDoc={buildSrcDoc(state.content ?? '', allowNetwork, scripts)}
- sandbox={scripts ? 'allow-scripts' : ''}
- className="min-h-0 w-full flex-1 border-0 bg-white"
- />
- </div>
- )
- }
+ case 'svg':
+ return <HtmlFrame state={state} allowNetwork={allowNetwork} />
case 'markdown':
return (
<div className="h-full overflow-auto px-4 py-3">
diff --git a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx
index 77645638f..9be6407a7 100644
--- a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx
+++ b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
-import { render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
vi.mock('@/i18n/react-i18next-compat', () => ({
useTranslation: () => ({
@@ -104,6 +104,74 @@ describe('CoworkPreviewPanel', () => {
await screen.findByText('common:preview.unresolvedRefs#1')
})
+ // A page built on a CDN script renders nothing while network is off; the
+ // pane says why and names the toggle, and the notice goes once it is on.
+ it('says when web resources are blocked, until network is allowed', async () => {
+ respondWith('<script src="https://cdn.example/phaser.js"></script><canvas></canvas>')
+ view('game.html')
+
+ await screen.findByText('common:preview.externalRefs#1')
+ fireEvent.click(screen.getByLabelText('common:preview.allowNetwork'))
+ await waitFor(() =>
+ expect(screen.queryByText('common:preview.externalRefs#1')).toBeNull()
+ )
+ })
+
+ it('does not mention blocked resources for a self-contained page', async () => {
+ respondWith('<canvas></canvas><script>run()</script>')
+ view('game.html')
+
+ await screen.findByTitle('game.html')
+ expect(screen.queryByText(/externalRefs/)).toBeNull()
+ })
+
+ // The sandbox swallows exceptions; the shim posts them and the pane shows
+ // the first, deduplicated, so a blank page comes with a reason.
+ it('surfaces errors the page reports through the shim', async () => {
+ respondWith('<script>throw new Error("boom")</script>')
+ view('game.html')
+
+ const frame = (await screen.findByTitle('game.html')) as HTMLIFrameElement
+ expect(frame.srcdoc).toContain('jan-preview-shim')
+ const report = (message: string) =>
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ data: { source: 'jan-preview-shim', type: 'error', message },
+ source: frame.contentWindow,
+ })
+ )
+ })
+ report('boom')
+ report('boom')
+ await screen.findByRole('alert')
+ expect(screen.getByRole('alert').textContent).toBe(
+ 'common:preview.scriptErrors#1'
+ )
+ report('later')
+ await waitFor(() =>
+ expect(screen.getByRole('alert').textContent).toBe(
+ 'common:preview.scriptErrors#2'
+ )
+ )
+ })
+
+ it('ignores a report from a window that is not the previewed frame', async () => {
+ respondWith('<p>ok</p>')
+ view('page.html')
+
+ await screen.findByTitle('page.html')
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ data: { source: 'jan-preview-shim', type: 'error', message: 'x' },
+ source: window,
+ })
+ )
+ })
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+
it('renders markdown through the shared renderer', async () => {
respondWith('# Title')
view('notes.md')
diff --git a/web-app/src/lib/__tests__/coworkPreview.test.ts b/web-app/src/lib/__tests__/coworkPreview.test.ts
index 8d4faa578..93708b363 100644
--- a/web-app/src/lib/__tests__/coworkPreview.test.ts
+++ b/web-app/src/lib/__tests__/coworkPreview.test.ts
@@ -5,6 +5,7 @@ import {
basenameOf,
isAssetKind,
unresolvedRefs,
+ externalRefs,
resolveInRoot,
} from '@/lib/coworkPreview'
@@ -63,7 +64,6 @@ describe('unresolvedRefs', () => {
it('does not count anything that resolves on its own', () => {
expect(unresolvedRefs('<img src="data:image/png;base64,AAA">')).toBe(0)
expect(unresolvedRefs('<script src="https://cdn.example/x.js">')).toBe(0)
- expect(unresolvedRefs('<img src="//cdn.example/x.png">')).toBe(0)
expect(unresolvedRefs('<a href="#section">x</a>')).toBe(0)
expect(unresolvedRefs('<img src="blob:abc">')).toBe(0)
})
@@ -76,6 +76,25 @@ describe('unresolvedRefs', () => {
it('ignores empty values', () => {
expect(unresolvedRefs('<img src="">')).toBe(0)
})
+
+ // about:srcdoc has no scheme or host to inherit, so `//cdn` is as dead as
+ // `./x.png`.
+ it('counts protocol-relative refs, which have nothing to inherit from', () => {
+ expect(unresolvedRefs('<img src="//cdn.example/x.png">')).toBe(1)
+ })
+})
+
+describe('externalRefs', () => {
+ it('counts http(s) refs and nothing else', () => {
+ expect(
+ externalRefs(
+ '<script src="https://cdn.example/phaser.js"></script>' +
+ '<link href="http://x.dev/a.css"><img src="data:image/png;base64,AA">' +
+ '<img src="./local.png"><a href="#top">x</a>'
+ )
+ ).toBe(2)
+ expect(externalRefs('<canvas></canvas><script>run()</script>')).toBe(0)
+ })
})
describe('resolveInRoot', () => {
diff --git a/web-app/src/lib/__tests__/previewShim.test.ts b/web-app/src/lib/__tests__/previewShim.test.ts
new file mode 100644
index 000000000..3d5fa32a2
--- /dev/null
+++ b/web-app/src/lib/__tests__/previewShim.test.ts
@@ -0,0 +1,78 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'
+import { PREVIEW_SHIM_SCRIPT, previewShimError } from '../previewShim'
+
+describe('PREVIEW_SHIM_SCRIPT', () => {
+ const posted: unknown[] = []
+ const sessionBefore = window.sessionStorage
+
+ // One run for the file: the shim guards against a second install, and a
+ // fresh install per test would stack listeners and double every report.
+ beforeAll(() => {
+ Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ get() {
+ throw new DOMException('sandboxed', 'SecurityError')
+ },
+ })
+ // jsdom's window.parent is the window itself.
+ vi.spyOn(window, 'postMessage').mockImplementation((data: unknown) => {
+ posted.push(data)
+ })
+ new Function(PREVIEW_SHIM_SCRIPT)()
+ })
+
+ afterAll(() => {
+ vi.restoreAllMocks()
+ })
+
+ beforeEach(() => {
+ posted.length = 0
+ })
+
+ it('never contains a closing script tag', () => {
+ expect(PREVIEW_SHIM_SCRIPT).not.toMatch(/<\/script/i)
+ })
+
+ // An opaque-origin frame throws on `localStorage` access; a game that saves a
+ // high score at startup then never draws its first frame.
+ it('replaces a throwing localStorage with an in-memory store', () => {
+ window.localStorage.setItem('score', '42')
+ expect(window.localStorage.getItem('score')).toBe('42')
+ expect(window.localStorage.length).toBe(1)
+ expect(window.localStorage.key(0)).toBe('score')
+ window.localStorage.removeItem('score')
+ expect(window.localStorage.getItem('score')).toBeNull()
+ })
+
+ it('leaves a working storage alone', () => {
+ expect(window.sessionStorage).toBe(sessionBefore)
+ })
+
+ it('reports uncaught errors and failed resources to the parent', () => {
+ window.dispatchEvent(new ErrorEvent('error', { message: 'boom' }))
+ const script = document.createElement('script')
+ script.src = 'https://cdn.example/lib.js'
+ document.body.appendChild(script)
+ script.dispatchEvent(new Event('error'))
+ expect(posted).toEqual([
+ { source: 'jan-preview-shim', type: 'error', message: 'boom' },
+ {
+ source: 'jan-preview-shim',
+ type: 'error',
+ message: 'Failed to load script https://cdn.example/lib.js',
+ },
+ ])
+ })
+})
+
+describe('previewShimError', () => {
+ it('extracts the message from a shim report only', () => {
+ expect(
+ previewShimError({ source: 'jan-preview-shim', type: 'error', message: 'x' })
+ ).toBe('x')
+ expect(previewShimError({ source: 'jan-preview-inspector', type: 'pin' })).toBeNull()
+ expect(previewShimError({ source: 'jan-preview-shim', type: 'error' })).toBeNull()
+ expect(previewShimError('nope')).toBeNull()
+ expect(previewShimError(null)).toBeNull()
+ })
+})
diff --git a/web-app/src/lib/coworkPreview.ts b/web-app/src/lib/coworkPreview.ts
index d0b9d1116..f0379761e 100644
--- a/web-app/src/lib/coworkPreview.ts
+++ b/web-app/src/lib/coworkPreview.ts
@@ -1,6 +1,7 @@
// Renderer selection and load-state modelling for the Cowork preview pane
// (jan-internal #242). Kept pure and separate from the component so the state
// machine and the security checks are testable without a DOM.
+import { countUnresolvedAssetRefs } from '@/lib/htmlAssets'
/** How a given file should be shown. `file` is the fallback card. */
export type PreviewKind = 'html' | 'svg' | 'markdown' | 'image' | 'video' | 'audio' | 'text' | 'file'
@@ -25,6 +26,8 @@ export type PreviewState =
assetUrl?: string
/** Relative refs the sandbox cannot resolve — see `unresolvedRefs`. */
unresolvedRefs?: number
+ /** `http(s)` refs blocked while network is off — see `externalRefs`. */
+ externalRefs?: number
}
| { status: 'unsupported'; path: string }
| { status: 'failed'; path: string; reason: string }
@@ -93,27 +96,21 @@ export function basenameOf(path: string): string {
}
/**
- * `HtmlArtifact` renders into an opaque-origin sandbox via `srcDoc`, so there is
- * no base URL: a relative `src`/`href` cannot resolve and the asset silently
- * fails to load. Count those so the pane can say so instead of presenting a
- * visibly broken page as if it were correct.
- *
- * Absolute URLs, `data:`/`blob:`, protocol-relative URLs, anchors and inline
- * handlers are all fine and not counted.
+ * Relative `src`/`href` the opaque-origin sandbox cannot resolve (no base URL).
+ * One implementation with the chat artifact card, so the two previews agree on
+ * what is broken.
*/
-export function unresolvedRefs(html: string): number {
+export const unresolvedRefs = countUnresolvedAssetRefs
+
+/**
+ * `http(s)` `src`/`href` that the sandbox blocks while network is off: a page
+ * built on a CDN script (Phaser, Three.js) renders nothing until the user
+ * flips the toggle, so the pane tells them.
+ */
+export function externalRefs(html: string): number {
let count = 0
for (const m of html.matchAll(/\b(?:src|href)\s*=\s*("([^"]*)"|'([^']*)')/gi)) {
- const value = (m[2] ?? m[3] ?? '').trim()
- if (!value) continue
- if (
- /^[a-z][a-z0-9+.-]*:/i.test(value) || // any scheme: http:, data:, mailto:
- value.startsWith('//') || // protocol-relative
- value.startsWith('#') // in-page anchor
- ) {
- continue
- }
- count += 1
+ if (/^https?:\/\//i.test((m[2] ?? m[3] ?? '').trim())) count += 1
}
return count
}
diff --git a/web-app/src/lib/htmlSandbox.ts b/web-app/src/lib/htmlSandbox.ts
index 47cf694a2..0777e9410 100644
--- a/web-app/src/lib/htmlSandbox.ts
+++ b/web-app/src/lib/htmlSandbox.ts
@@ -1,4 +1,5 @@
import { PREVIEW_INSPECTOR_SCRIPT } from '@/lib/previewInspector'
+import { PREVIEW_SHIM_SCRIPT } from '@/lib/previewShim'
function buildCsp(allowNetwork: boolean, allowScripts: boolean): string {
if (!allowScripts) {
@@ -10,22 +11,28 @@ function buildCsp(allowNetwork: boolean, allowScripts: boolean): string {
"connect-src 'none'",
].join('; ')
}
+ // `blob:` on script/worker and `media-src` are what a self-contained game
+ // needs: a Worker built from a blob, sound effects as data URLs.
if (allowNetwork) {
return [
"default-src 'none'",
- "script-src 'unsafe-inline' https:",
+ "script-src 'unsafe-inline' blob: https:",
"style-src 'unsafe-inline' https:",
'img-src data: blob: https:',
'font-src data: https:',
+ 'media-src data: blob: https:',
+ 'worker-src blob:',
'connect-src https:',
].join('; ')
}
return [
"default-src 'none'",
- "script-src 'unsafe-inline'",
+ "script-src 'unsafe-inline' blob:",
"style-src 'unsafe-inline'",
'img-src data: blob:',
'font-src data:',
+ 'media-src data: blob:',
+ 'worker-src blob:',
"connect-src 'none'",
].join('; ')
}
@@ -49,8 +56,9 @@ export function buildSrcDoc(
// Element inspection (hover outline / click-to-pin bbox) needs a script in
// the iframe's own document, which is only possible when scripts run at all
// (allowScripts=false is the static SVG mode).
+ // The shim goes first: storage must be patched before any model script runs.
const inspector = allowScripts
- ? `<script>${PREVIEW_INSPECTOR_SCRIPT}</script>`
+ ? `<script>${PREVIEW_SHIM_SCRIPT}</script><script>${PREVIEW_INSPECTOR_SCRIPT}</script>`
: ''
// Always wrap so the CSP meta precedes all model markup — a meta CSP is only
// honored before resource-fetching content, and a later one can't loosen it.
diff --git a/web-app/src/lib/previewShim.ts b/web-app/src/lib/previewShim.ts
new file mode 100644
index 000000000..70f01c7bc
--- /dev/null
+++ b/web-app/src/lib/previewShim.ts
@@ -0,0 +1,114 @@
+/**
+ * Runtime shim injected ahead of model markup in every artifact preview.
+ *
+ * The preview runs in an opaque-origin sandbox (`allow-scripts` without
+ * `allow-same-origin`), where `localStorage`/`sessionStorage` throw a
+ * SecurityError on access. Generated pages, games above all, touch storage at
+ * startup for a high score or a settings blob and die before drawing a frame.
+ * The shim swaps in an in-memory Storage so the page runs; nothing persists,
+ * which is the right outcome for untrusted markup.
+ *
+ * It also reports what the sandbox otherwise swallows -- uncaught exceptions,
+ * unhandled rejections, resources that fail to load and CSP-blocked fetches --
+ * to the parent as `{source:'jan-preview-shim', type:'error', message}`, so the
+ * pane can say why a page is blank instead of showing white.
+ *
+ * Dependency-free and CSP-safe (inlined under `script-src 'unsafe-inline'`).
+ * Must never contain the literal `</script`.
+ */
+export const PREVIEW_SHIM_SCRIPT = `(function () {
+ 'use strict'
+ if (window.__janPreviewShim) return
+ window.__janPreviewShim = true
+
+ function memoryStorage() {
+ var data = {}
+ var store = {
+ key: function (i) {
+ var keys = Object.keys(data)
+ return i >= 0 && i < keys.length ? keys[i] : null
+ },
+ getItem: function (k) {
+ return Object.prototype.hasOwnProperty.call(data, k) ? data[k] : null
+ },
+ setItem: function (k, v) { data[String(k)] = String(v) },
+ removeItem: function (k) { delete data[String(k)] },
+ clear: function () { data = {} }
+ }
+ Object.defineProperty(store, 'length', {
+ get: function () { return Object.keys(data).length }
+ })
+ return store
+ }
+
+ function shimStorage(name) {
+ try {
+ void window[name]
+ return
+ } catch (e) {
+ /* sandboxed: fall through to the in-memory stand-in */
+ }
+ try {
+ Object.defineProperty(window, name, {
+ value: memoryStorage(),
+ configurable: true,
+ writable: true
+ })
+ } catch (e) {
+ /* not redefinable on this engine; the page keeps the throwing getter */
+ }
+ }
+ shimStorage('localStorage')
+ shimStorage('sessionStorage')
+
+ function report(message) {
+ try {
+ window.parent.postMessage(
+ {
+ source: 'jan-preview-shim',
+ type: 'error',
+ message: String(message).slice(0, 500)
+ },
+ '*'
+ )
+ } catch (e) {
+ /* parent gone */
+ }
+ }
+
+ function describeTarget(t) {
+ var tag = (t.tagName || '').toLowerCase()
+ var ref = t.src || t.href || ''
+ return 'Failed to load ' + tag + (ref ? ' ' + ref : '')
+ }
+
+ // Capture phase: a resource error fires on the element and does not bubble.
+ window.addEventListener(
+ 'error',
+ function (e) {
+ if (e.target && e.target !== window && e.target.tagName) {
+ report(describeTarget(e.target))
+ return
+ }
+ report(e.message || 'Script error')
+ },
+ true
+ )
+ window.addEventListener('unhandledrejection', function (e) {
+ var r = e.reason
+ report(r && r.message ? r.message : String(r))
+ })
+ document.addEventListener('securitypolicyviolation', function (e) {
+ report('Blocked by the preview policy: ' + (e.blockedURI || e.violatedDirective))
+ })
+})()`
+
+export const PREVIEW_SHIM_SOURCE = 'jan-preview-shim'
+
+/** The error message carried by a shim report, or null for any other message. */
+export function previewShimError(data: unknown): string | null {
+ if (!data || typeof data !== 'object') return null
+ const d = data as { source?: unknown; type?: unknown; message?: unknown }
+ if (d.source !== PREVIEW_SHIM_SOURCE || d.type !== 'error') return null
+ return typeof d.message === 'string' && d.message ? d.message : null
+}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index c445c69e3..16c860241 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -145,7 +145,11 @@
"reload": "Reload",
"allowNetwork": "Allow network",
"unresolvedRefs_one": "1 file this page links to can't load in the preview. Open it to see it in a browser.",
- "unresolvedRefs_other": "{{count}} files this page links to can't load in the preview. Open it to see it in a browser."
+ "unresolvedRefs_other": "{{count}} files this page links to can't load in the preview. Open it to see it in a browser.",
+ "externalRefs_one": "1 resource this page loads from the web is blocked. Turn on \"Allow network\" to load it.",
+ "externalRefs_other": "{{count}} resources this page loads from the web are blocked. Turn on \"Allow network\" to load them.",
+ "scriptErrors_one": "The page reported an error: {{message}}",
+ "scriptErrors_other": "The page reported {{count}} errors. First: {{message}}"
},
"changes": {
"title": "Agent changes",