import { useEditor } from '@craftjs/core'; import { insertTargetOutsideInstance, isInsideInstance } from './global-sections'; import { usePages, treeToCraftState } from '../state/PageContext'; import { fullBleedPageRoots } from '../sitesmith/replace-plan'; import { canvasFingerprint, type CanvasFingerprint } from './canvas-fingerprint'; import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith'; import { sanitizeAiTree, buildNodeTree } from './craft-tree'; import { cleanAiResponse } from '../sitesmith/clean-ai-response'; import { useSiteDesign, type SiteDesign } from '../state/SiteDesignContext'; import { effectiveBackgroundOf } from './effective-background'; import { checkPrimaryCtaAccent, type CtaCheck } from '../sitesmith/cta-check'; import { repairAssetUse, type RepairAsset } from '../sitesmith/asset-repair'; import { toEditorAssetUrls } from '../sitesmith/editor-asset-urls'; import { repairResponseContrast, type ContrastAdjustment, type PatchContext } from './contrast-repair'; // Re-exported for existing callers/tests that import sanitizeAiTree/ // buildNodeTree from this module — the implementation lives in craft-tree.ts // alongside the shared flattener: `templates/apply-template.ts` needs the // exact same tree-materialization logic to load template header/footer/page // content (see the doc comment on `buildNodeTree` in craft-tree.ts). export { sanitizeAiTree, buildNodeTree }; /** * update_props may never touch these keys, regardless of what the AI sends. * `node_id` is the stable identifier other ops (and findNodeIdByAiNodeId) * rely on to re-target a node in later turns of the conversation — letting * the AI clobber it would silently orphan future patches. */ const PROTECTED_UPDATE_PROPS_KEYS = new Set(['node_id']); /** * Find the Craft.js node id that corresponds to an AI node_id value. * Checks `data.props.node_id` first, then falls back to raw id equality. */ export function findNodeIdByAiNodeId(query: any, aiNodeId: string): string | null { const all = query.getNodes() as Record; for (const [id, n] of Object.entries(all)) { if (n.data?.props?.node_id === aiNodeId) return id; if (id === aiNodeId) return id; } return null; } /** * Existing-canvas context for `update_props` ops: the node's props and the nearest ancestor's flat * background, so a text colour the response sets can be judged against what is really behind it. */ export function canvasNodeContext(query: any): PatchContext['nodeContext'] { return (aiNodeId: string) => { try { const id = findNodeIdByAiNodeId(query, aiNodeId); if (!id) return undefined; const props = { ...(query.node(id).get().data.props ?? {}) } as Record; // Same resolver as the style panels (gradients / images come back verbatim -> "not checked"). const parent = query.node(id).get().data.parent as string | null | undefined; const ancestorBg = parent ? effectiveBackgroundOf(query.getNodes() as Record, parent) ?? undefined : undefined; return { props, ancestorBg }; } catch { return undefined; } }; } /** * What the canvas should now show. `settled` is false when a whole-page/site load did not finish * (or fell back to an empty page) within the bound; `expected` is the fingerprint of the applied * result -- computed from the response tree itself for a page/site replace, from the live canvas * right after the (synchronous) edits otherwise. */ export interface AppliedCanvas { settled: boolean; expected: CanvasFingerprint | null } export interface ApplyOutcome { ok: boolean; message?: string; adjustments?: ContrastAdjustment[]; notChecked?: number; canvas?: AppliedCanvas; /** Report-only post-checks on a page/site replace (e.g. primary CTA not accent-filled); never shown to the owner. */ checks?: CtaCheck[]; /** Notes about image references repaired / hero photos chosen (round 9); shown with the other notes. */ imageNotes?: string[]; /** Patch only: how many ops actually changed the canvas (an op naming a missing node does nothing). */ changed?: number; /** Patch only: how many ops the response carried. */ ops?: number; /** Patch only (round 6): ops that did nothing, per reason (counts only). */ dropped?: PatchDropped; } /** unknown_id: the op names a node that is not on the canvas; no_allowed_props: nothing left to set (the * allow-list cleaner removed every prop, or only protected/invalid ones were sent). */ export type PatchDropped = Partial>; /** A canvas load is a setTimeout(0) away; 5 s means something is wrong, not slow. */ const SETTLE_BOUND_MS = 5000; function settleWithin(p: Promise, ms: number): Promise { return new Promise((resolve) => { const t = setTimeout(() => resolve(false), ms); p.then((ok) => { clearTimeout(t); resolve(ok); }, () => { clearTimeout(t); resolve(false); }); }); } /** Repair text/background contrast in a response against the current design (pure; no model call). */ export function repairForCanvas(resp: SitesmithResponse, design: SiteDesign, query: any) { return repairResponseContrast(resp, design, { nodeContext: canvasNodeContext(query) }); } /** Exported for unit tests */ export const __test = { findNodeIdByAiNodeId, buildNodeTree, applyPatch }; /** * React hook that returns an `apply` function. * Call `apply(response)` after a successful Sitesmith API call to materialize * the AI's instructions into the editor. */ export function useApplyAiResponse() { const { actions, query } = useEditor(); const pages = usePages(); const { design } = useSiteDesign(); /** * @param targetNodeId If set and the AI returned a section-scoped replace * instead of a patch, treat the first returned tree as a replacement for * this node (the user said "edit this block" — they don't want a new * section appended at the bottom). */ return async function apply( resp: SitesmithResponse, targetNodeId?: string, opts: { repairContrast?: boolean; /** The owner's request text (an owner-named button colour exempts the CTA check). */ userText?: string | null; /** scope=site only: ADD the pages (keep every other page) instead of replacing the site (round 4). */ addPages?: boolean; /** Round 9: the site's real uploads (fresh list; null = could not be loaded, nothing is checked; absent = no image repair). */ assets?: RepairAsset[] | null; /** Filenames the owner left ticked (hero substitutions pick only from these). */ usableAssets?: string[]; /** scope=page: the page being replaced is the home page. */ homePage?: boolean; /** Uploads to show in the editor as panel proxy URLs (defaults to `assets`; pass it alone to convert without repairing). */ editorAssets?: RepairAsset[] | null } = {}, ): Promise { // 'ask' type = AI wants clarification, nothing to apply if (resp.type === 'ask') return { ok: true }; // Round 9: image references that are not real uploads are repaired, and the hero photo rules run, BEFORE the // cleaner (which would otherwise just drop a proxy URL and leave a hole). Pure, no model call. let imageNotes: string[] = []; if (opts.assets !== undefined) { const rep = repairAssetUse(resp, { assets: opts.assets, usable: opts.usableAssets, userText: opts.userText, homePage: opts.homePage }); resp = rep.resp; imageNotes = rep.notes; for (const n of imageNotes) console.info(`[sitesmith] image: ${n}`); } // G8: allow-list cleaner (URLs, images, CSS, ids; form destinations and head code can never be // set by the model). Runs first, so nothing below -- contrast repair, the canvas -- sees a // value the cleaner would refuse. (Server-side mirror not implemented, deferred.) resp = cleanAiResponse(resp, (aiNodeId) => { const id = findNodeIdByAiNodeId(query, aiNodeId); if (!id) return undefined; const name = query.node(id).get()?.data?.name; return typeof name === 'string' ? name : undefined; }); // Editor canvas/Preview cannot load `assets/`: show uploads as the same proxy URL the AssetPicker stores // (publish rewrites it back to assets/). After the cleaner, which only knows the assets/ form. resp = toEditorAssetUrls(resp, opts.editorAssets !== undefined ? opts.editorAssets : opts.assets).resp; // AI-built pages are full-bleed (no 20px white frame from the Container default) -- new replaces only. resp = fullBleedPageRoots(resp); // Report-only: the primary CTA should use the accent colour (nothing is changed or shown to the owner). const checks = checkPrimaryCtaAccent(resp, opts.userText); for (const c of checks) console.info(`[sitesmith] check ${c.kind}: page "${c.page}" ${c.component} fill ${c.fill ?? '(none)'}`); // Contrast auto-repair (design "Settled calls" 8): fix failing text colours before they reach the canvas. let adjustments: ContrastAdjustment[] = []; let notChecked = 0; if (opts.repairContrast !== false) { const rep = repairForCanvas(resp, design, query); resp = rep.response; adjustments = rep.adjustments; notChecked = rep.notChecked; } const done = (r: { ok: boolean; message?: string; changed?: number; ops?: number; dropped?: PatchDropped }, canvas?: AppliedCanvas): ApplyOutcome => (r.ok ? { ...r, adjustments, notChecked, canvas: canvas ?? liveCanvas(), ...(checks.length ? { checks } : {}), ...(imageNotes.length ? { imageNotes } : {}) } : r); const liveCanvas = (): AppliedCanvas => { try { return { settled: true, expected: canvasFingerprint(query.serialize()) }; } catch { return { settled: true, expected: null }; } }; /** Wait for the deferred page load, then report what the canvas must show: the applied tree. */ const loadedCanvas = async (tree: SerializedTreeNode): Promise => { const settled = await settleWithin(pages.whenCanvasSettled(), SETTLE_BOUND_MS); let expected: CanvasFingerprint | null = null; try { expected = canvasFingerprint(treeToCraftState(tree)); } catch { /* null: unverifiable */ } return { settled, expected }; }; if (resp.type === 'replace') { if (resp.scope === 'site') { const sitePages = resp.pages.map((p) => ({ name: p.name, tree: p.tree })); if (!(opts.addPages ? pages.addAiPages(sitePages) : pages.replaceAllPages(sitePages))) { return { ok: false, message: pages.isEditingGlobal ? 'You are editing a global section. Click Done, then ask again to replace the site.' : 'Nothing to apply.', }; } if (resp.header) pages.setHeader(resp.header.tree); if (resp.footer) pages.setFooter(resp.footer.tree); return done({ ok: true }, await loadedCanvas(resp.pages[0].tree)); } if (resp.scope === 'page') { if (!pages.replaceCurrentPage(resp.pages[0])) { return { ok: false, message: 'You are editing a global section. Click Done, then ask again to replace the page.', }; } // Only present when the owner agreed to swap the starter header/footer (sitesmith/replace-plan.ts). if (resp.header) pages.setHeader(resp.header.tree); if (resp.footer) pages.setFooter(resp.footer.tree); return done({ ok: true }, await loadedCanvas(resp.pages[0].tree)); } if (resp.scope === 'section') { // When targeted at a specific node, the AI's tree replaces that node // in place (vs appending a fresh section at the end of ROOT). // #57: a target inside a global-section instance can't be restructured // (the next master sync would wipe it) -> append as a new section instead. if (targetNodeId && resp.pages.length > 0 && !targetInInstance(query, targetNodeId)) { try { const nodeTree = buildNodeTree(query, resp.pages[0].tree); const parent: string = query.node(targetNodeId).get().data.parent ?? 'ROOT'; const siblings: string[] = query.node(parent).childNodes(); const index = siblings.indexOf(targetNodeId); actions.delete(targetNodeId); actions.addNodeTree(nodeTree, parent, index); return done({ ok: true }); } catch (e) { console.warn('sitesmith: targeted section replace failed, falling back to append', e); } } // Insert each provided tree as a new node tree appended to ROOT for (const p of resp.pages) { try { const nodeTree = buildNodeTree(query, p.tree); actions.addNodeTree(nodeTree, 'ROOT'); } catch (e) { console.warn('sitesmith: failed to add section tree', e); } } return done({ ok: true }); } } if (resp.type === 'patch') { return done(applyPatch(actions, query, resp.ops)); } return { ok: false, message: 'Unknown response type' }; }; } function targetInInstance(query: any, nodeId: string): boolean { try { return isInsideInstance(query, query.node(nodeId).get()?.data?.parent); } catch { return false; } } function applyPatch( actions: any, query: any, ops: SitesmithPatchOp[], ): { ok: boolean; message?: string; changed: number; ops: number; dropped?: PatchDropped } { let changed = 0; const dropped: PatchDropped = {}; const drop = (why: keyof PatchDropped) => { dropped[why] = (dropped[why] ?? 0) + 1; }; for (const op of ops) { const id = findNodeIdByAiNodeId(query, op.node_id); if (!id) { console.warn('sitesmith patch: node_id not found, skipping op:', op.node_id, op.op); drop('unknown_id'); continue; } switch (op.op) { case 'update_props': { const patchProps = op.props; if (!patchProps || typeof patchProps !== 'object' || Array.isArray(patchProps)) { console.warn('sitesmith patch: update_props with invalid props payload, skipping', op.node_id); drop('no_allowed_props'); break; } // round 6: an op with nothing left to set (the cleaner emptied it) changes nothing: not a "change" const settable = Object.entries(patchProps).filter(([k, v]) => !PROTECTED_UPDATE_PROPS_KEYS.has(k) && !(k === 'style' && (!v || typeof v !== 'object' || Array.isArray(v)))); if (settable.length === 0) { drop('no_allowed_props'); break; } changed++; actions.setProp(id, (p: any) => { for (const [key, value] of Object.entries(patchProps)) { if (PROTECTED_UPDATE_PROPS_KEYS.has(key)) { console.warn(`sitesmith patch: refusing to overwrite protected prop "${key}"`); continue; } // Merge `style` shallowly instead of blindly replacing it — the // AI usually only means to change one or two style keys, and a // blind Object.assign would clobber every other style the user // (or a previous AI turn) had already set. if (key === 'style') { if (value && typeof value === 'object' && !Array.isArray(value)) { const existingStyle = p.style && typeof p.style === 'object' ? p.style : {}; p.style = { ...existingStyle, ...(value as Record) }; } else { // `style: null` (or any other non-object) is not a valid // style patch — ignore it rather than clobbering the whole // style object with null/undefined/a stray primitive. console.warn('sitesmith patch: update_props ignoring non-object "style" value', value); } } else { p[key] = value; } } }); break; } case 'replace_node': { try { const parent: string = query.node(id).get().data.parent ?? 'ROOT'; if (isInsideInstance(query, parent)) { console.warn('sitesmith patch: replace_node inside a global section instance, skipping', op.node_id); break; } const nodeTree = buildNodeTree(query, op.tree); const siblings: string[] = query.node(parent).childNodes(); const index = siblings.indexOf(id); actions.delete(id); actions.addNodeTree(nodeTree, parent, index); changed++; } catch (e) { console.warn('sitesmith patch: replace_node failed', e); } break; } case 'insert_after': case 'insert_before': { try { const parent0: string = query.node(id).get().data.parent ?? 'ROOT'; const siblings: string[] = query.node(parent0).childNodes(); const index = siblings.indexOf(id); // #57: next to a node inside an instance -> next to the instance. const at = insertTargetOutsideInstance(query, parent0, op.op === 'insert_after' ? index + 1 : index); if (!at) break; const nodeTree = buildNodeTree(query, op.tree); if (at.index !== undefined) actions.addNodeTree(nodeTree, at.parentId, at.index); else actions.addNodeTree(nodeTree, at.parentId); changed++; } catch (e) { console.warn(`sitesmith patch: ${op.op} failed`, e); } break; } case 'delete_node': try { actions.delete(id); changed++; } catch (e) { console.warn('sitesmith patch: delete_node failed', e); } break; default: // Every SitesmithPatchOp variant is handled above, so `op` is typed // `never` here at compile time — but the AI response is untrusted // JSON (see useSitesmith.ts's `j: SendResult = await r.json()`), so // a malformed/unrecognized `op` field can still reach this branch at // runtime. Log the raw value rather than assuming a shape. console.warn('sitesmith patch: unknown op', op); } } const out = { ok: true, changed, ops: Array.isArray(ops) ? ops.length : 0 }; if (Object.keys(dropped).length) { console.info('[sitesmith] patch ops did nothing', dropped); return { ...out, dropped }; } return out; }