Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(canvas): run artifacts in a sandboxed frame behind a flag (#9615)

Eric Hayesaced2a2866d5
diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.md
index e444cc8c7e..fb2a1f4fb6 100644
--- a/apps/web/src/features/block-canvas/README.md
+++ b/apps/web/src/features/block-canvas/README.md
@@ -56,6 +56,27 @@ text, connectors, media, and document cards. Selection/camera/tools stay local.
Incoming scene changes cancel active canvas gestures; intent rebasing is deferred. See [Graphics and Canvas parity](../../../../../docs/design/graphics-parity.md)
for the remaining editor and collaboration work.
+## Artifacts
+
+Behind `enable-canvas-artifacts`, an `artifact` node runs a self-contained HTML
+document in `views/artifact-frame.tsx`. The frame's sandbox is `allow-scripts`
+only, so the document has an opaque origin with no access to Macro's cookies,
+storage or DOM. Never add `allow-same-origin`. `core/artifact-document.ts` writes
+a content security policy ahead of the artifact's own markup, which blocks network
+requests, nested frames and form posts. Images and fonts must be inline.
+
+A policy cannot follow a navigation, and a sandbox does not stop a frame navigating
+itself. Each composed document therefore announces its load to the host with a token, from
+a script that removes itself before artifact code runs. A load without the token puts
+the artifact's own document back, and an artifact that keeps leaving is stopped, but the first request of each navigation has already been
+sent. Browsers also do not apply the policy to WebRTC.
+So an artifact cannot reach Macro's data, but it can send out what it already holds:
+treat artifact source, and anything typed into an
+artifact, as readable by whoever wrote it. Artifacts mount only while on screen, so
+off-screen scripts stop and restart with fresh state. With the flag off, a node
+shows its title and no script runs. The headless render bundle has no flag reader,
+so its caller says whether to run artifacts, in the same sandbox.
+
## Controls
The floating top toolbar uses the shared `Toolbar` and Phosphor icons for drawing
diff --git a/apps/web/src/features/block-canvas/browser-test/artifact-sandbox.browser.e2e.ts b/apps/web/src/features/block-canvas/browser-test/artifact-sandbox.browser.e2e.ts
new file mode 100644
index 0000000000..35e396a509
--- /dev/null
+++ b/apps/web/src/features/block-canvas/browser-test/artifact-sandbox.browser.e2e.ts
@@ -0,0 +1,147 @@
+import { createScene, translation } from '@macro-inc/graphics';
+import { expect, type Frame, type Page, test } from '@playwright/test';
+
+// A fresh page loads the render bundle unbundled from the dev server.
+test.setTimeout(180_000);
+
+const artifactScene = (html: string) =>
+ createScene([
+ {
+ id: 'artifact',
+ type: 'artifact',
+ placement: { parentId: 'scene-root', sortKey: 'a0' },
+ transform: translation(0, 0),
+ appearance: { fill: '#fff', stroke: '#000' },
+ geometry: {
+ width: 640,
+ height: 360,
+ title: 'Sandbox test',
+ html,
+ designWidth: 1280,
+ designHeight: 720,
+ presentOrder: 'a0',
+ },
+ },
+ ]);
+
+async function renderArtifact(page: Page, html: string): Promise<Frame> {
+ await page.goto('/canvas-render.html');
+ await page.waitForFunction(() => window.canvasRenderIdle === true, null, {
+ timeout: 150_000,
+ });
+ await page.evaluate(
+ (document) =>
+ window.renderCanvasSnapshot({
+ document,
+ crop: { x: 0, y: 0, width: 640, height: 360 },
+ scale: 1,
+ revision: 'test',
+ artifacts: true,
+ }),
+ artifactScene(html)
+ );
+
+ const element = await page.waitForSelector(
+ 'iframe[data-canvas-artifact-frame]'
+ );
+ const frame = await element.contentFrame();
+ if (!frame) throw new Error('Artifact frame has no document.');
+ return frame;
+}
+
+test('runs scripts with no access to the app', async ({ page }) => {
+ await page.context().addCookies([
+ {
+ name: 'session',
+ value: 'app-secret',
+ url: new URL('/', test.info().project.use.baseURL).href,
+ },
+ ]);
+ const frame = await renderArtifact(
+ page,
+ '<p id="out">waiting</p><script>document.getElementById("out").textContent = "ran";</script>'
+ );
+
+ await expect(frame.locator('#out')).toHaveText('ran');
+ const access = await frame.evaluate(() => {
+ const attempt = (read: () => unknown) => {
+ try {
+ return { value: read() };
+ } catch (error) {
+ return { blocked: (error as Error).name };
+ }
+ };
+ return {
+ origin: window.origin,
+ cookie: attempt(() => document.cookie),
+ storage: attempt(() => localStorage.length),
+ parent: attempt(() => window.parent.document.title),
+ };
+ });
+
+ expect(access.origin).toBe('null');
+ expect(access.cookie).toHaveProperty('blocked');
+ expect(access.storage).toHaveProperty('blocked');
+ expect(access.parent).toHaveProperty('blocked');
+});
+
+test('blocks network requests', async ({ page }) => {
+ // Only a request that reaches the network layer is routed.
+ const sent: string[] = [];
+ await page.route('https://example.com/**', (route) => {
+ sent.push(route.request().url());
+ return route.fulfill({ status: 200, body: '' });
+ });
+ const frame = await renderArtifact(page, '<p>Hi</p>');
+
+ const result = await frame.evaluate(() =>
+ Promise.allSettled([
+ fetch('https://example.com/fetch'),
+ new Promise((resolve, reject) => {
+ const image = new Image();
+ image.onload = resolve;
+ image.onerror = reject;
+ image.src = 'https://example.com/image.png';
+ }),
+ ]).then((results) => results.map(({ status }) => status))
+ );
+
+ expect(result).toEqual(['rejected', 'rejected']);
+ expect(sent).toEqual([]);
+});
+
+test('returns a frame that navigates away to its own document', async ({
+ page,
+}) => {
+ await page.route('https://example.com/**', (route) =>
+ route.fulfill({ contentType: 'text/html', body: '<p>Remote page</p>' })
+ );
+ const frame = await renderArtifact(page, '<p id="own">Own page</p>');
+
+ await frame
+ .evaluate(() => {
+ window.location.href = 'https://example.com/leave';
+ })
+ .catch(() => {});
+
+ const replaced = page
+ .locator('iframe[data-canvas-artifact-frame]')
+ .contentFrame();
+ await expect(replaced.locator('#own')).toHaveText('Own page');
+ await expect(replaced.getByText('Remote page')).toHaveCount(0);
+});
+
+test('stops an artifact that keeps navigating away', async ({ page }) => {
+ await page.route('https://example.com/**', (route) =>
+ route.fulfill({ contentType: 'text/html', body: '<p>Remote page</p>' })
+ );
+ await renderArtifact(
+ page,
+ '<script>window.location.href = "https://example.com/leave";</script>'
+ );
+
+ await expect(page.getByText('tried to leave its page')).toBeVisible();
+ await expect(page.locator('iframe[data-canvas-artifact-frame]')).toHaveCount(
+ 0
+ );
+});
diff --git a/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts b/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts
new file mode 100644
index 0000000000..2dcdeadda7
--- /dev/null
+++ b/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts
@@ -0,0 +1,47 @@
+import { expect, type Page, test } from '@playwright/test';
+
+const frameFor = (page: Page, id: string) =>
+ page
+ .locator(`[data-canvas-artifact="${id}"]`)
+ .locator('iframe[data-canvas-artifact-frame]');
+
+test('runs an artifact, passes input only while interacting', async ({
+ page,
+}) => {
+ await page.goto('/artifact.html?edit');
+ const node = page.locator('[data-canvas-artifact="First"]');
+ const frame = frameFor(page, 'First');
+ await expect(frame).toBeVisible();
+ await expect(frame).toHaveCSS('pointer-events', 'none');
+
+ await node.hover();
+ await node.getByRole('button', { name: 'Interact' }).click();
+ await expect(frame).toHaveCSS('pointer-events', 'auto');
+
+ const target = frame.contentFrame().locator('#target');
+ // The frame draws at half its design size. Playwright's element coordinates
+ // ignore that scale, so click where the button appears on screen. Input can
+ // reach the canvas until the frame's new hit-test region has been painted.
+ await expect(async () => {
+ await page.mouse.click(110, 108);
+ await expect(target).toHaveText('clicked', { timeout: 500 });
+ }).toPass();
+
+ await node.getByRole('button', { name: 'Done' }).click();
+ await expect(frame).toHaveCSS('pointer-events', 'none');
+});
+
+test('edits an artifact from the inspector', async ({ page }) => {
+ await page.goto('/artifact.html?edit');
+ await frameFor(page, 'First').waitFor();
+ await page.mouse.click(200, 150);
+
+ const html = page.getByLabel('Artifact HTML');
+ await expect(html).toBeVisible();
+ await html.fill('<p id="edited">Edited</p>');
+ await html.blur();
+
+ await expect(
+ frameFor(page, 'First').contentFrame().locator('#edited')
+ ).toHaveText('Edited');
+});
diff --git a/apps/web/src/features/block-canvas/browser-test/artifact.fixture.tsx b/apps/web/src/features/block-canvas/browser-test/artifact.fixture.tsx
new file mode 100644
index 0000000000..15e069a36c
--- /dev/null
+++ b/apps/web/src/features/block-canvas/browser-test/artifact.fixture.tsx
@@ -0,0 +1,63 @@
+import '../../../index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { UserContextProvider } from '@core/context/user';
+import { createScene, type ShapeItem, translation } from '@macro-inc/graphics';
+import { queryClient } from '@queries/client';
+import { QueryClientProvider } from '@tanstack/solid-query';
+import { DragDropProvider } from '@thisbeyond/solid-dnd';
+import { render } from 'solid-js/web';
+import { CanvasNextEditor } from '../canvas-next';
+
+const artifact = (
+ id: string,
+ x: number,
+ presentOrder: string
+): ShapeItem<'artifact'> => ({
+ id,
+ type: 'artifact',
+ placement: { parentId: 'scene-root', sortKey: presentOrder },
+ transform: translation(x, 100),
+ appearance: { fill: 'transparent', stroke: 'transparent' },
+ geometry: {
+ width: 320,
+ height: 180,
+ title: id,
+ html: `<button id="target" onclick="this.textContent='clicked'">${id}</button>`,
+ designWidth: 640,
+ designHeight: 360,
+ presentOrder,
+ },
+});
+const initial = {
+ version: 2,
+ document: createScene([
+ artifact('First', 100, 'a0'),
+ artifact('Second', 500, 'a1'),
+ ]),
+} as const;
+const editable = new URLSearchParams(location.search).has('edit');
+
+render(
+ () => (
+ <div style={{ width: '100vw', height: '100vh' }}>
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <QueryClientProvider client={queryClient}>
+ <UserContextProvider>
+ <DragDropProvider>
+ <CanvasNextEditor
+ documentId="canvas"
+ initial={initial}
+ canEdit={editable}
+ fitOnLoad={false}
+ />
+ </DragDropProvider>
+ </UserContextProvider>
+ </QueryClientProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ </div>
+ ),
+ document.getElementById('app')!
+);
diff --git a/apps/web/src/features/block-canvas/browser-test/artifact.html b/apps/web/src/features/block-canvas/browser-test/artifact.html
new file mode 100644
index 0000000000..ebcf510c55
--- /dev/null
+++ b/apps/web/src/features/block-canvas/browser-test/artifact.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /></head>
+ <body><div id="app"></div><script type="module" src="./artifact.fixture.tsx"></script></body>
+</html>
diff --git a/apps/web/src/features/block-canvas/browser-test/reference.fixture.tsx b/apps/web/src/features/block-canvas/browser-test/reference.fixture.tsx
index b9e166add2..82c456274d 100644
--- a/apps/web/src/features/block-canvas/browser-test/reference.fixture.tsx
+++ b/apps/web/src/features/block-canvas/browser-test/reference.fixture.tsx
@@ -1,4 +1,6 @@
import '../../../index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
import { createScene, type ShapeItem, translation } from '@macro-inc/graphics';
import { queryClient } from '@queries/client';
import { QueryClientProvider } from '@tanstack/solid-query';
@@ -36,17 +38,21 @@ const editable = new URLSearchParams(location.search).has('edit');
render(
() => (
<div style={{ width: '100vw', height: '100vh' }}>
- <QueryClientProvider client={queryClient}>
- <DragDropProvider>
- <CanvasDocument
- documentId="canvas"
- file={file}
- canEdit={editable}
- isNested={!editable}
- view={editable ? { x: 0, y: 0, scale: 100 } : undefined}
- />
- </DragDropProvider>
- </QueryClientProvider>
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <QueryClientProvider client={queryClient}>
+ <DragDropProvider>
+ <CanvasDocument
+ documentId="canvas"
+ file={file}
+ canEdit={editable}
+ isNested={!editable}
+ view={editable ? { x: 0, y: 0, scale: 100 } : undefined}
+ />
+ </DragDropProvider>
+ </QueryClientProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
</div>
),
document.getElementById('app')!
diff --git a/apps/web/src/features/block-canvas/browser-test/reference.playwright.config.ts b/apps/web/src/features/block-canvas/browser-test/reference.playwright.config.ts
index ca75569281..84fe29687c 100644
--- a/apps/web/src/features/block-canvas/browser-test/reference.playwright.config.ts
+++ b/apps/web/src/features/block-canvas/browser-test/reference.playwright.config.ts
@@ -7,7 +7,7 @@ const localURL = `http://127.0.0.1:${process.env.CANVAS_REFERENCE_PORT ?? 3029}`
export default defineConfig({
testDir: directory,
- testMatch: 'reference.e2e.ts',
+ testMatch: /(reference|artifact)\.e2e\.ts/,
outputDir: `${directory}/test-results`,
reporter: 'line',
use: { baseURL: localURL },
diff --git a/apps/web/src/features/block-canvas/browser-test/render.playwright.config.ts b/apps/web/src/features/block-canvas/browser-test/render.playwright.config.ts
index 220568fe92..3f8be98ea6 100644
--- a/apps/web/src/features/block-canvas/browser-test/render.playwright.config.ts
+++ b/apps/web/src/features/block-canvas/browser-test/render.playwright.config.ts
@@ -5,7 +5,7 @@ const directory = fileURLToPath(new URL('.', import.meta.url));
const external = process.env.CANVAS_RENDER_BASE_URL;
export default defineConfig({
testDir: directory,
- testMatch: 'text-layout.browser.e2e.ts',
+ testMatch: /(text-layout|artifact-sandbox)\.browser\.e2e\.ts/,
timeout: 60_000,
workers: 1,
reporter: 'line',
diff --git a/apps/web/src/features/block-canvas/components/artifact-inspector.tsx b/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
new file mode 100644
index 0000000000..c572484881
--- /dev/null
+++ b/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
@@ -0,0 +1,39 @@
+import {
+ ARTIFACT_HTML_MAX_LENGTH,
+ type ArtifactContent,
+ type ArtifactItem,
+} from '@macro-inc/graphics';
+import { InspectorField } from './inspector-field';
+import { InspectorSection } from './inspector-section';
+
+export function ArtifactInspector(props: {
+ item: ArtifactItem;
+ onChange: (content: ArtifactContent) => void;
+}) {
+ return (
+ <InspectorSection title="Artifact">
+ <InspectorField label="Title">
+ <input
+ class="w-full rounded border border-edge-muted bg-panel px-2 py-1 text-xs text-ink outline-none focus:border-edge-focus"
+ aria-label="Artifact title"
+ value={props.item.geometry.title}
+ onChange={(event) =>
+ props.onChange({ title: event.currentTarget.value })
+ }
+ />
+ </InspectorField>
+ <InspectorField label="HTML">
+ <textarea
+ class="h-48 w-full resize-y rounded border border-edge-muted bg-panel px-2 py-1 font-mono text-xs text-ink outline-none focus:border-edge-focus"
+ aria-label="Artifact HTML"
+ spellcheck={false}
+ maxLength={ARTIFACT_HTML_MAX_LENGTH}
+ value={props.item.geometry.html}
+ onChange={(event) =>
+ props.onChange({ html: event.currentTarget.value })
+ }
+ />
+ </InspectorField>
+ </InspectorSection>
+ );
+}
diff --git a/apps/web/src/features/block-canvas/components/insert-radial-menu.tsx b/apps/web/src/features/block-canvas/components/insert-radial-menu.tsx
index 1ae64dada2..6adca17b15 100644
--- a/apps/web/src/features/block-canvas/components/insert-radial-menu.tsx
+++ b/apps/web/src/features/block-canvas/components/insert-radial-menu.tsx
@@ -1,3 +1,4 @@
+import CodeIcon from '@icon/system/regular/code.svg';
import ImageIcon from '@icon/system/regular/image.svg';
import LinkIcon from '@icon/system/regular/link.svg';
import UploadIcon from '@icon/system/regular/upload-simple.svg';
@@ -15,27 +16,42 @@ export function CanvasInsertRadialMenu(props: {
onMedia: () => void;
onUpload: () => void;
onReference: () => void;
+ onArtifact?: () => void;
}) {
- const choices = [
- {
- label: 'Media',
- icon: ImageIcon,
- action: props.onMedia,
- position: 'left-1/2 top-4 -translate-x-1/2',
- },
- {
- label: 'Upload media',
- icon: UploadIcon,
- action: props.onUpload,
- position: 'right-0 top-40',
- },
- {
- label: 'Reference',
- icon: LinkIcon,
- action: props.onReference,
- position: 'left-0 top-40',
- },
- ];
+ const media = {
+ label: 'Media',
+ icon: ImageIcon,
+ action: props.onMedia,
+ position: 'left-1/2 top-4 -translate-x-1/2',
+ };
+ const upload = {
+ label: 'Upload media',
+ icon: UploadIcon,
+ action: props.onUpload,
+ };
+ const reference = {
+ label: 'Reference',
+ icon: LinkIcon,
+ action: props.onReference,
+ };
+ // Slices run clockwise from the top, so a fourth choice fills the bottom.
+ const choices = props.onArtifact
+ ? [
+ media,
+ { ...upload, position: 'right-0 top-[6.75rem]' },
+ {
+ label: 'Artifact',
+ icon: CodeIcon,
+ action: props.onArtifact,
+ position: 'left-1/2 bottom-4 -translate-x-1/2',
+ },
+ { ...reference, position: 'left-0 top-[6.75rem]' },
+ ]
+ : [
+ media,
+ { ...upload, position: 'right-0 top-40' },
+ { ...reference, position: 'left-0 top-40' },
+ ];
const [index, setIndex] = createSignal(0);
const [active, setActive] = createSignal<number | undefined>(0);
const sliceAngle = 360 / choices.length;
diff --git a/apps/web/src/features/block-canvas/core/artifact-document.test.ts b/apps/web/src/features/block-canvas/core/artifact-document.test.ts
new file mode 100644
index 0000000000..eafd66cc3a
--- /dev/null
+++ b/apps/web/src/features/block-canvas/core/artifact-document.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+import {
+ ARTIFACT_CSP,
+ composeArtifactDocument,
+ isArtifactLoadMarker,
+} from './artifact-document';
+
+const parse = (html: string) =>
+ new DOMParser().parseFromString(html, 'text/html');
+
+describe('composeArtifactDocument', () => {
+ it('parses the content security policy before anything in the artifact', () => {
+ const composed = composeArtifactDocument(
+ '<html><head><script>run()</script></head><body>Hi</body></html>',
+ {},
+ 'token'
+ );
+
+ const first = parse(composed).head.firstElementChild;
+ expect(first?.getAttribute('http-equiv')).toBe('Content-Security-Policy');
+ expect(first?.getAttribute('content')).toBe(ARTIFACT_CSP);
+ expect(composed.indexOf('Content-Security-Policy')).toBeLessThan(
+ composed.indexOf('<script>')
+ );
+ });
+
+ it('keeps the policy first for a fragment with no head', () => {
+ const composed = composeArtifactDocument(
+ '<script>run()</script>',
+ {},
+ 'token'
+ );
+
+ expect(parse(composed).head.firstElementChild?.tagName).toBe('META');
+ });
+
+ it('removes meta refresh, which would navigate out of the policy', () => {
+ const composed = composeArtifactDocument(
+ '<meta http-equiv="REFRESH" content="0;url=https://example.com"><p>Hi</p>',
+ {},
+ 'token'
+ );
+
+ expect(composed).not.toContain('example.com');
+ expect(composed).toContain('<p>Hi</p>');
+ });
+
+ it('exposes theme tokens as CSS variables', () => {
+ const composed = composeArtifactDocument(
+ '<p>Hi</p>',
+ { '--color-ink': '#111' },
+ 'token'
+ );
+
+ expect(composed).toContain(':root{--color-ink:#111}');
+ });
+
+ it('marks its own load before any artifact script can run', () => {
+ const composed = composeArtifactDocument(
+ '<script>run()</script>',
+ {},
+ 'secret'
+ );
+
+ expect(composed.indexOf('secret')).toBeLessThan(composed.indexOf('run()'));
+ expect(
+ isArtifactLoadMarker({ macroArtifactLoaded: 'secret' }, 'secret')
+ ).toBe(true);
+ expect(
+ isArtifactLoadMarker({ macroArtifactLoaded: 'guess' }, 'secret')
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/block-canvas/core/artifact-document.ts b/apps/web/src/features/block-canvas/core/artifact-document.ts
new file mode 100644
index 0000000000..e97dded3af
--- /dev/null
+++ b/apps/web/src/features/block-canvas/core/artifact-document.ts
@@ -0,0 +1,82 @@
+/**
+ * The iframe's `sandbox` gives the document an opaque origin, so it cannot reach
+ * Macro's cookies, storage or DOM. This policy keeps it off the network: scripts
+ * and styles must be inline, and images and fonts must be embedded.
+ */
+export const ARTIFACT_CSP = [
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "style-src 'unsafe-inline'",
+ 'img-src data: blob:',
+ 'font-src data:',
+ 'media-src data: blob:',
+ "base-uri 'none'",
+ "form-action 'none'",
+ "frame-src 'none'",
+].join('; ');
+
+export const ARTIFACT_SANDBOX = 'allow-scripts';
+
+const THEME_TOKENS = [
+ '--color-panel',
+ '--color-ink',
+ '--color-ink-muted',
+ '--color-accent',
+ '--color-edge-muted',
+];
+
+/** Macro's resolved theme colors, for artifacts that want to match the app. */
+export function artifactThemeTokens(element: Element): Record<string, string> {
+ const style = getComputedStyle(element);
+ return Object.fromEntries(
+ THEME_TOKENS.map((token) => [token, style.getPropertyValue(token).trim()])
+ );
+}
+
+/**
+ * Tells the host that its own document, not some page navigated to, has loaded.
+ * It runs before any artifact code and removes itself, keeping the token in a
+ * closure, so the artifact cannot hand it to another page. An artifact that
+ * navigates while parsing never reaches its own load, so it sends nothing.
+ */
+const loadMarker = (token: string) =>
+ `(function (host, token) {
+ addEventListener('load', function () {
+ host.postMessage({ macroArtifactLoaded: token }, '*');
+ });
+ })(parent, ${JSON.stringify(token)});
+ document.currentScript.remove();`;
+
+export const isArtifactLoadMarker = (data: unknown, token: string) =>
+ !!data &&
+ typeof data === 'object' &&
+ 'macroArtifactLoaded' in data &&
+ data.macroArtifactLoaded === token;
+
+/** Build the srcdoc. The parser never runs scripts, and the policy is parsed
+ * first so that nothing in the artifact can run or load before it applies. */
+export function composeArtifactDocument(
+ html: string,
+ tokens: Record<string, string>,
+ loadToken: string
+): string {
+ const parsed = new DOMParser().parseFromString(html, 'text/html');
+
+ for (const refresh of parsed.querySelectorAll('meta[http-equiv="refresh" i]'))
+ refresh.remove();
+
+ const theme = parsed.createElement('style');
+ theme.textContent = `:root{${Object.entries(tokens)
+ .map(([token, value]) => `${token}:${value}`)
+ .join(';')}}`;
+
+ const policy = parsed.createElement('meta');
+ policy.httpEquiv = 'Content-Security-Policy';
+ policy.content = ARTIFACT_CSP;
+
+ const marker = parsed.createElement('script');
+ marker.textContent = loadMarker(loadToken);
+
+ parsed.head.prepend(policy, theme, marker);
+ return `<!doctype html>${parsed.documentElement.outerHTML}`;
+}
diff --git a/apps/web/src/features/block-canvas/primitives/create-asset-state.ts b/apps/web/src/features/block-canvas/primitives/create-asset-state.ts
index d66983eac1..70121f040d 100644
--- a/apps/web/src/features/block-canvas/primitives/create-asset-state.ts
+++ b/apps/web/src/features/block-canvas/primitives/create-asset-state.ts
@@ -1,4 +1,8 @@
-import { insertShapesCommand, type Point } from '@macro-inc/graphics';
+import {
+ insertShapesCommand,
+ nextPresentOrder,
+ type Point,
+} from '@macro-inc/graphics';
import { createSignal, onCleanup } from 'solid-js';
import type {
CanvasAsset,
@@ -9,6 +13,11 @@ import type {
import { canEmbedDocument } from '../core/document-display';
import type { CanvasState } from './create-canvas-state';
+const STARTER_ARTIFACT_HTML = `<style>
+ body { margin: 0; height: 100vh; display: grid; place-items: center; font: 48px sans-serif; color: var(--color-ink); background: var(--color-panel); }
+</style>
+<h1>New artifact</h1>`;
+
export function createAssetState(
state: CanvasState,
source: CanvasAssetSource
@@ -124,6 +133,31 @@ export function createAssetState(
),
media: (asset: CanvasAsset, point: Point) =>
load([() => source.media(asset)], point),
+ artifact: (point: Point) => {
+ const width = 640;
+ const height = 360;
+ state.chooseTool('select');
+ state.editor.execute(insertShapesCommand, [
+ {
+ item: {
+ id: crypto.randomUUID(),
+ type: 'artifact',
+ appearance,
+ geometry: {
+ title: 'Untitled artifact',
+ html: STARTER_ARTIFACT_HTML,
+ width,
+ height,
+ designWidth: 1280,
+ designHeight: 720,
+ presentOrder: nextPresentOrder(state.editor.document),
+ },
+ },
+ point: { x: point.x - width / 2, y: point.y - height / 2 },
+ },
+ ]);
+ state.setNotice('Inserted artifact');
+ },
document: (
asset: CanvasAsset,
point: Point,
diff --git a/apps/web/src/features/block-canvas/primitives/create-embed-state.ts b/apps/web/src/features/block-canvas/primitives/create-embed-state.ts
index 7774bf1641..e365613274 100644
--- a/apps/web/src/features/block-canvas/primitives/create-embed-state.ts
+++ b/apps/web/src/features/block-canvas/primitives/create-embed-state.ts
@@ -8,25 +8,24 @@ export function createEmbedState(
prepare: () => void
) {
const [activeId, setActiveId] = createSignal<string>();
- const active = () => {
- const id = activeId();
- const item = id ? document.items[id] : undefined;
- return item?.type === 'document' &&
+ const canEnter = (id: string) => {
+ const item = document.items[id];
+ if (item?.type === 'artifact') return true;
+
+ return (
+ item?.type === 'document' &&
item.geometry.display === 'embed' &&
canEmbedDocument(item.geometry.fileType)
- ? id
- : undefined;
+ );
+ };
+ const active = () => {
+ const id = activeId();
+ return id && canEnter(id) ? id : undefined;
};
return {
active,
enter(id: string) {
- const item = document.items[id];
- if (
- item?.type !== 'document' ||
- item.geometry.display !== 'embed' ||
- !canEmbedDocument(item.geometry.fileType)
- )
- return;
+ if (!canEnter(id)) return;
prepare();
editor.select(id);
setActiveId(id);
diff --git a/apps/web/src/features/block-canvas/views/artifact-frame.tsx b/apps/web/src/features/block-canvas/views/artifact-frame.tsx
new file mode 100644
index 0000000000..b8f6d8c110
--- /dev/null
+++ b/apps/web/src/features/block-canvas/views/artifact-frame.tsx
@@ -0,0 +1,158 @@
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import {
+ ARTIFACT_SANDBOX,
+ artifactThemeTokens,
+ composeArtifactDocument,
+ isArtifactLoadMarker,
+} from '../core/artifact-document';
+
+/**
+ * Runs artifact HTML in an opaque-origin frame, laid out at its design size and
+ * scaled to fit. Never add `allow-same-origin`: with `allow-scripts` the document
+ * could remove its own sandbox and act as the signed-in user.
+ */
+export function ArtifactFrame(props: {
+ html: string;
+ title: string;
+ designWidth: number;
+ designHeight: number;
+ interactive: boolean;
+ /** Mount even offscreen, for renders that must capture every artifact. */
+ eager?: boolean;
+}) {
+ let host!: HTMLDivElement;
+ const [size, setSize] = createSignal({ width: 0, height: 0 });
+ const [visible, setVisible] = createSignal(!!props.eager);
+ const [generation, setGeneration] = createSignal(0);
+ const [navigatedAway, setNavigatedAway] = createSignal(false);
+ let restarts: number[] = [];
+
+ const scale = () =>
+ Math.min(
+ size().width / props.designWidth,
+ size().height / props.designHeight
+ );
+ const loadToken = crypto.randomUUID();
+ const srcdoc = createMemo(() =>
+ composeArtifactDocument(
+ props.html,
+ artifactThemeTokens(document.documentElement),
+ loadToken
+ )
+ );
+ const mounted = createMemo(() => ({
+ content: srcdoc(),
+ generation: generation(),
+ }));
+ createEffect(
+ on(srcdoc, () => {
+ restarts = [];
+ setNavigatedAway(false);
+ })
+ );
+
+ /**
+ * The policy cannot follow a navigation to another page, so a load that was not
+ * announced with this frame's token replaces the frame with the artifact's
+ * own document. Moving a frame in the DOM, which a layer reorder does, reloads it
+ * and announces again, so it needs no restart. An artifact that keeps leaving is
+ * stopped.
+ */
+ const restart = () => {
+ const now = Date.now();
+ restarts = [...restarts.filter((at) => now - at < 10_000), now];
+ if (restarts.length > 3) setNavigatedAway(true);
+ else setGeneration((value) => value + 1);
+ };
+
+ onMount(() => {
+ const sizes = new ResizeObserver(([entry]) => {
+ if (!entry) return;
+ setSize({
+ width: entry.contentRect.width,
+ height: entry.contentRect.height,
+ });
+ });
+ sizes.observe(host);
+ onCleanup(() => sizes.disconnect());
+
+ if (props.eager) return;
+ // A canvas can hold many artifacts; only those on screen run their scripts.
+ const viewport = new IntersectionObserver(([entry]) => {
+ setVisible(!!entry?.isIntersecting);
+ });
+ viewport.observe(host);
+ onCleanup(() => viewport.disconnect());
+ });
+
+ return (
+ <div ref={host} class="relative size-full overflow-hidden">
+ <Show
+ when={!navigatedAway()}
+ fallback={
+ <div class="grid size-full place-items-center p-4 text-center text-xs text-ink-muted">
+ This artifact tried to leave its page and was stopped.
+ </div>
+ }
+ >
+ <Show when={visible() ? mounted() : undefined} keyed>
+ {(frame) => {
+ let element: HTMLIFrameElement | undefined;
+ let loads = 0;
+ let announced = 0;
+ let checkLoad: ReturnType<typeof setTimeout> | undefined;
+ const onMessage = (event: MessageEvent) => {
+ if (
+ element &&
+ event.source === element.contentWindow &&
+ isArtifactLoadMarker(event.data, loadToken)
+ )
+ announced += 1;
+ };
+ window.addEventListener('message', onMessage);
+ onCleanup(() => {
+ window.removeEventListener('message', onMessage);
+ clearTimeout(checkLoad);
+ });
+
+ return (
+ <iframe
+ title={props.title}
+ data-canvas-artifact-frame
+ sandbox={ARTIFACT_SANDBOX}
+ allow=""
+ referrerPolicy="no-referrer"
+ srcdoc={frame.content}
+ tabIndex={props.interactive ? 0 : -1}
+ ref={element}
+ onLoad={() => {
+ // The message and the load event can arrive in either order.
+ loads += 1;
+ clearTimeout(checkLoad);
+ checkLoad = setTimeout(() => {
+ if (loads > announced) restart();
+ }, 250);
+ }}
+ class="absolute left-1/2 top-1/2 border-0"
+ style={{
+ width: `${props.designWidth}px`,
+ height: `${props.designHeight}px`,
+ transform: `translate(-50%, -50%) scale(${scale()})`,
+ 'pointer-events': props.interactive ? 'auto' : 'none',
+ }}
+ />
+ );
+ }}
+ </Show>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-canvas/views/artifact-view.tsx b/apps/web/src/features/block-canvas/views/artifact-view.tsx
new file mode 100644
index 0000000000..398f4903d9
--- /dev/null
+++ b/apps/web/src/features/block-canvas/views/artifact-view.tsx
@@ -0,0 +1,65 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { enableCanvasArtifacts } from '@core/constant/featureFlags';
+import type { ShapeViewProps } from '@macro-inc/graphics/solid';
+import { Show } from 'solid-js';
+import { ArtifactFrame } from './artifact-frame';
+
+export function CanvasArtifactView(
+ props: ShapeViewProps<'artifact'> & {
+ active: boolean;
+ onEnter: () => void;
+ onExit: () => void;
+ }
+) {
+ const flag = useFeatureFlag(enableCanvasArtifacts);
+ const title = () => props.item.geometry.title || 'Artifact';
+
+ return (
+ <div
+ data-canvas-artifact={props.item.id}
+ data-canvas-embed-active={props.active ? props.item.id : undefined}
+ class="group relative size-full overflow-hidden bg-panel"
+ onDblClick={(event) => {
+ if (!flag().enabled || props.active) return;
+ event.stopPropagation();
+ props.onEnter();
+ }}
+ style={{
+ opacity: props.item.appearance.opacity ?? 1,
+ 'border-radius': `${props.item.appearance.cornerRadius ?? 0}px`,
+ border: `${props.item.appearance.strokeWidth ?? 0}px solid ${props.item.appearance.stroke}`,
+ 'box-sizing': 'border-box',
+ }}
+ >
+ <Show
+ when={flag().enabled}
+ fallback={
+ <div class="grid size-full place-items-center p-4 text-center text-sm text-ink-muted">
+ {title()}
+ </div>
+ }
+ >
+ <ArtifactFrame
+ html={props.item.geometry.html}
+ title={title()}
+ designWidth={props.item.geometry.designWidth}
+ designHeight={props.item.geometry.designHeight}
+ interactive={props.active}
+ />
+ <div class="absolute right-2 top-2 flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 touch:opacity-100">
+ <button
+ type="button"
+ class="menu-surface rounded px-2 py-1 text-xs text-accent hover:bg-hover"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (props.active) props.onExit();
+ else props.onEnter();
+ }}
+ >
+ {props.active ? 'Done' : 'Interact'}
+ </button>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
index ee0290f7db..7e2a6936c4 100644
--- a/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
+++ b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
@@ -14,6 +14,7 @@ import {
TextView,
} from '@macro-inc/graphics/solid';
import { createSignal, onCleanup, onMount, Show } from 'solid-js';
+import { CanvasArtifactView } from './artifact-view';
import { CanvasDrawingToolbar, CanvasZoomToolbar } from './canvas-toolbars';
import { CanvasMediaView } from './embedded-items';
import { CanvasTextContent } from './text-content';
@@ -25,6 +26,7 @@ export function CanvasReadOnlyView(props: {
fitOnLoad?: boolean;
}) {
const [tool, setTool] = createSignal<'select' | 'pan'>('select');
+ const [activeArtifact, setActiveArtifact] = createSignal<string>();
const [scale, setScale] = createSignal(props.editor.getCamera().scale);
const [hasSelection, setHasSelection] = createSignal(
props.editor.getSession().selectedIds.length > 0
@@ -107,6 +109,14 @@ export function CanvasReadOnlyView(props: {
}}
gridColor="transparent"
renderers={{
+ artifact: (p) => (
+ <CanvasArtifactView
+ {...p}
+ active={activeArtifact() === p.item.id}
+ onEnter={() => setActiveArtifact(p.item.id)}
+ onExit={() => setActiveArtifact(undefined)}
+ />
+ ),
connector: (p) => (
<ConnectorView {...p} contentView={CanvasTextContent} />
),
diff --git a/apps/web/src/features/block-canvas/views/canvas-view.tsx b/apps/web/src/features/block-canvas/views/canvas-view.tsx
index fa218118ab..55e13874f1 100644
--- a/apps/web/src/features/block-canvas/views/canvas-view.tsx
+++ b/apps/web/src/features/block-canvas/views/canvas-view.tsx
@@ -1,5 +1,7 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useSidePanel } from '@components/app/side-panel';
import { createImageActions } from '@core/component/ImageActions';
+import { enableCanvasArtifacts } from '@core/constant/featureFlags';
import { fireAndForget } from '@core/util/fireAndForget';
import Copy from '@icon/system/regular/copy.svg';
import DownloadSimple from '@icon/system/regular/download-simple.svg';
@@ -10,6 +12,7 @@ import {
type DocumentGeometry,
distributeCommand,
screenToWorld,
+ setArtifactCommand,
styleCommand,
} from '@macro-inc/graphics';
import { attachConnectorControls } from '@macro-inc/graphics/browser';
@@ -35,6 +38,7 @@ import {
Show,
} from 'solid-js';
import type { CanvasClipboard } from '../clipboard';
+import { ArtifactInspector } from '../components/artifact-inspector';
import { ConnectorInspector } from '../components/connector-inspector';
import type { CanvasEmbedViewProps } from '../components/embed-view';
import { EraserTrail } from '../components/eraser-trail';
@@ -57,6 +61,7 @@ import type {
import type { CanvasInsertState } from '../primitives/create-insert-state';
import { attachTextInput } from '../primitives/text-input';
import { useCanvasMediaSource } from '../queries/media';
+import { CanvasArtifactView } from './artifact-view';
import { CanvasContextMenu } from './canvas-context-menu';
import {
CanvasDrawingToolbar,
@@ -106,6 +111,11 @@ export function CanvasView(props: {
state.selection().length === 1
? state.document.items[state.selection()[0]!]
: undefined;
+ const selectedArtifact = () => {
+ const item = selectedItem();
+ return item?.type === 'artifact' ? item : undefined;
+ };
+ const artifactsFlag = useFeatureFlag(enableCanvasArtifacts);
const selectedImage = () => {
const item = selectedItem();
return item?.type === 'image' ? item : undefined;
@@ -256,6 +266,14 @@ export function CanvasView(props: {
location={location}
onClose={props.insert.close}
onRestoreFocus={focus}
+ onArtifact={
+ artifactsFlag().enabled
+ ? () => {
+ props.assets.artifact(location.world);
+ props.insert.close();
+ }
+ : undefined
+ }
onSelect={(asset, mode) => {
if (mode === 'media')
fireAndForget(
@@ -428,6 +446,19 @@ export function CanvasView(props: {
onScrub={() => state.text.scrubFontSize(state.inspector)}
/>
</Show>
+ <Show when={artifactsFlag().enabled && selectedArtifact()}>
+ {(artifact) => (
+ <ArtifactInspector
+ item={artifact()}
+ onChange={(content) =>
+ editor.execute(setArtifactCommand, {
+ id: artifact().id,
+ content,
+ })
+ }
+ />
+ )}
+ </Show>
<Show when={selectedImage()}>
<div class="flex flex-col gap-2 p-3">
<Button
@@ -620,6 +651,14 @@ export function CanvasView(props: {
onStop={props.assets.stopPlayback}
/>
),
+ artifact: (itemProps) => (
+ <CanvasArtifactView
+ {...itemProps}
+ active={state.embeds.active() === itemProps.item.id}
+ onEnter={() => state.embeds.enter(itemProps.item.id)}
+ onExit={exitEmbed}
+ />
+ ),
document: (itemProps) => (
<CanvasDocumentView
{...itemProps}
@@ -659,7 +698,9 @@ export function CanvasView(props: {
input={{
ignoreTarget: (target) =>
target instanceof Element &&
- !!target.closest('[data-canvas-document]') &&
+ !!target.closest(
+ '[data-canvas-document],[data-canvas-artifact]'
+ ) &&
!!target.closest(
'button,a,input,select,textarea,[role="button"]'
),
diff --git a/apps/web/src/features/block-canvas/views/insert-menu.tsx b/apps/web/src/features/block-canvas/views/insert-menu.tsx
index 6e52a71b12..babb6faf81 100644
--- a/apps/web/src/features/block-canvas/views/insert-menu.tsx
+++ b/apps/web/src/features/block-canvas/views/insert-menu.tsx
@@ -1,3 +1,4 @@
+import CodeIcon from '@icon/system/regular/code.svg';
import ImageIcon from '@icon/system/regular/image.svg';
import LinkIcon from '@icon/system/regular/link.svg';
import UploadIcon from '@icon/system/regular/upload-simple.svg';
@@ -14,6 +15,8 @@ export function CanvasInsertMenu(props: {
location: CanvasInsertLocation;
onSelect: (asset: CanvasAsset, mode: CanvasInsertMode) => void;
onFiles: (files: File[]) => void;
+ /** Absent while artifacts are off for this user. */
+ onArtifact?: () => void;
onClose: () => void;
onRestoreFocus: () => void;
}) {
@@ -72,6 +75,7 @@ export function CanvasInsertMenu(props: {
center={props.location.screen}
onMedia={() => setMode('media')}
onReference={() => setMode('reference')}
+ onArtifact={props.onArtifact}
onUpload={() => uploadInput?.click()}
/>
</Popover.Content>
@@ -107,6 +111,13 @@ export function CanvasInsertMenu(props: {
<Dropdown.Item onSelect={() => setMode('reference')}>
<LinkIcon class="size-4" /> Reference
</Dropdown.Item>
+ <Show when={props.onArtifact}>
+ {(onArtifact) => (
+ <Dropdown.Item onSelect={onArtifact()}>
+ <CodeIcon class="size-4" /> Artifact
+ </Dropdown.Item>
+ )}
+ </Show>
</Dropdown.Group>
</Dropdown.Content>
</Dropdown>
diff --git a/apps/web/src/features/block-canvas/views/render-entry.tsx b/apps/web/src/features/block-canvas/views/render-entry.tsx
index 657ef8c63f..4add3cbf49 100644
--- a/apps/web/src/features/block-canvas/views/render-entry.tsx
+++ b/apps/web/src/features/block-canvas/views/render-entry.tsx
@@ -21,7 +21,9 @@ import {
RectangleView,
TextView,
} from '@macro-inc/graphics/solid';
+import { Show } from 'solid-js';
import { render } from 'solid-js/web';
+import { ArtifactFrame } from './artifact-frame';
import { CanvasTextContent, createCanvasTextMeasurer } from './text-content';
initializeLexical();
@@ -42,6 +44,8 @@ declare global {
crop: Bounds;
scale: number;
revision: string;
+ /** Whether the requesting user has artifacts; off shows only titles. */
+ artifacts?: boolean;
}) => Promise<void>;
measureCanvasSnapshot: (snapshot: {
document: GraphicsDocument;
@@ -55,6 +59,21 @@ declare global {
}
}
+/** An artifact that never finishes loading must not hold up the whole render. */
+function artifactFramesLoaded(root: HTMLElement) {
+ const frames = root.querySelectorAll('iframe[data-canvas-artifact-frame]');
+ return Promise.all(
+ Array.from(frames, (frame) =>
+ Promise.race([
+ new Promise((resolve) =>
+ frame.addEventListener('load', resolve, { once: true })
+ ),
+ new Promise((resolve) => setTimeout(resolve, 3_000)),
+ ])
+ )
+ );
+}
+
/** Browser-owned deadlines survive a lost Worker connection, including local CDP. */
window.canvasRenderIdle = true;
window.prepareCanvasRender = async () => {
@@ -138,6 +157,25 @@ window.renderCanvasSnapshot = async (snapshot) => {
text: (props) => (
<TextView {...props} contentView={CanvasTextContent} />
),
+ artifact: (props) => (
+ <Show
+ when={snapshot.artifacts}
+ fallback={
+ <div class="size-full border border-edge-muted p-2 text-xs">
+ Artifact: {props.item.geometry.title}
+ </div>
+ }
+ >
+ <ArtifactFrame
+ html={props.item.geometry.html}
+ title={props.item.geometry.title}
+ designWidth={props.item.geometry.designWidth}
+ designHeight={props.item.geometry.designHeight}
+ interactive={false}
+ eager
+ />
+ </Show>
+ ),
image: (props) => (
<div class="size-full border border-edge-muted p-2 text-xs">
Image unavailable: {props.item.geometry.name}
@@ -166,6 +204,7 @@ window.renderCanvasSnapshot = async (snapshot) => {
};
await fontsReady;
await document.fonts.ready;
+ await artifactFramesLoaded(root);
window.readCanvasTextLayout = () =>
Array.from(
root.querySelectorAll<HTMLElement>('[data-graphics-item]')
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 2b74c761c1..c37c585997 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -165,6 +165,13 @@ export const macroConnect = defineFlag({
env: 'ENABLE_MACRO_CONNECT',
});
+/** HTML artifact nodes on Canvas, including running their scripts in a sandbox. */
+export const enableCanvasArtifacts = defineFlag({
+ key: 'enable-canvas-artifacts',
+ env: 'ENABLE_CANVAS_ARTIFACTS',
+ default: onInDev,
+});
+
/** Browser-style tabs in the macOS desktop title bar; each tab holds a split layout. */
export const enableDesktopTabs = defineFlag({
key: 'enable-desktop-tabs',
diff --git a/docs/agent-guide/canvas.md b/docs/agent-guide/canvas.md
index 22a7a4e1ef..d24661e349 100644
--- a/docs/agent-guide/canvas.md
+++ b/docs/agent-guide/canvas.md
@@ -25,6 +25,14 @@ Controls are disabled while resolving the image source or running an action.
Check an uploaded image and a workspace image, and confirm both actions disappear
for multiple selections, groups, videos, and non-image shapes.
+## Artifacts
+
+Artifacts are behind the `enable-canvas-artifacts` flag. **Insert** offers
+**Artifact**, which places a node with starter HTML. The Canvas inspector edits its
+title and HTML. The document runs in a sandboxed frame; **Interact** or a
+double-click passes pointer input to it, and **Done** or a click elsewhere returns
+to the canvas. With the flag off, an artifact shows only its title and no script runs.
+
## Multiplayer canvas
Open the same canvas as two editors and a viewer. Create/move a shape in one
diff --git a/docs/architecture/canvas.md b/docs/architecture/canvas.md
index a9e8644e6c..65ba78cb9a 100644
--- a/docs/architecture/canvas.md
+++ b/docs/architecture/canvas.md
@@ -35,6 +35,14 @@ Canvas Next is the Macro host for a reusable graphics engine. The host owns
product UI and services; `@macro-inc/graphics` owns the portable scene and editing
model.
+## Artifacts
+
+An `artifact` node holds a self-contained HTML document, running behind
+`enable-canvas-artifacts`. Graphics stores it as opaque content; the Canvas host
+runs it in an opaque-origin sandboxed iframe, without a separate domain. See the
+[Canvas Next README](../../apps/web/src/features/block-canvas/README.md#artifacts)
+for the security model and its limits.
+
## Layers
| Layer | Responsibility |
diff --git a/packages/graphics/src/core/artifact-order.ts b/packages/graphics/src/core/artifact-order.ts
new file mode 100644
index 0000000000..0bd17db357
--- /dev/null
+++ b/packages/graphics/src/core/artifact-order.ts
@@ -0,0 +1,23 @@
+import type { ArtifactItem, GraphicsDocument } from './model';
+import { sortKeysBetween } from './ordering';
+
+/** Artifacts in presentation order. Concurrent inserts can share a key, so the
+ * ID breaks ties the same way on every client. */
+export function presentationOrder(document: GraphicsDocument): ArtifactItem[] {
+ const artifacts = Object.values(document.items).filter(
+ (item): item is ArtifactItem => item.type === 'artifact'
+ );
+
+ return artifacts.sort((a, b) => {
+ const left = a.geometry.presentOrder;
+ const right = b.geometry.presentOrder;
+ if (left !== right) return left < right ? -1 : 1;
+ return a.id < b.id ? -1 : 1;
+ });
+}
+
+/** Sort key placing a new artifact after every existing one. */
+export function nextPresentOrder(document: GraphicsDocument): string {
+ const last = presentationOrder(document).at(-1);
+ return sortKeysBetween(last?.geometry.presentOrder ?? null, null, 1)[0]!;
+}
diff --git a/packages/graphics/src/core/index.ts b/packages/graphics/src/core/index.ts
index b3c42e3268..43dee88453 100644
--- a/packages/graphics/src/core/index.ts
+++ b/packages/graphics/src/core/index.ts
@@ -1,6 +1,7 @@
export * from './affine';
export { resolveAppearance } from './appearance';
export * from './artifact-commands';
+export * from './artifact-order';
export type { GraphicsBackend } from './backend';
export {
fitImageCamera,
@@ -33,6 +34,7 @@ export { type LayerOperation, reorderNodes } from './layering';
export { fullyConnected, layoutBounds, layoutRoots } from './layout';
export type {
Appearance,
+ ArtifactItem,
Bounds,
Camera,
EllipseItem,
diff --git a/packages/graphics/src/core/model.ts b/packages/graphics/src/core/model.ts
index 96e2379cc7..9e2d41289a 100644
--- a/packages/graphics/src/core/model.ts
+++ b/packages/graphics/src/core/model.ts
@@ -54,6 +54,7 @@ export type ShapeItem<K extends ShapeKind = ShapeKind> = {
export type RectangleItem = ShapeItem<'rectangle'>;
export type EllipseItem = ShapeItem<'ellipse'>;
export type PencilItem = ShapeItem<'pencil'>;
+export type ArtifactItem = ShapeItem<'artifact'>;
export type GroupItem = SpatialNode & Readonly<{ type: 'group' }>;
export type SurfaceItem = Readonly<{ id: string; type: 'surface' }>;
export type GraphicsItem = ShapeItem | GroupItem | SurfaceItem;
diff --git a/packages/graphics/src/core/shapes/artifact.ts b/packages/graphics/src/core/shapes/artifact.ts
index 4dd1f513b1..4deef90266 100644
--- a/packages/graphics/src/core/shapes/artifact.ts
+++ b/packages/graphics/src/core/shapes/artifact.ts
@@ -16,6 +16,10 @@ export type ArtifactGeometry = BoxGeometry &
presentOrder: string;
}>;
+/** Authoring limit for hosts and AI edits. Stored scenes are not rejected over
+ * it, so one oversized artifact can never stop a canvas from opening. */
+export const ARTIFACT_HTML_MAX_LENGTH = 256_000;
+
const positive = (value: unknown) =>
typeof value === 'number' && Number.isFinite(value) && value > 0;
diff --git a/packages/graphics/tests/artifact-order.test.ts b/packages/graphics/tests/artifact-order.test.ts
new file mode 100644
index 0000000000..5dacd5d122
--- /dev/null
+++ b/packages/graphics/tests/artifact-order.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import { createScene, translation } from '../src/core';
+import {
+ nextPresentOrder,
+ presentationOrder,
+} from '../src/core/artifact-order';
+
+const artifact = (id: string, presentOrder: string) => ({
+ id,
+ type: 'artifact' as const,
+ placement: { parentId: 'scene-root', sortKey: `a${id}` },
+ transform: translation(0, 0),
+ appearance: { fill: '#fff', stroke: '#000' },
+ geometry: {
+ width: 100,
+ height: 100,
+ title: id,
+ html: '',
+ designWidth: 100,
+ designHeight: 100,
+ presentOrder,
+ },
+});
+
+describe('presentation order', () => {
+ it('sorts artifacts by key and breaks ties by id', () => {
+ const scene = createScene([
+ artifact('3', 'a1'),
+ artifact('2', 'a0'),
+ artifact('1', 'a1'),
+ ]);
+
+ expect(presentationOrder(scene).map((item) => item.id)).toEqual([
+ '2',
+ '1',
+ '3',
+ ]);
+ });
+
+ it('places a new artifact after every existing one', () => {
+ const scene = createScene([artifact('1', 'a5'), artifact('2', 'a2')]);
+
+ expect(nextPresentOrder(scene) > 'a5').toBe(true);
+ });
+});