:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): show suggested changes as a field diff with a rendered email comparison (#112717)
Daniel Marchuk6690d83d297b
diff --git a/frontend/src/lib/hooks/useBodyIsDark.ts b/frontend/src/lib/hooks/useBodyIsDark.tsnew file mode 100644index 000000000000..3a408894a1be--- /dev/null+++ b/frontend/src/lib/hooks/useBodyIsDark.ts@@ -0,0 +1,16 @@+import { useEffect, useState } from 'react'++/** Whether the page shows the dark theme, read from `body[theme]`, the attribute the surrounding CSS+ * follows. `themeLogic.isDarkModeOn` can lag behind it, which left the editor light on a dark page. */+export function useBodyIsDark(): boolean {+ const [isDark, setIsDark] = useState(() => document.body.getAttribute('theme') === 'dark')+ useEffect(() => {+ const sync = (): void => setIsDark(document.body.getAttribute('theme') === 'dark')+ // The attribute may already have changed between the first render and here.+ sync()+ const observer = new MutationObserver(sync)+ observer.observe(document.body, { attributeFilter: ['theme'] })+ return () => observer.disconnect()+ }, [])+ return isDark+}diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex caa37e8729e7..9afe713a56e0 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -6,6 +6,7 @@ import * as monacoModule from 'monaco-editor'import { IDisposable, editor, editor as importedEditor } from 'monaco-editor'import { useEffect, useMemo, useRef, useState } from 'react'+import { useBodyIsDark } from 'lib/hooks/useBodyIsDark'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { usePageVisibility } from 'lib/hooks/usePageVisibility'import { Spinner } from 'lib/lemon-ui/Spinner'@@ -71,21 +72,6 @@ function remeasureFontsWhenReady(monaco: Monaco): void {void document.fonts.ready.then(() => monaco.editor.remeasureFonts())}-/** Whether the page shows the dark theme, read from `body[theme]`, the attribute the surrounding CSS- * follows. `themeLogic.isDarkModeOn` can lag behind it, which left the editor light on a dark page. */-function useBodyIsDark(): boolean {- const [isDark, setIsDark] = useState(() => document.body.getAttribute('theme') === 'dark')- useEffect(() => {- const sync = (): void => setIsDark(document.body.getAttribute('theme') === 'dark')- // The attribute may already have changed between the first render and here.- sync()- const observer = new MutationObserver(sync)- observer.observe(document.body, { attributeFilter: ['theme'] })- return () => observer.disconnect()- }, [])- return isDark-}-function initEditor(monaco: Monaco,editor: importedEditor.IStandaloneCodeEditor,diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsxindex 721fbf04b8eb..d3d34cd868c7 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx@@ -1,45 +1,34 @@import { useValues } from 'kea'import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'-import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { Tooltip } from 'lib/lemon-ui/Tooltip'import type { WorkflowProposalApi } from '../../generated/api.schemas'import { workflowLogic } from '../workflowLogic'-import { SuggestedFieldChange, describeSuggestedChanges } from './suggestionChanges'+import { SuggestedFieldChange, describeSuggestedChanges, groupStepFields } from './suggestionChanges'+import { WorkflowSuggestionEmailChange } from './WorkflowSuggestionEmailChange'+import { WorkflowSuggestionFieldDiff } from './WorkflowSuggestionFieldDiff'-function ChangedValue({ value }: { value: unknown }): JSX.Element {- if (value === undefined) {- return <span className="text-secondary italic">Not set</span>- }- if (value === null) {- return <span className="text-secondary italic">Removed</span>- }- if (typeof value === 'string') {- return <span className="whitespace-pre-wrap break-words line-clamp-4">{value}</span>- }+function FieldDiffs({+ fields,+ emails = [],+ isNewStep = false,+}: {+ fields: SuggestedFieldChange[]+ emails?: SuggestedFieldChange[]+ isNewStep?: boolean+}): JSX.Element {return (- <pre className="text-xs bg-surface-secondary rounded p-2 overflow-x-auto mb-0 max-h-40">- {JSON.stringify(value, null, 2)}- </pre>+ <div className="flex flex-col gap-3 pl-2 border-l">+ {fields.map((change) => (+ <WorkflowSuggestionFieldDiff key={change.path} change={change} />+ ))}+ {emails.map((change) => (+ <WorkflowSuggestionEmailChange key={change.path} change={change} isNewStep={isNewStep} />+ ))}+ </div>)}-const COLUMNS: LemonTableColumns<SuggestedFieldChange> = [- {- title: 'Field',- key: 'field',- width: '20%',- render: (_, change) => (- <Tooltip title={change.path}>- <span className="font-medium">{change.label}</span>- </Tooltip>- ),- },- { title: 'Now', key: 'before', width: '40%', render: (_, change) => <ChangedValue value={change.before} /> },- { title: 'Suggested', key: 'after', width: '40%', render: (_, change) => <ChangedValue value={change.after} /> },-]-export function WorkflowSuggestionDetails({id,proposal,@@ -54,18 +43,35 @@ export function WorkflowSuggestionDetails({return (<div className="flex flex-col gap-3 text-sm">{nothingToShow && <span className="text-secondary">This suggestion changes nothing on the workflow.</span>}- {changes.steps.map((step) => (- <div key={step.stepId} className="flex flex-col gap-1">- <span className="font-semibold">- {step.stepName ? `Step: ${step.stepName}` : `New step: ${step.stepId}`}- </span>- <LemonTable size="small" columns={COLUMNS} dataSource={step.fields} rowKey="path" />- </div>- ))}+ {changes.steps.map((step) => {+ const { email, main, other } = groupStepFields(step)+ return (+ <div key={step.stepId} className="flex flex-col gap-1">+ <span className="font-semibold">+ {step.isNew+ ? `New step: ${step.stepName ?? step.stepId}`+ : `Step: ${step.stepName ?? step.stepId}`}+ </span>+ <FieldDiffs fields={main} emails={email} isNewStep={step.isNew} />+ {other.length > 0 && (+ <LemonCollapse+ size="xsmall"+ panels={[+ {+ key: 'other',+ header: `Other settings (${other.length})`,+ content: <FieldDiffs fields={other} />,+ },+ ]}+ />+ )}+ </div>+ )+ })}{changes.workflow.length > 0 && (<div className="flex flex-col gap-1"><span className="font-semibold">Workflow</span>- <LemonTable size="small" columns={COLUMNS} dataSource={changes.workflow} rowKey="path" />+ <FieldDiffs fields={changes.workflow} /></div>)}<LemonCollapsediff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailChange.stories.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailChange.stories.tsxnew file mode 100644index 000000000000..c5f62e79247a--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailChange.stories.tsx@@ -0,0 +1,64 @@+import { Meta, StoryFn } from '@storybook/react'++import { WorkflowSuggestionEmailChange } from './WorkflowSuggestionEmailChange'++const meta: Meta<typeof WorkflowSuggestionEmailChange> = {+ title: 'Products/Workflows/Suggestion email change',+ component: WorkflowSuggestionEmailChange,+ // Monaco lays the diff out after the first paint, like the other Monaco diff stories.+ tags: ['test-skip'],+}+export default meta++const email = (cta: string, buttonStyle = 'background:#1d4aff;color:#fff;padding:12px 20px'): string =>+ `<html><body><h1>Hi there,</h1><p>You finished setup. Here is one more thing to try before the week is out, and it only takes a minute.</p><p><a href="https://example.com" style="${buttonStyle}">${cta}</a></p><p>Thanks, the Example team</p></body></html>`++const Template: StoryFn<typeof WorkflowSuggestionEmailChange> = (args) => (+ <div className="max-w-200">+ <WorkflowSuggestionEmailChange {...args} />+ </div>+)++export const TextChange = Template.bind({})+TextChange.args = {+ isNewStep: false,+ change: {+ path: 'config.inputs.email.value.html',+ label: 'email › html',+ before: email('Run the play'),+ after: email('Create your first workflow'),+ },+}++export const StylingOnly = Template.bind({})+StylingOnly.args = {+ isNewStep: false,+ change: {+ path: 'config.inputs.email.value.html',+ label: 'email › html',+ before: email('Run the play'),+ after: email('Run the play', 'background:#1d4aff;color:#fff;padding:16px 28px;font-size:17px'),+ },+}++export const NewEmailStep = Template.bind({})+NewEmailStep.args = {+ isNewStep: true,+ change: {+ path: 'config.inputs.email.value.html',+ label: 'email › html',+ before: undefined,+ after: email('Create your first workflow'),+ },+}++export const EmptyEmailOnExistingStep = Template.bind({})+EmptyEmailOnExistingStep.args = {+ isNewStep: false,+ change: {+ path: 'config.inputs.email.value.html',+ label: 'email › html',+ before: '',+ after: email('Create your first workflow'),+ },+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailChange.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailChange.tsxnew file mode 100644index 000000000000..a0ca2952b6af--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailChange.tsx@@ -0,0 +1,46 @@+import { useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import type { SuggestedFieldChange } from './suggestionChanges'+import { WorkflowSuggestionEmailCompareModal } from './WorkflowSuggestionEmailCompareModal'+import { WorkflowSuggestionFieldDiff } from './WorkflowSuggestionFieldDiff'++function asHtml(value: unknown): string | null {+ return typeof value === 'string' && value.trim() ? value : null+}++export function WorkflowSuggestionEmailChange({+ change,+ isNewStep,+}: {+ change: SuggestedFieldChange+ isNewStep: boolean+}): JSX.Element {+ const [comparing, setComparing] = useState(false)++ return (+ <>+ <WorkflowSuggestionFieldDiff+ change={change}+ action={+ <LemonButton+ type="secondary"+ size="small"+ data-attr="workflow-suggestion-compare-emails"+ onClick={() => setComparing(true)}+ >+ Compare emails+ </LemonButton>+ }+ />+ <WorkflowSuggestionEmailCompareModal+ isOpen={comparing}+ onClose={() => setComparing(false)}+ isNewEmail={isNewStep}+ before={asHtml(change.before)}+ after={asHtml(change.after)}+ />+ </>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailCompareModal.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailCompareModal.tsxnew file mode 100644index 000000000000..3610f44fe6ab--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEmailCompareModal.tsx@@ -0,0 +1,96 @@+import { useState } from 'react'++import { LemonButton, LemonModal } from '@posthog/lemon-ui'++import { emailPreviewDocument } from './suggestionEmailPreview'++function RenderedEmail({+ label,+ html,+ loadRemote,+}: {+ label: string+ html: string | null+ loadRemote: boolean+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1 flex-1 min-w-xl">+ <span className="text-xs font-semibold uppercase text-secondary">{label}</span>+ {html ? (+ // sandbox="" keeps scripts and same-origin access out of model-written HTML.+ <iframe+ title={`Rendered email: ${label}`}+ sandbox=""+ referrerPolicy="no-referrer"+ srcDoc={emailPreviewDocument(html, { loadRemote })}+ className="w-full h-[70vh] bg-white rounded border"+ />+ ) : (+ <div className="flex items-center justify-center h-[70vh] rounded border text-secondary">+ No email content+ </div>+ )}+ </div>+ )+}++export function WorkflowSuggestionEmailCompareModal({+ isOpen,+ onClose,+ isNewEmail,+ before,+ after,+}: {+ isOpen: boolean+ onClose: () => void+ isNewEmail: boolean+ before: string | null+ after: string | null+}): JSX.Element {+ // The suggested HTML is model-written, so its remote images load only when a person asks for them.+ const [loadRemote, setLoadRemote] = useState(false)+ const close = (): void => {+ setLoadRemote(false)+ onClose()+ }++ return (+ <LemonModal+ isOpen={isOpen}+ onClose={close}+ width={1400}+ title="Compare emails"+ description={+ isNewEmail+ ? 'This suggestion adds a new email.'+ : 'The email as it sends now, next to the email with this suggestion applied.'+ }+ >+ <div className="flex items-center justify-between gap-2 flex-wrap mb-2">+ <span className="text-secondary">+ {loadRemote+ ? 'Remote images are loaded.'+ : 'Remote images are blocked, so opening this preview does not contact the servers they come from.'}+ </span>+ <LemonButton+ type="secondary"+ size="small"+ data-attr="workflow-suggestion-load-remote-images"+ onClick={() => setLoadRemote(!loadRemote)}+ >+ {loadRemote ? 'Block remote images' : 'Load remote images'}+ </LemonButton>+ </div>+ <div className="flex flex-wrap gap-4">+ {isNewEmail ? (+ <RenderedEmail label="New email" html={after} loadRemote={loadRemote} />+ ) : (+ <>+ <RenderedEmail label="Now" html={before} loadRemote={loadRemote} />+ <RenderedEmail label="Suggested" html={after} loadRemote={loadRemote} />+ </>+ )}+ </div>+ </LemonModal>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionFieldDiff.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionFieldDiff.tsxnew file mode 100644index 000000000000..94c79408ec85--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionFieldDiff.tsx@@ -0,0 +1,142 @@+import { ReactNode, Suspense, useEffect, useRef, useState } from 'react'++import { Spinner } from '@posthog/lemon-ui'++import type { MonacoDiffEditorProps } from 'lib/components/MonacoDiffEditor'+import { useBodyIsDark } from 'lib/hooks/useBodyIsDark'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { lazyWithRetry } from 'lib/utils/retryImport'++import { SuggestedFieldChange, describeFieldView } from './suggestionChanges'++const MonacoDiffEditor = lazyWithRetry(() => import('lib/components/MonacoDiffEditor'))++// Module-level so the editor does not re-apply its options on every render.+const DIFF_OPTIONS: MonacoDiffEditorProps['options'] = {+ automaticLayout: true,+ renderOverviewRuler: false,+ scrollBeyondLastLine: false,+ minimap: { enabled: false },+ wordWrap: 'on',+ diffWordWrap: 'on',+ diffAlgorithm: 'advanced',+ hideUnchangedRegions: {+ enabled: true,+ contextLineCount: 3,+ minimumLineCount: 3,+ revealLineCount: 20,+ },+}++function InlineValue({ value, side }: { value: unknown; side: 'before' | 'after' }): JSX.Element {+ if (value === undefined) {+ return <span className="text-secondary italic">Not set</span>+ }+ if (value === null) {+ return <span className="text-secondary italic">Removed</span>+ }+ return (+ <span+ className={+ side === 'before'+ ? 'rounded px-1 bg-fill-error-highlight line-through break-all whitespace-pre-wrap'+ : 'rounded px-1 bg-fill-success-highlight break-all whitespace-pre-wrap'+ }+ >+ {typeof value === 'string' ? value : JSON.stringify(value)}+ </span>+ )+}++export function WorkflowSuggestionFieldDiff({+ change,+ action,+}: {+ change: SuggestedFieldChange+ /** Rendered at the end of the field's label row. */+ action?: ReactNode+}): JSX.Element {+ const isDarkModeOn = useBodyIsDark()+ const view = describeFieldView(change)+ const isTwoSidedDiff = view.kind === 'diff' && view.original !== '' && view.modified !== ''+ // Each diff editor costs real main-thread time, and a workflow can hold several long suggestions,+ // so an editor mounts only when its card comes near the screen. The container exists only for a+ // two-sided diff, so the observer attaches again when a field becomes one.+ const diffRef = useRef<HTMLDivElement>(null)+ const [inView, setInView] = useState(false)+ useEffect(() => {+ const element = diffRef.current+ if (inView || !element) {+ return+ }+ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry.isIntersecting) {+ setInView(true)+ observer.disconnect()+ }+ },+ { rootMargin: '400px' }+ )+ observer.observe(element)+ return () => observer.disconnect()+ }, [inView, isTwoSidedDiff])++ const label = (+ <Tooltip title={change.path}>+ <span className="font-medium">{change.label}</span>+ </Tooltip>+ )++ if (view.kind === 'inline') {+ return (+ <div className="flex items-baseline gap-2 flex-wrap">+ {label}+ <InlineValue value={change.before} side="before" />+ <span className="text-secondary">→</span>+ <InlineValue value={change.after} side="after" />+ {action && <div className="ml-auto">{action}</div>}+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-1 w-full">+ <div className="flex items-center gap-2 flex-wrap">+ {label}+ {change.before === undefined && (+ <span className="text-xs text-secondary">Added by this suggestion</span>+ )}+ {change.after === null && <span className="text-xs text-secondary">Removed by this suggestion</span>}+ {action && <div className="ml-auto">{action}</div>}+ </div>+ {/* Monaco shows an empty side as a changed blank line, so a one-sided change is a plain block. */}+ {!isTwoSidedDiff ? (+ <pre+ className={`text-xs rounded p-2 mb-0 max-h-80 overflow-auto whitespace-pre-wrap break-words ${+ view.modified === '' ? 'bg-fill-error-highlight' : 'bg-fill-success-highlight'+ }`}+ >+ {view.modified || view.original}+ </pre>+ ) : (+ <div ref={diffRef} className="border rounded overflow-hidden">+ {inView ? (+ <Suspense fallback={<Spinner className="text-2xl mx-auto my-4" />}>+ <MonacoDiffEditor+ original={view.original}+ modified={view.modified}+ // The XML tokenizer colors HTML without the HTML language worker, which is not bundled.+ language={view.language === 'html' ? 'xml' : view.language}+ options={DIFF_OPTIONS}+ theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}+ />+ </Suspense>+ ) : (+ <Spinner className="text-2xl mx-auto my-4" />+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.ts b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.tsindex d8cba7ab0811..3d0419a10b8d 100644--- a/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.ts+++ b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.ts@@ -1,5 +1,5 @@import type { HogFlow } from '../hogflows/types'-import { describeSuggestedChanges } from './suggestionChanges'+import { SuggestedFieldView, describeFieldView, describeSuggestedChanges, groupStepFields } from './suggestionChanges'const live = {name: 'Onboarding welcome',@@ -12,7 +12,7 @@ const live = {],} as unknown as HogFlow-describe('describeSuggestedChanges', () => {+describe('suggestionChanges', () => {it('pairs each changed field with the live value at the same path and names the step', () => {const changes = describeSuggestedChanges({@@ -28,6 +28,7 @@ describe('describeSuggestedChanges', () => {{stepId: 'email_1',stepName: 'Welcome email',+ isNew: false,fields: [{path: 'config.inputs.email.value.subject',@@ -42,11 +43,11 @@ describe('describeSuggestedChanges', () => {})it.each([- ['a step the live workflow does not have', { actions: [{ id: 'new_1', name: 'Added' }] }, null],- ['no live workflow yet', { actions: [{ id: 'email_1', name: 'Added' }] }, null],- ])('reads nothing as before for %s', (_name, content, expectedName) => {+ ['a step the live workflow does not have', { actions: [{ id: 'new_1', name: 'Added' }] }],+ ['no live workflow yet', { actions: [{ id: 'email_1', name: 'Added' }] }],+ ])('reads nothing as before for %s, and names the step from the suggestion', (_name, content) => {const changes = describeSuggestedChanges(content, _name.startsWith('no') ? null : live)- expect(changes.steps[0].stepName).toBe(expectedName)+ expect(changes.steps[0]).toMatchObject({ stepName: 'Added', isNew: true })expect(changes.steps[0].fields).toEqual([{ path: 'name', label: 'name', before: undefined, after: 'Added' }])})@@ -71,4 +72,127 @@ describe('describeSuggestedChanges', () => {// Approving reduces the patch the same way, so the table must not read as a four-field edit.expect(steps[0].fields.map((field) => field.path)).toEqual(['config.subject'])})++ it.each([+ [+ 'a new email step',+ null,+ {+ main: ['name', 'config.inputs.email.value.subject'],+ other: ['config.utm_tags_enabled', 'config.inputs.email.value.design.body.rows'],+ },+ ],+ [+ 'an edited email step',+ {+ name: 'Welcome email',+ config: { inputs: { email: { value: { subject: 'Old', cc: '[email protected]' } } } },+ },+ {+ main: [+ 'name',+ 'config.utm_tags_enabled',+ 'config.inputs.email.value.subject',+ 'config.inputs.email.value.preheader',+ 'config.inputs.email.value.cc',+ ],+ other: ['config.inputs.email.value.design.body.rows'],+ },+ ],+ ])('groups the fields of %s so the email and its key fields come first', (_name, liveStep, expected) => {+ const step = {+ id: 'email_2',+ name: 'Follow-up',+ config: {+ utm_tags_enabled: true,+ inputs: {+ email: {+ value: {+ subject: 'Did you see this?',+ preheader: '',+ cc: '',+ html: '<p>hi</p>',+ design: { body: { rows: [{ id: 'row_1' }] } },+ },+ },+ },+ },+ }+ const workflow = { actions: liveStep ? [{ id: 'email_2', ...liveStep }] : [] } as unknown as HogFlow++ const grouped = groupStepFields(describeSuggestedChanges({ actions: [step] }, workflow).steps[0])++ expect(grouped.email.map((field) => field.path)).toEqual(['config.inputs.email.value.html'])+ expect(grouped.main.map((field) => field.path)).toEqual(expected.main)+ expect(grouped.other.map((field) => field.path)).toEqual(expected.other)+ })++ describe('describeFieldView', () => {+ const emailHtml = (cta: string): string =>+ `<table><tr><td><h1>Welcome aboard</h1></td></tr><tr><td><a href="https://example.com/start">${cta}</a></td></tr></table>`++ it.each([+ [+ 'a short text edit',+ 'config.inputs.email.value.subject',+ 'Old subject',+ 'New subject',+ { kind: 'inline' },+ ],+ ['a number', 'config.delay_duration', 1, 2, { kind: 'inline' }],+ [+ 'minified email HTML, split between tags',+ 'config.inputs.email.value.html',+ emailHtml('Run the play'),+ emailHtml('Create your first workflow'),+ {+ kind: 'diff',+ language: 'html',+ original: emailHtml('Run the play').replace(/>(?=<)/g, '>\n'),+ modified: emailHtml('Create your first workflow').replace(/>(?=<)/g, '>\n'),+ },+ ],+ [+ 'a new multi-line text field',+ 'config.inputs.email.value.text',+ undefined,+ 'Hi there\nYour trial ends soon',+ { kind: 'diff', language: 'plaintext', original: '', modified: 'Hi there\nYour trial ends soon' },+ ],+ [+ 'an object',+ 'filters',+ { events: [{ id: 'signed_up' }] },+ { events: [{ id: 'signed_up' }, { id: 'invited_user' }] },+ {+ kind: 'diff',+ language: 'json',+ original: JSON.stringify({ events: [{ id: 'signed_up' }] }, null, 2),+ modified: JSON.stringify({ events: [{ id: 'signed_up' }, { id: 'invited_user' }] }, null, 2),+ },+ ],+ ])('shows %s as the right view', (_name, path, before, after, expected) => {+ expect(describeFieldView({ path, label: path, before, after })).toEqual(expected)+ })+ })++ it.each([+ ['the same image, so only the text changes', 'A', 'A', false],+ ['a swapped image of the same size', 'A', 'B', true],+ ])('shows an inline image as its size and digest: %s', (_name, beforeFill, afterFill, imageLineDiffers) => {+ const html = (fill: string, cta: string): string =>+ `<p>Hi</p><img src="data:image/png;base64,${fill.repeat(4096)}"><a>${cta}</a>`++ const view = describeFieldView({+ path: 'config.inputs.email.value.html',+ label: 'email › html',+ before: html(beforeFill, 'Old'),+ after: html(afterFill, 'New'),+ })++ const { original, modified } = view as Extract<SuggestedFieldView, { kind: 'diff' }>+ const imageLine = (text: string): string => text.split('\n')[1]+ expect(imageLine(original)).toMatch(/^<img src="data:image\/png;base64,… \(3 KB, [0-9a-f]{8}\)">$/)+ expect(imageLine(original) !== imageLine(modified)).toBe(imageLineDiffers)+ })})diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionChanges.ts b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.tsindex 4d6165c8a9b2..b298d909361c 100644--- a/products/workflows/frontend/Workflows/suggestions/suggestionChanges.ts+++ b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.ts@@ -10,17 +10,31 @@ export interface SuggestedFieldChange {export interface SuggestedStepChange {stepId: stringstepName: string | null+ isNew: booleanfields: SuggestedFieldChange[]}+export interface GroupedStepFields {+ email: SuggestedFieldChange[]+ main: SuggestedFieldChange[]+ other: SuggestedFieldChange[]+}+export interface SuggestedChanges {steps: SuggestedStepChange[]workflow: SuggestedFieldChange[]}+export type SuggestedFieldView =+ | { kind: 'inline' }+ | { kind: 'diff'; language: 'html' | 'json' | 'plaintext'; original: string; modified: string }+// Every step input sits at `config.inputs.<name>.value`, so those segments say nothing to a reader.const SILENT_SEGMENTS = new Set(['config', 'inputs', 'value'])+// A value longer than this does not fit on one line next to its replacement, so it gets a diff.+const INLINE_MAX_LENGTH = 80+function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)}@@ -75,6 +89,69 @@ function sameLeaf(before: unknown, after: unknown): boolean {return JSON.stringify(before) === JSON.stringify(after)}+function fitsInline(value: unknown): boolean {+ if (typeof value === 'string') {+ return value.length <= INLINE_MAX_LENGTH && !value.includes('\n')+ }+ return !isPlainObject(value) && !Array.isArray(value)+}++function looksLikeHtml(change: SuggestedFieldChange): boolean {+ if (change.path.split('.').at(-1) === 'html') {+ return true+ }+ return [change.before, change.after].some((value) => typeof value === 'string' && /^\s*</.test(value))+}++// Minified email HTML can be one long line. A line break between adjacent tags lets the diff+// point at the changed tag, and it keeps HTML that already has line breaks as it is.+function splitAdjacentTags(html: string): string {+ return html.replace(/>(?=<)/g, '>\n')+}++// FNV-1a, enough to tell two payloads apart in a label.+function shortDigest(text: string): string {+ let hash = 0x811c9dc5+ for (let index = 0; index < text.length; index++) {+ hash = Math.imul(hash ^ text.charCodeAt(index), 0x01000193)+ }+ return (hash >>> 0).toString(16).padStart(8, '0')+}++// Inline images can be megabytes of base64 that hide the change and stall the diff. Their bytes+// say nothing a reader can judge, so the diff shows their size, plus a digest so a swapped image+// still shows as a change. Compare emails renders them.+function shortenDataUris(html: string): string {+ return html.replace(/data:([\w/+.-]+);base64,[A-Za-z0-9+/=\s]{200,}/g, (match, type: string) => {+ const kilobytes = Math.round((match.length * 3) / 4 / 1024)+ return `data:${type};base64,… (${kilobytes.toLocaleString()} KB, ${shortDigest(match)})`+ })+}++export function describeFieldView(change: SuggestedFieldChange): SuggestedFieldView {+ const { before, after } = change+ if (fitsInline(before) && fitsInline(after)) {+ return { kind: 'inline' }+ }+ const isText = (value: unknown): boolean => typeof value === 'string' || value === undefined || value === null+ if (isText(before) && isText(after)) {+ const original = typeof before === 'string' ? before : ''+ const modified = typeof after === 'string' ? after : ''+ if (looksLikeHtml(change)) {+ return {+ kind: 'diff',+ language: 'html',+ original: splitAdjacentTags(shortenDataUris(original)),+ modified: splitAdjacentTags(shortenDataUris(modified)),+ }+ }+ return { kind: 'diff', language: 'plaintext', original, modified }+ }+ const asJson = (value: unknown): string =>+ value === undefined || value === null ? '' : JSON.stringify(value, null, 2)+ return { kind: 'diff', language: 'json', original: asJson(before), modified: asJson(after) }+}+export function describeSuggestedChanges(content: Record<string, unknown>, live: HogFlow | null): SuggestedChanges {const { actions, ...rest } = contentconst liveSteps = new Map((live?.actions ?? []).map((action) => [action.id, action]))@@ -89,7 +166,8 @@ export function describeSuggestedChanges(content: Record<string, unknown>, live:const liveStep = liveSteps.get(id)steps.push({stepId: id,- stepName: liveStep?.name ?? null,+ stepName: liveStep?.name ?? (typeof patch.name === 'string' ? patch.name : null),+ isNew: liveStep === undefined,fields: leafChanges(patch, liveStep),})}@@ -97,3 +175,40 @@ export function describeSuggestedChanges(content: Record<string, unknown>, live:return { steps, workflow: leafChanges(rest, live) }}++const EMAIL_HTML_PATH = /(^|\.)email\.value\.html$/+// The visual editor's layout state. The rendered emails show what it changes.+const EMAIL_DESIGN_PATH = /(^|\.)email\.value\.design(\.|$)/+// What a reader needs to judge a new step. Its other settings are mostly defaults.+const NEW_STEP_KEY_PATHS = new Set([+ 'name',+ 'config.inputs.email.value.subject',+ 'config.inputs.email.value.preheader',+ 'config.inputs.email.value.to.email',+])++function isEmpty(value: unknown): boolean {+ return (+ value === undefined ||+ value === null ||+ value === '' ||+ (Array.isArray(value) && value.length === 0) ||+ (isPlainObject(value) && Object.keys(value).length === 0)+ )+}++export function groupStepFields(step: SuggestedStepChange): GroupedStepFields {+ const grouped: GroupedStepFields = { email: [], main: [], other: [] }+ for (const field of step.fields) {+ if (EMAIL_HTML_PATH.test(field.path)) {+ grouped.email.push(field)+ } else if (EMAIL_DESIGN_PATH.test(field.path)) {+ grouped.other.push(field)+ } else if (!step.isNew) {+ grouped.main.push(field)+ } else if (!isEmpty(field.after)) {+ grouped[NEW_STEP_KEY_PATHS.has(field.path) ? 'main' : 'other'].push(field)+ }+ }+ return grouped+}diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEmailPreview.test.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEmailPreview.test.tsnew file mode 100644index 000000000000..24a8fd867540--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEmailPreview.test.ts@@ -0,0 +1,64 @@+import { emailPreviewDocument } from './suggestionEmailPreview'++const PIXEL = '<img src="https://attacker.example/pixel.gif">'++function preview(html: string, loadRemote = false): Document {+ return new DOMParser().parseFromString(emailPreviewDocument(html, { loadRemote }), 'text/html')+}++function policyOf(doc: Document): string | null | undefined {+ return doc.head.firstElementChild?.matches('meta[http-equiv="Content-Security-Policy"]')+ ? doc.head.firstElementChild.getAttribute('content')+ : undefined+}++describe('emailPreviewDocument', () => {+ it.each([+ ['a full document', `<!DOCTYPE html><html><head><title>Hi</title></head><body>${PIXEL}</body></html>`],+ ['a fragment', `<p>Hi</p>${PIXEL}`],+ ['a head inside a comment', `<!-- <head> --><p>Hi</p>${PIXEL}`],+ ['a head inside a quoted attribute', `<head data-note="> ${PIXEL.replace(/"/g, "'")}"><body>${PIXEL}</body>`],+ ['a head inside a title', `<title><head></title>${PIXEL}`],+ ])('blocks remote images in %s, with the policy first in the real head', (_name, html) => {+ const doc = preview(html)++ expect(policyOf(doc)).toContain('img-src data:;')+ expect(doc.head.querySelectorAll('meta[http-equiv]')).toHaveLength(1)+ expect(doc.querySelector('meta[name="referrer"]')?.getAttribute('content')).toBe('no-referrer')+ })++ it.each([+ ['a refresh', '<meta http-equiv="refresh" content="0;url=https://attacker.example/">'],+ ['a looser policy of its own', `<meta http-equiv="Content-Security-Policy" content="img-src *">`],+ ['a base that repoints links', '<base href="https://attacker.example/">'],+ [+ 'a nested frame with its own refresh',+ `<iframe srcdoc="<meta http-equiv='refresh' content='0;url=https://attacker.example/'>"></iframe>`,+ ],+ [+ 'an embedded object',+ '<object data="https://attacker.example/x"></object><embed src="https://attacker.example/y">',+ ],+ ])('drops %s from the email, even with remote images loaded', (_name, tag) => {+ const doc = preview(`<html><head>${tag}</head><body><p>Hi</p>${tag}</body></html>`, true)++ expect(doc.querySelectorAll('meta[http-equiv]')).toHaveLength(1)+ expect(doc.querySelectorAll('base, iframe, object, embed')).toHaveLength(0)+ expect(policyOf(doc)).toContain('img-src data: https:')+ })++ it.each([+ [+ 'the XHTML transitional doctype emails use',+ '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><body><p>Hi</p></body></html>',+ 'CSS1Compat',+ ],+ ['no doctype', '<p>Hi</p>', 'BackCompat'],+ ])('keeps the rendering mode of %s', (_name, html, mode) => {+ const original = new DOMParser().parseFromString(html, 'text/html')++ expect(original.compatMode).toBe(mode)+ expect(preview(html).compatMode).toBe(mode)+ expect(preview(html).body.textContent).toBe('Hi')+ })+})diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEmailPreview.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEmailPreview.tsnew file mode 100644index 000000000000..6cec38cb9483--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEmailPreview.ts@@ -0,0 +1,42 @@+// The suggested HTML is model-written, and a sandbox stops scripts but not subresources. Blocked, the+// preview renders inline styles and images that ship inside the email and contacts no server at all.+const BLOCKED_POLICY =+ "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; form-action 'none'"+// Only after a person asks: images, stylesheets and fonts load, and nothing else does.+const REMOTE_POLICY =+ "default-src 'none'; style-src 'unsafe-inline' https:; img-src data: https:; font-src data: https:; form-action 'none'"++function doctypeOf(doc: Document): string {+ const { doctype } = doc+ if (!doctype) {+ return ''+ }+ const publicId = doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : ''+ const systemId = doctype.systemId ? `${doctype.publicId ? '' : ' SYSTEM'} "${doctype.systemId}"` : ''+ return `<!DOCTYPE ${doctype.name}${publicId}${systemId}>`+}++/**+ * Builds the document the comparison renders. The email is parsed by the same parser the frame uses, so+ * the policy lands in the real head however the email's own markup is written, rather than wherever a+ * pattern match in the untrusted text points. Parsing fetches nothing.+ */+export function emailPreviewDocument(html: string, { loadRemote }: { loadRemote: boolean }): string {+ const doc = new DOMParser().parseFromString(html, 'text/html')+ // A refresh navigates the frame itself, which no policy directive stops, and a base can repoint links.+ // A nested frame or plugin carries its own document, out of reach of this cleanup, and has no place in an email.+ doc.querySelectorAll('meta[http-equiv], base, iframe, frame, frameset, object, embed').forEach((element) =>+ element.remove()+ )++ const policy = doc.createElement('meta')+ policy.httpEquiv = 'Content-Security-Policy'+ policy.content = loadRemote ? REMOTE_POLICY : BLOCKED_POLICY+ const referrer = doc.createElement('meta')+ referrer.name = 'referrer'+ referrer.content = 'no-referrer'+ doc.head.prepend(policy, referrer)++ // The email's own doctype decides its rendering mode, so the preview keeps it.+ return doctypeOf(doc) + doc.documentElement.outerHTML+}