From e7cc48897c816a44480021b6436100ae3a6fa0c9 Mon Sep 17 00:00:00 2001 From: Suraj Air Date: Thu, 26 Nov 2026 16:44:44 +0530 Subject: [PATCH] chore(sync): pro@caffb5c MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sync src/ from chaibuilder/pro (sync_with_core) into chaibuilder/core. Source commits since last sync (.sync-ref was pro@a4127ad): caffb5c71 test: gate optional AI tool expectations on registered actions bd43dea82 fix(chai): share DB singleton on globalThis and surface site-domain failure cause 532323538 fix(chai): pick one variant per section for custom and library blocks 124a0dc9d fix(chai): add AI panel i18n keys to en/es bundles 0f3131905 Merge remote-tracking branch 'origin/develop' into sync_builder_ai_mcp 605e42632 feat(chai): add JSON-first read_blocks and update_block_props across Builder AI & M… a4df38ec7 fix(i18n): add missing replace block keys to es.json 36dbbf79d feat(chai): populate es.json bundle and enforce locale parity (#671) 349780397 fix(i18n): localize non-English revision dates fddbfa537 feat(i18n): convert plurals to _one/_other and localize formatting (#670) 232030916 feat(i18n): wrap untranslated strings in chai plugins (#669) ab2cedeb0 feat(i18n): wrap untranslated strings in pages builder (#668) 31a5ea858 feat(i18n): wrap untranslated strings in core components (#668) 9fb49b5d8 feat(i18n): wrap untranslated strings in rjsf-widgets (#668) 5d4c26511 feat(i18n): wrap design-tokens, hooks, and ui sr-only strings (#668) 228b9c37e feat(i18n): translate block names, settings labels, and variants (#667) 690c65501 fix(i18n): add Show more key to en.json 7926226d2 feat(chai): prefer custom and library blocks before hand-authored HTML in AI & MCP f0b576aec feat(i18n): backfill chai en.json and add key coverage guard (#666) d9955e29e feat(i18n): add chai locale plumbing (#665) 0a88c8a19 fix(chai): keep server-only AI tool modules out of client editor bundle b2081846f feat(chai): require section layout design tokens in AI/MCP rules and design checks 79349c9c9 fix(chai): show all used-in pages at once with a count on Show more 4c2943259 fix(chai): use cn for delete dialog list classes d9f7393c2 fix(chai): cap used-in-pages list in delete Global Block dialog c1b0c3971 refactor(chai): keep theme and design-token edits MCP-only 052f1e758 fix(chai): address PR #899 review findings across Builder AI & MCP da2fdfa40 Merge remote-tracking branch 'origin/develop' into sync_builder_ai_mcp 42a4b0560 feat(chai): sync Builder AI with MCP single-page capabilities & add CI drift guard 0ca7b35cf fix(chai): keep search focus when a block menu opens the add-blocks dialog (+36 more) Files: 158 updated, 20 added, 0 deleted + src/builder/core/components/chaibuilder-editor-locale.test.tsx + src/builder/core/components/settings/json-form.test.ts + src/builder/core/locales/es.json + src/builder/core/locales/locales.test.ts + src/server/chai-actions/ai/ask-ai/ai-edit-block-action.test.ts + src/server/chai-actions/ai/design/compose-design-brief.ts + src/server/chai-actions/ai/design/feature.ts + src/server/chai-actions/ai/design/guides/index.ts + src/server/chai-actions/ai/design/guides/refine.ts + src/server/chai-actions/ai/design/guides/setup.ts + src/server/chai-actions/ai/design/rules-in-force.ts + src/server/chai-actions/ai/page-tool-operations.ts + src/server/chai-actions/ai/remote-image-constants.ts + src/server/chai-actions/ai/remote-image.ts + src/server/chai-actions/ai/shared-instructions.ts + src/utils/design-checks/evaluate-write-checks.ts + src/utils/page-lang.ts + src/utils/page-seo.ts + src/utils/page-translations.ts + src/utils/page-type-helpers.ts ~ src/builder/core/components/canvas/dnd/drag-and-drop/hooks/use-block-drop.ts ~ src/builder/core/components/canvas/static/bubble-menu.tsx ~ src/builder/core/components/canvas/static/error-fallback.tsx ~ src/builder/core/components/canvas/static/new-blocks-renderer.tsx ~ src/builder/core/components/canvas/topbar/page-validation.tsx ~ src/builder/core/components/canvas/topbar/validation-errors-modal.tsx ~ src/builder/core/components/chaibuilder-editor.tsx ~ src/builder/core/components/layout/add-blocks-dialog.tsx ~ src/builder/core/components/layout/root-layout.tsx ~ src/builder/core/components/settings/block-settings.tsx ~ src/builder/core/components/settings/choices/advance-choices.tsx ~ src/builder/core/components/settings/choices/block-style.tsx ~ src/builder/core/components/settings/choices/dropdown-choices.tsx ~ src/builder/core/components/settings/common-settings.tsx ~ src/builder/core/components/settings/get-block-heading.ts ~ src/builder/core/components/settings/json-form.tsx ~ src/builder/core/components/settings/new-panel/breakpoint-selector.tsx ~ src/builder/core/components/sidepanels/panels/add-blocks/core-block.tsx ~ src/builder/core/components/sidepanels/panels/add-blocks/default-blocks.tsx ~ src/builder/core/components/sidepanels/panels/add-blocks/global-search-results.tsx (+138 more, see the diff) Sync-Direction: pro->core Sync-Source: chaibuilder/pro@caffb5c71cef15f8d88ff077343079cca754c220 Sync-Previous: chaibuilder/pro@a4127ad93f51d4f04e4945a035f5845739418ca3 Sync-Manifest: sha256:6b1d0d837b32cedcde28c404d3a67a82b9408c8aab4cc914bdbdf7a77be931b1 --- .sync-ref | 2 +- .../dnd/drag-and-drop/hooks/use-block-drop.ts | 4 +- .../components/canvas/static/bubble-menu.tsx | 24 +- .../canvas/static/error-fallback.tsx | 5 +- .../canvas/static/new-blocks-renderer.tsx | 13 +- .../canvas/topbar/page-validation.tsx | 12 +- .../canvas/topbar/validation-errors-modal.tsx | 28 +- .../chaibuilder-editor-locale.test.tsx | 86 + .../core/components/chaibuilder-editor.tsx | 22 +- .../components/layout/add-blocks-dialog.tsx | 45 +- .../core/components/layout/root-layout.tsx | 10 +- .../components/settings/block-settings.tsx | 4 +- .../settings/choices/advance-choices.tsx | 4 +- .../settings/choices/block-style.tsx | 8 +- .../settings/choices/dropdown-choices.tsx | 4 +- .../components/settings/common-settings.tsx | 6 +- .../components/settings/get-block-heading.ts | 5 +- .../components/settings/json-form.test.ts | 80 + .../core/components/settings/json-form.tsx | 123 +- .../new-panel/breakpoint-selector.tsx | 2 +- .../panels/add-blocks/core-block.tsx | 8 +- .../panels/add-blocks/default-blocks.tsx | 6 +- .../add-blocks/global-search-results.tsx | 12 +- .../panels/add-blocks/import-html.tsx | 5 +- .../add-blocks/libraries-panel.test.tsx | 16 +- .../panels/add-blocks/libraries-panel.tsx | 34 +- .../panels/add-blocks/partial-block-card.tsx | 3 +- .../panels/add-blocks/partial-blocks.tsx | 2 +- .../panels/images/media-manager-modal.tsx | 4 +- .../panels/outline/block-more-options.tsx | 27 +- .../sidepanels/panels/outline/list-tree.tsx | 4 +- .../sidepanels/panels/outline/node.tsx | 35 +- .../panels/outline/paste-into-root.tsx | 2 +- .../theme-configuration/css-import-modal.tsx | 2 +- .../design-tokens/token-list-components.tsx | 6 +- src/builder/core/functions/block-helpers.ts | 74 + src/builder/core/locales/en.json | 1429 +++++++++++- src/builder/core/locales/es.json | 2014 +++++++++++++++++ src/builder/core/locales/load.ts | 22 + src/builder/core/locales/locales.test.ts | 214 ++ src/builder/core/rjsf-widgets/Icon.tsx | 4 +- src/builder/core/rjsf-widgets/IconPicker.tsx | 8 +- .../binding-pipeline-editor.tsx | 26 +- src/builder/core/rjsf-widgets/binding.tsx | 5 +- src/builder/core/rjsf-widgets/code-widget.tsx | 2 +- .../core/rjsf-widgets/collection-select.tsx | 4 +- .../grouped-object-field-template.tsx | 12 +- src/builder/core/rjsf-widgets/image.tsx | 2 +- .../rjsf-widgets/json-form-field-template.tsx | 6 +- .../core/rjsf-widgets/repeater-binding.tsx | 6 +- .../repeater-data/filters-field.tsx | 32 +- .../rjsf-widgets/repeater-data/sort-field.tsx | 10 +- src/builder/core/rjsf-widgets/row-col.tsx | 4 +- .../rte-widget/rte-color-picker.tsx | 12 +- .../rjsf-widgets/rte-widget/rte-menu-bar.tsx | 30 +- .../rte-widget/rte-widget-modal.tsx | 8 +- .../rjsf-widgets/rte-widget/rte-widget.tsx | 6 +- src/builder/core/rjsf-widgets/slider.tsx | 12 +- src/builder/core/rjsf-widgets/sources.tsx | 14 +- .../core/rjsf-widgets/variant-select.tsx | 35 +- src/builder/core/rjsf-widgets/video.tsx | 2 +- src/builder/core/screen-too-small.tsx | 9 +- src/builder/dam/default-media-manager.tsx | 21 +- .../hooks/__tests__/structure-rules.test.ts | 6 +- .../__tests__/use-blocks-html-for-ai.test.ts | 53 + .../hooks/history/use-blocks-store-manager.ts | 1 + .../partial-blocks/use-partial-blocks-list.ts | 6 +- .../use-watch-partial-blocks.ts | 8 +- src/builder/hooks/structure-rules.ts | 44 +- src/builder/hooks/use-add-block.ts | 47 +- src/builder/hooks/use-add-custom-block.ts | 12 +- src/builder/hooks/use-blocks-html-for-ai.ts | 23 +- src/builder/hooks/use-check-structure.tsx | 59 +- src/builder/hooks/use-copy-blockIds.ts | 12 +- .../hooks/use-library-chai-blocks.test.ts | 16 + src/builder/hooks/use-library-chai-blocks.ts | 17 +- src/builder/hooks/use-paste-blocks.ts | 24 +- src/builder/pages/chaibuilder-pages.tsx | 41 +- .../pages/client/components/delete-page.tsx | 33 +- .../components/dynamic-page-selector.tsx | 17 +- .../client/components/dynamic-slug-input.tsx | 6 +- .../client/components/edit-url-panel.tsx | 10 +- .../client/components/json-diff-viewer.tsx | 19 +- .../client/components/key-value-editor.tsx | 8 +- .../components/page-action-dropdown.tsx | 4 +- .../pages/client/components/page-creator.tsx | 98 +- .../components/page-manager/page-item.tsx | 28 +- .../page-manager/page-link-context-menu.tsx | 4 +- .../components/parent-page-selector.tsx | 4 +- .../translation-warning-modal.tsx | 16 +- .../client/components/screen-overlay.tsx | 44 +- .../components/seo-language-switch-dialog.tsx | 19 +- .../pages/client/components/seo-panel.tsx | 8 +- .../pages/client/components/slug-input.tsx | 8 +- .../client/components/smart-json-input.tsx | 16 +- .../client/components/template-selection.tsx | 16 +- .../pages/client/components/topbar-right.tsx | 11 +- .../client/components/upstream-page-menu.tsx | 3 +- .../pages/client/components/web-preview.tsx | 4 +- .../client/realtime/ai-page-edit-time.ts | 11 +- .../pages/components/ai-elements/message.tsx | 21 +- .../components/ai-elements/prompt-input.tsx | 49 +- .../components/ai-elements/reasoning.tsx | 12 +- src/builder/pages/components/ui/dialog.tsx | 3 +- .../pages/digital-asset-manager/mutations.ts | 31 +- .../digital-asset-manager/pagination.tsx | 10 +- .../single-asset-detail.tsx | 10 +- .../use-download-image.ts | 4 +- src/builder/pages/hooks/ai/use-ai-context.ts | 57 +- src/builder/pages/hooks/pages/mutations.ts | 47 +- .../pages/hooks/pages/use-duplicate-page.ts | 8 +- src/builder/pages/hooks/project/mutations.ts | 4 +- .../project/use-templates-with-libraries.ts | 7 +- .../pages/hooks/user/use-check-access.ts | 6 +- .../panels/ai-panel/ai-context-modal.tsx | 21 +- .../panels/ai-panel/ai-panel-content.tsx | 47 +- .../panels/ai-panel/ai-panel-default-lang.tsx | 10 +- .../panels/ai-panel/ai-panel-page-chat.tsx | 63 +- .../pages/panels/ai-panel/ai-prompt-input.tsx | 2 +- .../panels/ai-panel/context-display-bar.tsx | 2 +- .../ai-panel/model-selector-dropdown.tsx | 8 +- .../panels/ai-panel/section-progress.tsx | 10 +- .../ai-panel/selected-block-display.tsx | 2 +- .../pages/panels/ai-panel/tool-part-card.tsx | 47 +- .../panels/ai-panel/use-ai-page-chat.test.tsx | 424 +++- .../pages/panels/ai-panel/use-ai-page-chat.ts | 735 ++++-- src/builder/pages/utils/image-compression.ts | 9 +- src/builder/pages/utils/page-organization.ts | 1 + src/components/ui/dialog.tsx | 40 +- src/components/ui/sheet.tsx | 28 +- src/constants/AI_TOOL_HISTORY.ts | 16 + src/db/core.ts | 76 +- .../page-errors/client/page-errors-panel.tsx | 163 +- src/registry/v2/__tests__/index.test.ts | 29 +- src/registry/v2/runtime/core.tsx | 17 +- src/server/build-config.test.ts | 19 + .../ai/ask-ai/ai-edit-block-action.test.ts | 88 + .../ai/ask-ai/ai-edit-block-action.ts | 114 +- .../ai/ask-ai/ai-edit-executors.test.ts | 245 +- .../ai/ask-ai/ai-edit-executors.ts | 242 +- .../ai/ask-ai/ai-edit-page-action.test.ts | 198 +- .../ai/ask-ai/ai-edit-page-action.ts | 196 +- .../ai-edit-page-prompt-context.test.ts | 37 +- .../ai/ask-ai/ai-edit-page-prompt-context.ts | 87 +- .../ai/ask-ai/ai-edit-page-tools.test.ts | 267 ++- .../ai/ask-ai/ai-edit-page-tools.ts | 1060 +++++++-- .../ai/ask-ai/ai-edit-tool-contract.ts | 357 ++- .../ai/design/compose-design-brief.ts | 214 ++ src/server/chai-actions/ai/design/feature.ts | 30 + .../chai-actions/ai/design/guides/index.ts | 43 + .../chai-actions/ai/design/guides/refine.ts | 97 + .../chai-actions/ai/design/guides/setup.ts | 33 + .../chai-actions/ai/design/rules-in-force.ts | 44 + .../chai-actions/ai/page-tool-operations.ts | 539 +++++ .../chai-actions/ai/remote-image-constants.ts | 12 + src/server/chai-actions/ai/remote-image.ts | 591 +++++ .../chai-actions/ai/shared-instructions.ts | 77 + .../chai-actions/base-ai-action.test.ts | 6 +- .../edit-page-tools-system-prompt.ts | 447 ++-- .../chai-actions/pages/get-website-pages.ts | 18 +- .../chai-actions/pages/upstream-pages.ts | 9 + .../chai-actions/website/theme-patch.ts | 10 +- .../chai-builder/public/get-site-domains.ts | 10 +- src/types/blocks.ts | 5 + src/types/chaibuilder-config.ts | 5 + src/types/chaibuilder-editor-props.ts | 22 + src/types/common.ts | 1 + src/utils/blocks-tree-ops.ts | 43 +- .../design-checks/evaluate-write-checks.ts | 89 + src/utils/design-checks/index.ts | 5 + src/utils/design-checks/rules/structure.ts | 53 +- .../design-checks/run-design-checks.test.ts | 48 +- .../import-html/restore-block-prop-types.ts | 24 +- src/utils/page-lang.ts | 56 + src/utils/page-seo.ts | 315 +++ src/utils/page-translations.ts | 405 ++++ src/utils/page-type-helpers.ts | 64 + src/web-blocks/helper.test.ts | 102 +- src/web-blocks/helper.ts | 39 +- 179 files changed, 12146 insertions(+), 1671 deletions(-) create mode 100644 src/builder/core/components/chaibuilder-editor-locale.test.tsx create mode 100644 src/builder/core/components/settings/json-form.test.ts create mode 100644 src/builder/core/locales/es.json create mode 100644 src/builder/core/locales/locales.test.ts create mode 100644 src/server/chai-actions/ai/ask-ai/ai-edit-block-action.test.ts create mode 100644 src/server/chai-actions/ai/design/compose-design-brief.ts create mode 100644 src/server/chai-actions/ai/design/feature.ts create mode 100644 src/server/chai-actions/ai/design/guides/index.ts create mode 100644 src/server/chai-actions/ai/design/guides/refine.ts create mode 100644 src/server/chai-actions/ai/design/guides/setup.ts create mode 100644 src/server/chai-actions/ai/design/rules-in-force.ts create mode 100644 src/server/chai-actions/ai/page-tool-operations.ts create mode 100644 src/server/chai-actions/ai/remote-image-constants.ts create mode 100644 src/server/chai-actions/ai/remote-image.ts create mode 100644 src/server/chai-actions/ai/shared-instructions.ts create mode 100644 src/utils/design-checks/evaluate-write-checks.ts create mode 100644 src/utils/page-lang.ts create mode 100644 src/utils/page-seo.ts create mode 100644 src/utils/page-translations.ts create mode 100644 src/utils/page-type-helpers.ts diff --git a/.sync-ref b/.sync-ref index b8109c147..2a3c8d60f 100644 --- a/.sync-ref +++ b/.sync-ref @@ -1 +1 @@ -chaibuilder/pro@a4127ad93f51d4f04e4945a035f5845739418ca3 +chaibuilder/pro@caffb5c71cef15f8d88ff077343079cca754c220 diff --git a/src/builder/core/components/canvas/dnd/drag-and-drop/hooks/use-block-drop.ts b/src/builder/core/components/canvas/dnd/drag-and-drop/hooks/use-block-drop.ts index cac266cba..04fa9efcf 100644 --- a/src/builder/core/components/canvas/dnd/drag-and-drop/hooks/use-block-drop.ts +++ b/src/builder/core/components/canvas/dnd/drag-and-drop/hooks/use-block-drop.ts @@ -13,6 +13,7 @@ import { useAtom, useSetAtom } from "jotai"; import { filter, find, get, has, isEmpty, isFunction } from "lodash-es"; import { DragEvent, useCallback } from "react"; +import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { canvasRenderKeyAtom, @@ -63,6 +64,7 @@ import { ChaiBlock } from "~/types/common"; *
*/ export const useBlockDrop = () => { + const { t } = useTranslation(); const [draggedBlock, setDraggedBlock] = useAtom(dragAndDropAtom); const setDropIndicator = useSetAtom(dropIndicatorAtom); const [iframe] = useCanvasIframe(); @@ -211,7 +213,7 @@ export const useBlockDrop = () => { const partialBlockId = dropBlock.partialBlockId || ""; const { canAdd, reason } = checkPartialCanAdd(partialBlockId); if (!canAdd) { - toast.error(reason || `Cannot add this ${singular}`); + toast.error(reason || t("Cannot add this {{name}}", { name: singular })); return; } addCoreBlock( diff --git a/src/builder/core/components/canvas/static/bubble-menu.tsx b/src/builder/core/components/canvas/static/bubble-menu.tsx index a3d972ea3..45db7c24f 100644 --- a/src/builder/core/components/canvas/static/bubble-menu.tsx +++ b/src/builder/core/components/canvas/static/bubble-menu.tsx @@ -13,6 +13,7 @@ import { UnderlineIcon, } from "@radix-ui/react-icons"; import { Editor } from "@tiptap/react"; +import { useTranslation } from "react-i18next"; import { cn } from "~/lib/utils"; const BUBBLE_MENU_ICONS = { @@ -59,10 +60,11 @@ interface BubbleMenuProps { } export const BubbleMenu = ({ editor }: BubbleMenuProps) => { + const { t } = useTranslation(); if (!editor) return null; const addLink = () => { - const url = window.prompt("Enter URL"); + const url = window.prompt(t("Enter URL")); if (url) { editor.chain().focus().setLink({ href: url }).run(); } @@ -73,32 +75,32 @@ export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
editor.chain().focus().toggleBold().run()} isActive={editor.isActive("bold")} /> editor.chain().focus().toggleItalic().run()} isActive={editor.isActive("italic")} /> editor.chain().focus().toggleUnderline().run()} isActive={editor.isActive("underline")} /> editor.chain().focus().toggleStrike().run()} isActive={editor.isActive("strike")} />
{ if (editor.isActive("link")) { editor.chain().focus().unsetLink().run(); @@ -111,32 +113,32 @@ export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
editor.chain().focus().toggleBulletList().run()} isActive={editor.isActive("bulletList")} /> editor.chain().focus().toggleOrderedList().run()} isActive={editor.isActive("orderedList")} />
editor.chain().focus().setTextAlign("left").run()} isActive={editor.isActive({ textAlign: "left" })} /> editor.chain().focus().setTextAlign("center").run()} isActive={editor.isActive({ textAlign: "center" })} /> editor.chain().focus().setTextAlign("right").run()} isActive={editor.isActive({ textAlign: "right" })} /> diff --git a/src/builder/core/components/canvas/static/error-fallback.tsx b/src/builder/core/components/canvas/static/error-fallback.tsx index 62d0504bf..804d65239 100644 --- a/src/builder/core/components/canvas/static/error-fallback.tsx +++ b/src/builder/core/components/canvas/static/error-fallback.tsx @@ -1,7 +1,10 @@ +import { useTranslation } from "react-i18next"; + export const ErrorFallback = () => { + const { t } = useTranslation(); return (
- Something went wrong. + {t("Something went wrong.")}
); }; diff --git a/src/builder/core/components/canvas/static/new-blocks-renderer.tsx b/src/builder/core/components/canvas/static/new-blocks-renderer.tsx index a4ec088c0..5145c5059 100644 --- a/src/builder/core/components/canvas/static/new-blocks-renderer.tsx +++ b/src/builder/core/components/canvas/static/new-blocks-renderer.tsx @@ -341,11 +341,14 @@ const ChaiSlotPlaceholder = ({ name }: { name: string }) => { ); }; -const PartialDepthExceededPlaceholder = () => ( -
-

Maximum partial nesting depth ({MAX_PARTIAL_DEPTH} levels) exceeded

-
-); +const PartialDepthExceededPlaceholder = () => { + const { t } = useTranslation(); + return ( +
+

{t("Maximum partial nesting depth ({{depth}} levels) exceeded", { depth: MAX_PARTIAL_DEPTH })}

+
+ ); +}; const PartialBlocksRenderer = ({ partialBlockId }: { partialBlockId: string }) => { const { getPartialBlocks } = usePartialBlocksStore(); diff --git a/src/builder/core/components/canvas/topbar/page-validation.tsx b/src/builder/core/components/canvas/topbar/page-validation.tsx index 93d80f3de..0b8383b91 100644 --- a/src/builder/core/components/canvas/topbar/page-validation.tsx +++ b/src/builder/core/components/canvas/topbar/page-validation.tsx @@ -27,13 +27,13 @@ export const PageValidation = () => { const getMessage = () => { if (hasErrors && hasWarnings) { - return `${errorCount} error${errorCount > 1 ? "s" : ""}, ${warningCount} warning${warningCount > 1 ? "s" : ""}`; + return `${t("{{count}} errors", { count: errorCount })}, ${t("{{count}} warnings", { count: warningCount })}`; } if (hasErrors) { - return `${errorCount} error${errorCount > 1 ? "s" : ""}`; + return t("{{count}} errors", { count: errorCount }); } if (hasWarnings) { - return `${warningCount} warning${warningCount > 1 ? "s" : ""}`; + return t("{{count}} warnings", { count: warningCount }); } return ""; }; @@ -67,13 +67,15 @@ export const PageValidation = () => { ? "border border-red-200 bg-red-50 text-red-700" : "border border-orange-200 bg-orange-50 text-orange-700" }`}> -
{error.severity === "error" ? "Error:" : "Warning:"}
+
{error.severity === "error" ? t("Error:") : t("Warning:")}
{error.message}
))} {errors.length > 5 && ( -

... and {errors.length - 5} more issues

+

+ {t("... and {{count}} more issues", { count: errors.length - 5 })} +

)}
)} diff --git a/src/builder/core/components/canvas/topbar/validation-errors-modal.tsx b/src/builder/core/components/canvas/topbar/validation-errors-modal.tsx index 47812c9e7..d3dd69dff 100644 --- a/src/builder/core/components/canvas/topbar/validation-errors-modal.tsx +++ b/src/builder/core/components/canvas/topbar/validation-errors-modal.tsx @@ -28,6 +28,7 @@ export const ValidationErrorsModal = ({ errors, actionLabel, showSnooze = false, + blocked = false, }: { isOpen: boolean; onClose: () => void; @@ -36,6 +37,8 @@ export const ValidationErrorsModal = ({ errors: StructureError[]; actionLabel: string; showSnooze?: boolean; + /** Errors must be fixed first: hides the continue action and snooze. */ + blocked?: boolean; }) => { const { t } = useTranslation(); const [snoozeDays, setSnoozeDays] = useState(NO_SNOOZE); @@ -45,7 +48,7 @@ export const ValidationErrorsModal = ({ if (isOpen) setSnoozeDays(NO_SNOOZE); }, [isOpen]); const [, setSelectedBlockIds] = useSelectedBlockIds(); - const gotoPage = useBuilderProp("gotoPage", (_arg: { pageId: string; lang?: string }) => {}); + const gotoPage = useBuilderProp("gotoPage", (_arg: { pageId: string; lang?: string }) => { }); const { selectedLang, fallbackLang } = useLanguages(); const errorList = errors.filter((e) => e.severity === "error"); @@ -74,7 +77,9 @@ export const ValidationErrorsModal = ({ {t("Page Validation Issues")} - {t("The following issues were found on this page. You can fix them or continue anyway.")} + {blocked + ? t("The following issues were found on this page.") + : t("The following issues were found on this page. You can fix them or continue anyway.")} @@ -112,7 +117,9 @@ export const ValidationErrorsModal = ({
- {showSnooze ? ( + {blocked ? ( + {t("Resolve errors to publish the page.")} + ) : showSnooze ? (
{t("Do not show for")}
- + { - const type = block._type.split("/").pop() || block._type; + const rawType = block._type.split("/").pop() || block._type; + const type = rawType ? i18n.t(rawType) : rawType; const name = block._name || type; return name === type ? name : `${name} (${type})`; }; diff --git a/src/builder/core/components/settings/json-form.test.ts b/src/builder/core/components/settings/json-form.test.ts new file mode 100644 index 000000000..bafd6828f --- /dev/null +++ b/src/builder/core/components/settings/json-form.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from "vitest"; +import { translateSchema, translateUiSchema } from "./json-form"; + +describe("translateSchema and translateUiSchema", () => { + const dict: Record = { + Title: "Título", + "Heading text": "Texto del encabezado", + "Option A": "Opción A", + "Option B": "Opción B", + "Branch One": "Rama Uno", + "Any Option": "Cualquier Opción", + "Item Title": "Título del elemento", + "Enter title...": "Ingresa el título...", + "Helpful note": "Nota útil", + "UI Title": "Título UI", + }; + const t = (key: string) => dict[key] ?? key; + + it("translates title, description, enumNames, oneOf/anyOf titles, and nested properties while preserving group, subgroup, and enum values", () => { + const schema = { + type: "object", + title: "Title", + properties: { + heading: { + type: "string", + title: "Title", + description: "Heading text", + group: "Content", + subgroup: "Typography", + enum: ["a", "b"], + enumNames: ["Option A", "Option B"], + }, + items: { + type: "array", + items: { + type: "object", + properties: { + name: { type: "string", title: "Item Title" }, + }, + }, + }, + }, + oneOf: [{ title: "Branch One", properties: {} }], + anyOf: [{ title: "Any Option", properties: {} }], + }; + + const translated = translateSchema(schema, t); + + expect(translated.title).toBe("Título"); + expect(translated.properties.heading.title).toBe("Título"); + expect(translated.properties.heading.description).toBe("Texto del encabezado"); + expect(translated.properties.heading.enumNames).toEqual(["Opción A", "Opción B"]); + // Machine values and group collapse keys must remain untouched. + expect(translated.properties.heading.enum).toEqual(["a", "b"]); + expect(translated.properties.heading.group).toBe("Content"); + expect(translated.properties.heading.subgroup).toBe("Typography"); + expect(translated.properties.items.items.properties.name.title).toBe("Título del elemento"); + expect(translated.oneOf[0].title).toBe("Rama Uno"); + expect(translated.anyOf[0].title).toBe("Cualquier Opción"); + // Must not mutate input object. + expect(schema.title).toBe("Title"); + }); + + it("translates ui:placeholder, ui:help, and ui:title recursively", () => { + const uiSchema = { + heading: { + "ui:placeholder": "Enter title...", + "ui:help": "Helpful note", + "ui:title": "UI Title", + "ui:options": { rows: 3 }, + }, + }; + + const translated = translateUiSchema(uiSchema, t); + expect(translated.heading["ui:placeholder"]).toBe("Ingresa el título..."); + expect(translated.heading["ui:help"]).toBe("Nota útil"); + expect(translated.heading["ui:title"]).toBe("Título UI"); + expect(translated.heading["ui:options"]).toEqual({ rows: 3 }); + }); +}); diff --git a/src/builder/core/components/settings/json-form.tsx b/src/builder/core/components/settings/json-form.tsx index 78467c3ea..af728a728 100644 --- a/src/builder/core/components/settings/json-form.tsx +++ b/src/builder/core/components/settings/json-form.tsx @@ -3,8 +3,9 @@ import { useThrottledCallback } from "@react-hookz/web"; import RjForm from "@rjsf/core"; import { RJSFSchema, UiSchema } from "@rjsf/utils"; import validator from "@rjsf/validator-ajv8"; -import { get, set, take } from "lodash-es"; +import { get, isPlainObject, set, take } from "lodash-es"; import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; import { BindingInputWidget, BindingTextareaWidget } from "~/builder/core/rjsf-widgets/binding-editor/binding-editor-widget"; import { CodeEditor } from "~/builder/core/rjsf-widgets/code-widget"; import { CollectionFilterSortField } from "~/builder/core/rjsf-widgets/collection-select"; @@ -97,15 +98,107 @@ type JSONFormType = { onChange: ({ formData }: any, key?: string) => void; }; -const CustomAddButton = (props: any) => ( - -); +type TranslateFn = (key: string) => string; -const JSONFormContent = ({ formRef, blockId, blockType, formData, selectedLang, uiSchemaCopy, schemaCopy, onChange }: any) => { +const translateNonEmpty = (value: unknown, t: TranslateFn) => + typeof value === "string" && value.length > 0 ? t(value) : value; + +/** + * Returns a copy of `schema` with user-facing labels translated. + * `group` and `subgroup` are intentionally preserved untranslated because + * `GroupedObjectFieldTemplate` keys accordion collapse state on them. + */ +export const translateSchema = (schema: any, t: TranslateFn): any => { + if (Array.isArray(schema)) { + return schema.map((item) => translateSchema(item, t)); + } + if (!isPlainObject(schema)) { + return schema; + } + + const next: Record = { ...schema }; + if (typeof next.title === "string" && next.title.length > 0) { + next.title = t(next.title); + } + if (typeof next.description === "string" && next.description.length > 0) { + next.description = t(next.description); + } + if (Array.isArray(next.enumNames)) { + next.enumNames = next.enumNames.map((name: unknown) => translateNonEmpty(name, t)); + } + if (isPlainObject(next.properties)) { + const props: Record = {}; + for (const [k, v] of Object.entries(next.properties)) { + props[k] = translateSchema(v, t); + } + next.properties = props; + } + if (next.items !== undefined) { + next.items = translateSchema(next.items, t); + } + if (isPlainObject(next.additionalProperties)) { + next.additionalProperties = translateSchema(next.additionalProperties, t); + } + if (isPlainObject(next.dependencies)) { + const deps: Record = {}; + for (const [k, v] of Object.entries(next.dependencies)) { + deps[k] = translateSchema(v, t); + } + next.dependencies = deps; + } + for (const key of ["allOf", "oneOf", "anyOf"] as const) { + if (Array.isArray(next[key])) { + next[key] = next[key].map((item: unknown) => translateSchema(item, t)); + } + } + for (const key of ["if", "then", "else"] as const) { + if (isPlainObject(next[key])) { + next[key] = translateSchema(next[key], t); + } + } + return next; +}; + +/** Returns a copy of `uiSchema` with `ui:placeholder`, `ui:help`, and `ui:title` translated. */ +export const translateUiSchema = (uiSchema: any, t: TranslateFn): any => { + if (!isPlainObject(uiSchema)) { + return uiSchema; + } + const next: Record = {}; + for (const [k, v] of Object.entries(uiSchema)) { + if (k === "ui:placeholder" || k === "ui:help" || k === "ui:title") { + next[k] = translateNonEmpty(v, t); + } else if (isPlainObject(v) && !k.startsWith("ui:")) { + next[k] = translateUiSchema(v, t); + } else { + next[k] = v; + } + } + return next; +}; + +const CustomAddButton = (props: any) => { + const { t } = useTranslation(); + return ( + + ); +}; + +const JSONFormContent = ({ + formRef, + blockId, + blockType, + formData, + selectedLang, + language, + uiSchemaCopy, + schemaCopy, + onChange, +}: any) => { const { widgets, fields, templates } = useJsonFormElements(); const onFormDataChange = useCallback( @@ -125,7 +218,7 @@ const JSONFormContent = ({ formRef, blockId, blockType, formData, selectedLang, return ( { + const { t, i18n } = useTranslation(); const { selectedLang } = useLanguages(); const formDataRef = useRef(formData); const formRef = useRef(null); @@ -153,6 +247,8 @@ export const JSONForm = memo(({ blockId, blockType, schema, uiSchema, formData, const [_formData, setFormData] = useState(formData); const [isFocused, setIsFocused] = useState(false); const [{ schema: schemaCopy, uiSchema: uiSchemaCopy }] = useState({ schema, uiSchema }); + const translatedSchema = useMemo(() => translateSchema(schemaCopy, t), [schemaCopy, t, i18n.language]); + const translatedUiSchema = useMemo(() => translateUiSchema(uiSchemaCopy, t), [uiSchemaCopy, t, i18n.language]); useEffect(() => { const formElement = (formRef?.current as any)?.formElement?.current as HTMLFormElement; @@ -202,15 +298,16 @@ export const JSONForm = memo(({ blockId, blockType, schema, uiSchema, formData, formRef={formRef} formData={_formData} selectedLang={selectedLang} - uiSchemaCopy={uiSchemaCopy} - schemaCopy={schemaCopy} + language={i18n.language} + uiSchemaCopy={translatedUiSchema} + schemaCopy={translatedSchema} onChange={(data: any, id?: string) => { setFormData(data.formData); throttledChange(data, id); }} /> ), - [blockId, blockType, _formData, selectedLang, uiSchemaCopy, schemaCopy, throttledChange], + [blockId, blockType, _formData, selectedLang, i18n.language, translatedUiSchema, translatedSchema, throttledChange], ); return memoizedJSONFormContent; diff --git a/src/builder/core/components/settings/new-panel/breakpoint-selector.tsx b/src/builder/core/components/settings/new-panel/breakpoint-selector.tsx index c6d566cc9..4ec4dd9ec 100644 --- a/src/builder/core/components/settings/new-panel/breakpoint-selector.tsx +++ b/src/builder/core/components/settings/new-panel/breakpoint-selector.tsx @@ -22,7 +22,7 @@ export function BreakpointSelector() {

- {breakpoint === "xs" ? "Base" : breakpoint} + {breakpoint === "xs" ? t("Base") : breakpoint}   {t(message)} diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/core-block.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/core-block.tsx index 8327032f1..c64b5ca98 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/core-block.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/core-block.tsx @@ -26,13 +26,15 @@ export const CoreBlock = ({ const isDisabled = disabled || block.disabled; const { addCoreBlock, addPredefinedBlock } = useAddBlock(); const addBlockToPage = () => { + let added; if (has(block, "blocks")) { const blocks = isFunction(block.blocks) ? block.blocks() : block.blocks; - addPredefinedBlock(syncChaiBlocksWithDefaultProps(blocks), parentId || null, position); + added = addPredefinedBlock(syncChaiBlocksWithDefaultProps(blocks), parentId || null, position); } else { - addCoreBlock(block, parentId || null, position); + added = addCoreBlock(block, parentId || null, position); } - pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); + // A refused replace keeps the dialog open to pick another block. + if (added) pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); }; const isDragAndDropEnabled = useIsDragAndDropEnabled(); diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/default-blocks.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/default-blocks.tsx index ece250ac1..b10710253 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/default-blocks.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/default-blocks.tsx @@ -1,9 +1,10 @@ import { filter, groupBy, map, uniq } from "lodash-es"; import { ChaiBuilderBlocks } from "~/builder/core/components/sidepanels/panels/add-blocks/add-blocks"; -import { isBlockAvailableForPageType } from "~/builder/core/functions/block-helpers"; +import { isBlockAvailable } from "~/builder/core/functions/block-helpers"; import { useBuilderProp } from "~/builder/hooks/use-builder-prop"; import { usePrimaryPage } from "~/builder/pages/hooks/pages/use-current-page"; import { useRegisteredChaiBlocks } from "~/registry"; +import type { ChaiCanShowBlock } from "~/types/chaibuilder-editor-props"; export const DefaultChaiBlocks = ({ parentId, @@ -24,12 +25,13 @@ export const DefaultChaiBlocks = ({ const { data: currentPage } = usePrimaryPage(); const currentPageType = currentPage?.pageType || "page"; const layoutPagesEnabled = useBuilderProp("flags.layoutPages", false); + const canShowBlock = useBuilderProp("canShowBlock", undefined); const showPageSlot = layoutPagesEnabled && currentPageType === "_layout"; const groupedBlocks = groupBy(chaiBlocks, "category") as Record; const availableBlocks = filter( groupedBlocks.core, - (block) => !block.showInLibrary && isBlockAvailableForPageType(block, currentPageType), + (block) => !block.showInLibrary && isBlockAvailable(block, currentPageType, canShowBlock), ).map((block) => (block.type === "PageSlot" && showPageSlot ? { ...block, hidden: false } : block)); const uniqueTypeGroup = uniq(map(availableBlocks, "group")); diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/global-search-results.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/global-search-results.tsx index 21bad6ba7..c80f99501 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/global-search-results.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/global-search-results.tsx @@ -8,7 +8,7 @@ import { isRegisteredLibraryBlockDisabled, } from "~/builder/core/components/sidepanels/panels/add-blocks/libraries-panel"; import { PartialBlockCard } from "~/builder/core/components/sidepanels/panels/add-blocks/partial-block-card"; -import { canAcceptInto, canBeNestedInside, isBlockAvailableForPageType } from "~/builder/core/functions/block-helpers"; +import { canAcceptInto, canBeNestedInside, isBlockAvailable } from "~/builder/core/functions/block-helpers"; import { useBlocksStore } from "~/builder/hooks/history/use-blocks-store-undoable-actions"; import { libraryBlocksAtom, useLibraryBlocks } from "~/builder/hooks/use-library-blocks"; import { useBuilderProp } from "~/builder/hooks/use-builder-prop"; @@ -20,7 +20,7 @@ import { usePrimaryPage } from "~/builder/pages/hooks/pages/use-current-page"; import { useRegisteredChaiLibraries } from "~/builder/register-apis"; import { Label } from "~/components/ui/label"; import { useRegisteredChaiBlocks } from "~/registry"; -import type { ChaiLibrary } from "~/types/chaibuilder-editor-props"; +import type { ChaiCanShowBlock, ChaiLibrary } from "~/types/chaibuilder-editor-props"; import { matchesGlobalSearch } from "./global-search"; const LibraryLoader = ({ library }: { library: ChaiLibrary }) => { @@ -59,6 +59,7 @@ export const GlobalSearchResults = ({ const chaiBlocks = useRegisteredChaiBlocks(); const { data: currentPage } = usePrimaryPage(); const layoutPagesEnabled = useBuilderProp("flags.layoutPages", false); + const canShowBlock = useBuilderProp("canShowBlock", undefined); const dnd = useBuilderProp("flags.dragAndDrop", true); const [allBlocks] = useBlocksStore(); const parentType = allBlocks.find((block) => block._id === parentId)?._type; @@ -103,7 +104,7 @@ export const GlobalSearchResults = ({ const coreResults = useMemo( () => filter(chaiBlocks, { category: "core" }) - .filter((block) => isBlockAvailableForPageType(block, currentPageType)) + .filter((block) => isBlockAvailable(block, currentPageType, canShowBlock)) .map((block) => (block.type === "PageSlot" && showPageSlot ? { ...block, hidden: false } : block)) .filter( (block) => @@ -111,13 +112,14 @@ export const GlobalSearchResults = ({ !block.showInLibrary && matchesGlobalSearch(searchTerm, [block.label, block.type, block.group, block.category]), ), - [chaiBlocks, currentPageType, searchTerm, showPageSlot], + [canShowBlock, chaiBlocks, currentPageType, searchTerm, showPageSlot], ); const libraryResults = useMemo( () => [ ...libraries.flatMap((library) => (libraryBlocks[library.id]?.blocks || []) + .filter((block) => isBlockAvailable(block, currentPageType, canShowBlock)) .filter((block) => matchesGlobalSearch(searchTerm, [ block.name, @@ -133,7 +135,7 @@ export const GlobalSearchResults = ({ .filter((block) => matchesGlobalSearch(searchTerm, [block.label, block.type, block.description, block.group])) .map((block) => ({ key: `chai-block-${block.type}`, block: block as any, library: undefined })), ], - [libraries, libraryBlocks, libraryChaiBlocks, searchTerm], + [canShowBlock, currentPageType, libraries, libraryBlocks, libraryChaiBlocks, searchTerm], ); const coreByGroup = useMemo(() => groupBy(coreResults, "group"), [coreResults]); diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/import-html.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/import-html.tsx index 269152b2b..bd9832ed3 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/import-html.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/import-html.tsx @@ -28,9 +28,10 @@ const ImportHTML = ({ setLoading(true); const codeHtml = await runChaiPreImportHtmlHook(code); const blocks = await getBlocksFromHTML(codeHtml); - addPredefinedBlock([...blocks], parentId, position); - setCode(""); + const added = addPredefinedBlock([...blocks], parentId, position); setLoading(false); + if (!added) return; + setCode(""); pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); }; diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.test.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.test.tsx index bd8eeb135..5cb3cd4ba 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.test.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.test.tsx @@ -12,7 +12,7 @@ registerChaiLibrary("lib-a", { name: "Library A", description: "", getBlocksList: async () => [ - { id: "a1", name: "Hero A", group: "hero" }, + { id: "a1", name: "Hero A", group: "hero", metadata: { siteTypes: ["Agent"] } }, { id: "a2", name: "Footer A", group: "footer" }, ], getBlock, @@ -98,4 +98,18 @@ describe("UILibrariesPanel card insertion", () => { fireEvent.click(screen.getByRole("button", { name: "Add" })); await waitFor(() => expect(getBlock).toHaveBeenCalledTimes(1)); }); + + it("hides library blocks rejected by canShowBlock", async () => { + renderInBuilder(, { + builderProps: { + canShowBlock: (block: { metadata?: Record }) => { + const siteTypes = block.metadata?.siteTypes as string[] | undefined; + return !siteTypes || siteTypes.includes("Company"); + }, + }, + }); + await screen.findByText("Footer A"); + expect(screen.queryByText("Hero")).toBeNull(); + expect(screen.queryByText("Hero A")).toBeNull(); + }); }); diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.tsx index 539da2ecf..3ecd86ba7 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/libraries-panel.tsx @@ -10,7 +10,7 @@ import { useDragAndDrop, useIsDragAndDropEnabled } from "~/builder/core/componen import { dragAndDropAtom } from "~/builder/core/components/canvas/dnd/drag-and-drop/hooks/use-drag-and-drop"; import { ChaiImage } from "~/builder/core/components/shared"; import { CHAI_BUILDER_EVENTS } from "~/builder/core/events"; -import { canAcceptChildBlock, canBeNestedInside } from "~/builder/core/functions/block-helpers"; +import { canAcceptChildBlock, canBeNestedInside, isBlockAvailable } from "~/builder/core/functions/block-helpers"; import { pubsub } from "~/builder/core/pubsub"; import { useBlocksStore } from "~/builder/hooks/history/use-blocks-store-undoable-actions"; import { useAddBlock } from "~/builder/hooks/use-add-block"; @@ -18,6 +18,7 @@ import { useBuilderProp } from "~/builder/hooks/use-builder-prop"; import { useLibraryBlocks } from "~/builder/hooks/use-library-blocks"; import { useLibraryChaiBlocks } from "~/builder/hooks/use-library-chai-blocks"; import { useSelectedLibrary } from "~/builder/hooks/use-selected-library"; +import { usePrimaryPage } from "~/builder/pages/hooks/pages/use-current-page"; import { useRegisteredChaiLibraries } from "~/builder/register-apis"; import { Button } from "~/components/ui/button"; import { Label } from "~/components/ui/label"; @@ -26,7 +27,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~ import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip"; import { cn } from "~/lib/utils"; import { syncChaiBlocksWithDefaultProps } from "~/registry"; -import { ChaiLibrary, ChaiLibraryBlock } from "~/types/chaibuilder-editor-props"; +import { ChaiCanShowBlock, ChaiLibrary, ChaiLibraryBlock } from "~/types/chaibuilder-editor-props"; import { ChaiBlock } from "~/types/common"; import { getBlocksFromHTML } from "~/utils/import-html/html-to-json"; import { ChaiDraggableBlock } from "./draggable-block"; @@ -70,8 +71,10 @@ export const BlockCard = ({ const getUILibraryBlock = useMemo(() => library?.getBlock || (() => []), [library]); const { addCoreBlock, addPredefinedBlock } = useAddBlock(); const groupMaxDepth = useBuilderProp("libraryGroupMaxDepth", NO_GROUP_MAX_DEPTH); - const name = get(block, "name", get(block, "label")); - const description = get(block, "description", ""); + const rawName = get(block, "name", get(block, "label")); + const name = rawName ? t(rawName) : ""; + const rawDescription = get(block, "description", ""); + const description = rawDescription ? t(rawDescription) : ""; const { onDragStart, onDragEnd } = useDragAndDrop(); const isDragAndDropEnabled = useIsDragAndDropEnabled(); const setDraggedBlock = useSetAtom(dragAndDropAtom); @@ -81,13 +84,14 @@ export const BlockCard = ({ e.stopPropagation(); if (disabled) return; if (has(block, "component")) { + let added; if (has(block, "blocks")) { const blocks = isFunction(block.blocks) ? block.blocks() : block.blocks; - addPredefinedBlock(syncChaiBlocksWithDefaultProps(blocks), parentId, position); + added = addPredefinedBlock(syncChaiBlocksWithDefaultProps(blocks), parentId, position); } else { - addCoreBlock(block, parentId, position); + added = addCoreBlock(block, parentId, position); } - pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); + if (added) pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); return; } setIsAdding(true); @@ -98,11 +102,12 @@ export const BlockCard = ({ if (typeof uiBlocks === "string") { uiBlocks = await getBlocksFromHTML(uiBlocks); } - if (!isEmpty(uiBlocks)) + const added = + isEmpty(uiBlocks) || addPredefinedBlock(syncChaiBlocksWithDefaultProps(uiBlocks), parentId, position, { maxDepth: getLibraryBlockMaxDepth(block, groupMaxDepth), }); - pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); + if (added) pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); setTimeout(() => setIsAdding(false), 1000); }, [addCoreBlock, addPredefinedBlock, block, disabled, getUILibraryBlock, groupMaxDepth, library, parentId, position], @@ -155,7 +160,7 @@ export const BlockCard = ({ {isAdding && (

- Adding... + {t("Adding...")}
)} {block.preview ? ( @@ -202,7 +207,14 @@ const UILibrarySection = ({ const dnd = useBuilderProp("flags.dragAndDrop", true); const [allBlocks] = useBlocksStore(); const parentType = allBlocks.find((block) => block._id === parentId)?._type; - const libraryBlocks = useMemo(() => [...uiLibraryBlocks, ...libraryChaiBlocks], [uiLibraryBlocks, libraryChaiBlocks]); + const { data: currentPage } = usePrimaryPage(); + const canShowBlock = useBuilderProp("canShowBlock", undefined); + const pageType = currentPage?.pageType || "page"; + // A library block that names `pageTypes` or fails `canShowBlock` is hidden, matching the Blocks tab. + const libraryBlocks = useMemo( + () => [...uiLibraryBlocks.filter((block) => isBlockAvailable(block, pageType, canShowBlock)), ...libraryChaiBlocks], + [uiLibraryBlocks, libraryChaiBlocks, pageType, canShowBlock], + ); // Support a controlled search term (single search box shared across all // add-block tabs) and an internal one (when used standalone). const isSearchControlled = controlledSearchTerm !== undefined; diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/partial-block-card.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/partial-block-card.tsx index 5a713e56f..a0e78d806 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/partial-block-card.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/partial-block-card.tsx @@ -39,8 +39,7 @@ export const PartialBlockCard = ({ const addBlockToPage = () => { if (isDisabled) return; - addCoreBlock(block, parentId || null, position); - pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); + if (addCoreBlock(block, parentId || null, position)) pubsub.publish(CHAI_BUILDER_EVENTS.CLOSE_ADD_BLOCK); }; return ( diff --git a/src/builder/core/components/sidepanels/panels/add-blocks/partial-blocks.tsx b/src/builder/core/components/sidepanels/panels/add-blocks/partial-blocks.tsx index e5a71b90a..b37f04f3f 100644 --- a/src/builder/core/components/sidepanels/panels/add-blocks/partial-blocks.tsx +++ b/src/builder/core/components/sidepanels/panels/add-blocks/partial-blocks.tsx @@ -156,7 +156,7 @@ export const PartialBlocks = ({
); diff --git a/src/builder/core/components/sidepanels/panels/images/media-manager-modal.tsx b/src/builder/core/components/sidepanels/panels/images/media-manager-modal.tsx index 2ce865504..63f34da7a 100644 --- a/src/builder/core/components/sidepanels/panels/images/media-manager-modal.tsx +++ b/src/builder/core/components/sidepanels/panels/images/media-manager-modal.tsx @@ -1,4 +1,5 @@ import React, { useState } from "react"; +import { useTranslation } from "react-i18next"; import { DefaultMediaManager, type ChaiMediaManagerMode } from "~/builder/dam/default-media-manager"; import { ChaiSlot } from "~/builder/register-apis"; import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "~/components/ui/dialog"; @@ -23,6 +24,7 @@ const MediaManagerModal = ({ open: controlledOpen, onOpenChange, }: MediaManagerModalProps) => { + const { t } = useTranslation(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); const isControlled = controlledOpen !== undefined; const open = isControlled ? controlledOpen : uncontrolledOpen; @@ -41,7 +43,7 @@ const MediaManagerModal = ({ setOpen(_open)}> {children ? {children} : null} - Media Manager + {t("Media Manager")}
{ e.stopPropagation(); setSelectedIds([]); - pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, selectedBlock); + pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, { forceModal: true }); }}> {t("Add block")} @@ -346,10 +346,19 @@ const BlockContextMenuContent = ({ onClick={(e: React.MouseEvent) => { e.stopPropagation(); setSelectedIds([node.data._id]); - pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, node.data); + pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, { ...node.data, forceModal: true }); }}> {t("Add block")} + { + e.stopPropagation(); + pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, { replaceBlockId: node.data._id, forceModal: true }); + }}> + {t("Replace block")} + { + if (document.activeElement?.closest('[role="dialog"]')) event.preventDefault(); +}; + export const BlockMoreOptions = ({ children, id, @@ -382,14 +396,15 @@ export const BlockMoreOptions = ({ node: any; type?: "context" | "option"; }) => { + const { t } = useTranslation(); const [, setSelectedIds] = useSelectedBlockIds(); if (type === "context") { return ( {children} - - ACTIONS + + {t("ACTIONS")} @@ -404,7 +419,7 @@ export const BlockMoreOptions = ({ if (open) setSelectedIds([id]); }}> {children} - + diff --git a/src/builder/core/components/sidepanels/panels/outline/list-tree.tsx b/src/builder/core/components/sidepanels/panels/outline/list-tree.tsx index 395d0d84b..15c8578eb 100644 --- a/src/builder/core/components/sidepanels/panels/outline/list-tree.tsx +++ b/src/builder/core/components/sidepanels/panels/outline/list-tree.tsx @@ -604,7 +604,7 @@ const ListTree = () => {
{hasPermission(CHAI_PERMISSIONS["pages:update"]) && (
diff --git a/src/builder/core/components/sidepanels/panels/outline/node.tsx b/src/builder/core/components/sidepanels/panels/outline/node.tsx index 801699946..118ddfa12 100644 --- a/src/builder/core/components/sidepanels/panels/outline/node.tsx +++ b/src/builder/core/components/sidepanels/panels/outline/node.tsx @@ -6,6 +6,7 @@ import { memo, useCallback, useEffect, useMemo, useRef } from "react"; import { NodeRendererProps } from "react-arborist"; import { useTranslation } from "react-i18next"; import { canvasIframeAtom } from "~/builder/atoms/ui"; +import i18n from "~/builder/core/locales/load"; import { TypeIcon } from "~/builder/core/components/sidepanels/panels/outline/block-type-icon"; import { CHAI_BUILDER_EVENTS } from "~/builder/core/events"; import { canAcceptChildBlock, canAddChildBlock } from "~/builder/core/functions/block-helpers"; @@ -52,21 +53,25 @@ const currentAddSelection = atom(null); * with the rows they belong to. */ export const OUTLINE_INDENT = 14; -export const getBlockTypeLabel = (data: any): string => { +const defaultTranslate = (key: string) => i18n.t(key); + +export const getBlockTypeLabel = (data: any, translate: (key: string) => string = defaultTranslate): string => { if (data?._type === "Box" && data?.tag && data?.tag !== "div") { - return startCase(data.tag); + return translate(startCase(data.tag)); } // Users see a slot as an "Area"; code keeps `ChaiSlot`. - if (data?._type === "ChaiSlot") return "Area"; - return data?._type?.split("/").pop() || ""; + if (data?._type === "ChaiSlot") return translate("Area"); + const rawType = data?._type?.split("/").pop() || ""; + return rawType ? translate(rawType) : ""; }; -export const getBlockDisplayName = (data: any): string => data?._name || getBlockTypeLabel(data); +export const getBlockDisplayName = (data: any, translate: (key: string) => string = defaultTranslate): string => + data?._name || getBlockTypeLabel(data, translate); /** "Name (Type)" for a renamed block, so the hover title still says what it is. */ -export const getBlockHoverTitle = (data: any): string => { - const displayName = getBlockDisplayName(data); - const typeLabel = getBlockTypeLabel(data); +export const getBlockHoverTitle = (data: any, translate: (key: string) => string = defaultTranslate): string => { + const displayName = getBlockDisplayName(data, translate); + const typeLabel = getBlockTypeLabel(data, translate); if (!displayName || !typeLabel || displayName.trim().toLowerCase() === typeLabel.trim().toLowerCase()) { return displayName; } @@ -104,7 +109,8 @@ export const getOutlineNodeLabel = ( isPartialBlock: boolean, partialRefId: string, projectPages: Array<{ id?: string; name?: string }> | undefined, -): string => getPartialDisplayName(isPartialBlock, partialRefId, projectPages) ?? getBlockDisplayName(data); + translate: (key: string) => string = defaultTranslate, +): string => getPartialDisplayName(isPartialBlock, partialRefId, projectPages) ?? getBlockDisplayName(data, translate); const truncateText = (text: string, maxLength: number) => { if (text.length > maxLength) { @@ -114,7 +120,7 @@ const truncateText = (text: string, maxLength: number) => { }; export const Node = memo(({ node, style, dragHandle }: NodeRendererProps) => { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); const updateBlockProps = useUpdateBlocksProps(); const [iframe] = useAtom(canvasIframeAtom); const iframeRef = useRef(null); @@ -233,8 +239,7 @@ export const Node = memo(({ node, style, dragHandle }: NodeRendererProps) = // The insertion placeholder always opens the Add Blocks MODAL, never the side // panel: the placeholder carries a parent + position, and the side panel drops - // both (it always adds at the root end). Other OPEN_ADD_BLOCK triggers keep the - // side panel when drag and drop is on. + // both (it always adds at the root end). Every outline trigger forces the modal. const addBlockOnPosition = (position: number) => { onMouseLeave(); const parentId = get(node, "parent.id"); @@ -286,11 +291,11 @@ export const Node = memo(({ node, style, dragHandle }: NodeRendererProps) = // page can't be resolved (e.g. a missing partial). const { data: projectPages } = useChaiPrimaryPages(); const displayName = useMemo( - () => getOutlineNodeLabel(data, isPartialBlock, partialRefId, projectPages), - [isPartialBlock, partialRefId, projectPages, data], + () => getOutlineNodeLabel(data, isPartialBlock, partialRefId, projectPages, t), + [isPartialBlock, partialRefId, projectPages, data, t, i18n.language], ); // Partial rows show the partial's live name; their baked `_name` is stale. - const hoverTitle = isPartialBlock ? displayName : getBlockHoverTitle(data); + const hoverTitle = isPartialBlock ? displayName : getBlockHoverTitle(data, t); // The sentinel row appended after the last root block: a hover-revealed // "Add block" pill that appends at the end of the page (position -1). Without diff --git a/src/builder/core/components/sidepanels/panels/outline/paste-into-root.tsx b/src/builder/core/components/sidepanels/panels/outline/paste-into-root.tsx index 682a63ee1..d12a2ef10 100644 --- a/src/builder/core/components/sidepanels/panels/outline/paste-into-root.tsx +++ b/src/builder/core/components/sidepanels/panels/outline/paste-into-root.tsx @@ -41,7 +41,7 @@ export const PasteAtRootContextMenu = ({ {hasPermission(CHAI_PERMISSIONS["pages:update"]) && ( pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, null)}> + onClick={() => pubsub.publish(CHAI_BUILDER_EVENTS.OPEN_ADD_BLOCK, { forceModal: true })}> {t("Add block")} )} diff --git a/src/builder/core/components/sidepanels/panels/theme-configuration/css-import-modal.tsx b/src/builder/core/components/sidepanels/panels/theme-configuration/css-import-modal.tsx index 60893aeb8..00d0d2276 100644 --- a/src/builder/core/components/sidepanels/panels/theme-configuration/css-import-modal.tsx +++ b/src/builder/core/components/sidepanels/panels/theme-configuration/css-import-modal.tsx @@ -110,7 +110,7 @@ export const CssImportModal: React.FC = ({ open, onOpenChan )}
-

Get theme resources:

+

{t("Get theme resources:")}

diff --git a/src/builder/core/design-tokens/token-list-components.tsx b/src/builder/core/design-tokens/token-list-components.tsx index 423add69c..a643dbc9c 100644 --- a/src/builder/core/design-tokens/token-list-components.tsx +++ b/src/builder/core/design-tokens/token-list-components.tsx @@ -107,7 +107,7 @@ export const SingleToken: React.FC = ({ e.stopPropagation(); unarchiveToken(tokenId); }}> - Restore + {t("Restore")} )} {canDelete && ( @@ -119,7 +119,7 @@ export const SingleToken: React.FC = ({ deleteToken(tokenId); }} className="text-destructive hover:text-destructive"> - Delete + {t("Delete")} )} @@ -325,7 +325,7 @@ export const CustomTokensList: React.FC = () => { e.stopPropagation(); handleArchiveClick(tokenId, token.name); }}> - Archive + {t("Archive")} )}
diff --git a/src/builder/core/functions/block-helpers.ts b/src/builder/core/functions/block-helpers.ts index 8408f7763..58c247ad4 100644 --- a/src/builder/core/functions/block-helpers.ts +++ b/src/builder/core/functions/block-helpers.ts @@ -1,6 +1,7 @@ import { get, has, omit } from "lodash-es"; import { getRegisteredChaiBlock } from "~/registry"; import { getSlotRule, matchesAccept } from "~/render/block-slots"; +import type { ChaiCanShowBlock } from "~/types/chaibuilder-editor-props"; type BlockDefinition = { canAcceptBlock?: (target: string) => boolean; @@ -128,6 +129,32 @@ export const isBlockAvailableForPageType = (block: { pageTypes?: string[] }, pag return pageTypes.includes(pageType); }; +/** + * Combines `pageTypes` availability with the host's optional `canShowBlock` predicate. + * When `canShowBlock` is omitted, falls back to `isBlockAvailableForPageType`. + */ +export const isBlockAvailable = ( + block: { pageTypes?: string[]; type?: string; id?: string; metadata?: Record }, + pageType: string, + canShowBlock?: ChaiCanShowBlock, +) => isBlockAvailableForPageType(block, pageType) && (canShowBlock ? canShowBlock(block, { pageType }) : true); + +/** + * Returns registered block type names rejected by the host's `canShowBlock` predicate. + */ +export const getHiddenBlockTypes = ( + blocks: Record }>, + pageType: string, + canShowBlock?: ChaiCanShowBlock, +): string[] => { + if (!canShowBlock) return []; + const hidden = Object.entries(blocks) + .filter(([, block]) => !canShowBlock(block, { pageType })) + .map(([registryKey, block]) => block.type ?? registryKey) + .filter((type): type is string => typeof type === "string" && type.length > 0); + return Array.from(new Set(hidden)); +}; + if (import.meta.vitest) { describe("canDropBlock Function", () => { it('should return false if dragSourceType is "Slot"', () => { @@ -162,4 +189,51 @@ if (import.meta.vitest) { expect(isBlockAvailableForPageType({ pageTypes: ["product", "collection"] }, "collection")).toBe(true); }); }); + + describe("isBlockAvailable Function", () => { + it("falls back to pageTypes when no canShowBlock is given", () => { + expect(isBlockAvailable({ type: "A", pageTypes: ["product"] }, "product")).toBe(true); + expect(isBlockAvailable({ type: "A", pageTypes: ["product"] }, "page")).toBe(false); + }); + + it("applies canShowBlock with pageType context alongside pageTypes", () => { + const seen: Array<{ type?: string; pageType?: string }> = []; + const canShowBlock: ChaiCanShowBlock = (block, ctx) => { + seen.push({ type: block.type, pageType: ctx.pageType }); + return block.metadata?.allowed === true; + }; + + expect(isBlockAvailable({ type: "Allowed", metadata: { allowed: true } }, "page", canShowBlock)).toBe(true); + expect(isBlockAvailable({ type: "Hidden", metadata: { allowed: false } }, "page", canShowBlock)).toBe(false); + // Fails pageTypes first, so canShowBlock is not even called. + expect( + isBlockAvailable({ type: "WrongPage", pageTypes: ["product"], metadata: { allowed: true } }, "page", canShowBlock), + ).toBe(false); + expect(seen).toEqual([ + { type: "Allowed", pageType: "page" }, + { type: "Hidden", pageType: "page" }, + ]); + }); + }); + + describe("getHiddenBlockTypes Function", () => { + it("returns an empty array when canShowBlock is omitted", () => { + expect(getHiddenBlockTypes({ A: { type: "A" } }, "page")).toEqual([]); + }); + + it("returns block types rejected by canShowBlock with pageType context", () => { + const canShowBlock: ChaiCanShowBlock = (block, ctx) => + ctx.pageType === "page" && block.metadata?.allowed !== false; + expect( + getHiddenBlockTypes( + { + Allowed: { type: "Allowed", metadata: { allowed: true } }, + Hidden: { type: "Hidden", metadata: { allowed: false } }, + }, + "page", + canShowBlock, + ), + ).toEqual(["Hidden"]); + }); + }); } diff --git a/src/builder/core/locales/en.json b/src/builder/core/locales/en.json index 5063801db..b098ae11f 100644 --- a/src/builder/core/locales/en.json +++ b/src/builder/core/locales/en.json @@ -2,6 +2,8 @@ "Add block": "Add Block", "Add Block": "Add Block", "Add blocks": "Add blocks", + "Replace block": "Replace block", + "This block can't replace the selected block here.": "This block can't replace the selected block here.", "Add inside": "Add inside", "Add before": "Add before", "Add after": "Add after", @@ -245,7 +247,6 @@ "Filter by tag": "Filter by tag", "No tags found.": "No tags found.", "Clear filters": "Clear filters", - "Layouts": "Layouts", "Search Layouts": "Search Layouts", "Type": "Type", "Status": "Status", @@ -305,7 +306,6 @@ "CSS Variables": "CSS Variables", "You don't have permission to edit settings or styles": "You don't have permission to edit settings or styles", "Please contact your administrator to get access": "Please contact your administrator to get access", - "flex.heading": "Flex Child", "flex.basis": "Basis", "flex.order": "Order", @@ -579,7 +579,6 @@ "rows": "Rows" }, "Export Code": "Export Code", - "Exporting {{count}} blocks": "Exporting {{count}} blocks", "Exporting all blocks": "Exporting all blocks", "Export code copied!": "Export code copied!", "Failed to copy export code": "Failed to copy export code", @@ -590,5 +589,1427 @@ "Enter key": "Enter key", "Add": "Add", "Save": "Save", - "Screen": "Screen" + "Screen": "Screen", + "Improving writing in all text elements. Replacing placeholder content with meaningful relevant content.": "Improving writing in all text elements. Replacing placeholder content with meaningful relevant content.", + "Translate to {{lang}}": "Translate to {{lang}}", + "Translate the content to {{lang}}. Maintain same tone, style and length.": "Translate the content to {{lang}}. Maintain same tone, style and length.", + "Selected block": "Selected block", + "Quick actions": "Quick actions", + "Search...": "Search...", + "HTML Code Editor": "HTML Code Editor", + "{{name}} — {{type}}. Double click to edit.": "{{name}} — {{type}}. Double click to edit.", + "{{type}}. Double click to edit.": "{{type}}. Double click to edit.", + "ACTIONS": "ACTIONS", + "Clear canvas": "Clear canvas", + "Data Binding": "Data Binding", + "Invalid structure": "Invalid structure", + "No validation issues found.": "No validation issues found.", + "Page Validation Issues": "Page Validation Issues", + "The following issues were found on this page.": "The following issues were found on this page.", + "The following issues were found on this page. You can fix them or continue anyway.": "The following issues were found on this page. You can fix them or continue anyway.", + "Errors": "Errors", + "Warnings": "Warnings", + "Resolve errors to publish the page.": "Resolve errors to publish the page.", + "Do not show for": "Do not show for", + "Off": "Off", + "days": "days", + "day": "day", + "Go to block": "Go to block", + "Open {{name}}": "Open {{name}}", + "Expand": "Expand", + "Collapse": "Collapse", + "Style Elements": "Style Elements", + "Ask AI to style this block...": "Ask AI to style this block...", + "Add Attribute": "Add Attribute", + "View Attribute": "View Attribute", + "Edit attribute": "Edit attribute", + "Add attribute": "Add attribute", + "Key": "Key", + "No attributes added yet": "No attributes added yet", + "Token Classes": "Token Classes", + "Panel name": "Panel name", + "Loading pages...": "Loading pages...", + "Used on ({{count}})": "Used on ({{count}})", + "This page": "This page", + "(this page)": "(this page)", + "Edit {{type}}": "Edit {{type}}", + "Changes to this {{type}} apply on every page that uses it.": "Changes to this {{type}} apply on every page that uses it.", + "Choose a wrapper in Settings to style this block.": "Choose a wrapper in Settings to style this block.", + "This block has no settings or styles": "This block has no settings or styles", + "Select element": "Select element", + "Search element...": "Search element...", + "No element found.": "No element found.", + "Available databindings:": "Available databindings:", + "Visibility": "Visibility", + " Visible when true": " Visible when true", + "Open visibility settings": "Open visibility settings", + "Conditional Visibility": "Conditional Visibility", + "Choose a boolean data path or add boolean pipes. The block is visible only when the result is true.": "Choose a boolean data path or add boolean pipes. The block is visible only when the result is true.", + "No results found": "No results found", + "Searching...": "Searching...", + "Select library": "Select library", + "This library is empty": "This library is empty", + "Select a group": "Select a group", + "View description": "View description", + "Loading {{name}}...": "Loading {{name}}...", + "No {{name}} available": "No {{name}} available", + "Theme and {{label}}": "Theme and {{label}}", + "{{name}} detected. Clone {{name}}?": "{{name}} detected. Clone {{name}}?", + "Show block": "Show block", + "Hide block": "Hide block", + "Get started by adding your first block to begin building your page": "Get started by adding your first block to begin building your page", + "Add block at the top": "Add block at the top", + "{{name}} created successfully": "{{name}} created successfully", + "Name is required": "Name is required", + "Page type is required": "Page type is required", + "This {{name}} is used inside another {{name}}. Creating a {{name}} here would exceed the maximum nesting depth ({{depth}} levels)": "This {{name}} is used inside another {{name}}. Creating a {{name}} here would exceed the maximum nesting depth ({{depth}} levels)", + "This section contains {{plural}}. Creating a {{name}} from it would exceed the maximum nesting depth ({{depth}} levels)": "This section contains {{plural}}. Creating a {{name}} from it would exceed the maximum nesting depth ({{depth}} levels)", + "Convert this section into a {{name}} that can be reused across pages.": "Convert this section into a {{name}} that can be reused across pages.", + "Select partial type": "Select partial type", + "Enter {{name}} name": "Enter {{name}} name", + "Description": "Description", + "Describe what this {{name}} is for. Used by AI to understand when to use it.": "Describe what this {{name}} is for. Used by AI to understand when to use it.", + "Block name": "Block name", + "Add block at the end": "Add block at the end", + "Add block here": "Add block here", + "It will hide block from canvas": "It will hide block from canvas", + "It will make block visible in canvas": "It will make block visible in canvas", + "This global block was deleted. Remove it from this page.": "This global block was deleted. Remove it from this page.", + "Missing": "Missing", + "Update library block": "Update library block", + "Save to library": "Save to library", + "FILTERS": "FILTERS", + "Block types": "Block types", + "BLOCK TYPES": "BLOCK TYPES", + "Conditional": "Conditional", + "Data binding": "Data binding", + "Animations": "Animations", + "Search results": "Search results", + "No matching blocks": "No matching blocks", + "Unwrap": "Unwrap", + "Wrap In": "Wrap In", + "Box": "Box", + "Link": "Link", + "Wrap with": "Wrap with", + "Invalid CSS format": "Invalid CSS format", + "The CSS doesn't contain enough theme information. Please ensure it includes at least background, foreground, primary, and primary-foreground colors.": "The CSS doesn't contain enough theme information. Please ensure it includes at least background, foreground, primary, and primary-foreground colors.", + "Failed to parse CSS. Please check your syntax and try again.": "Failed to parse CSS. Please check your syntax and try again.", + "Paste your CSS variables to import a custom theme. The CSS should contain :root and .dark blocks with CSS custom properties.": "Paste your CSS variables to import a custom theme. The CSS should contain :root and .dark blocks with CSS custom properties.", + "Select font": "Select font", + "Theme saved": "Theme saved", + "Failed to save theme": "Failed to save theme", + "You don't have permission to edit the theme. Please contact your administrator to get access.": "You don't have permission to edit the theme. Please contact your administrator to get access.", + "Select preset": "Select preset", + "Typography": "Typography", + "Border Radius": "Border Radius", + "Site layout": "Site layout", + "Not set": "Not set", + "Container": "Container", + "Fluid": "Fluid", + "Narrow": "Narrow", + "Colors": "Colors", + "Toggle dark mode": "Toggle dark mode", + "Discard": "Discard", + "Unsaved theme changes": "Unsaved theme changes", + "You have unsaved theme changes. Do you want to save them before closing?": "You have unsaved theme changes. Do you want to save them before closing?", + "Discard changes": "Discard changes", + "Save & Close": "Save & Close", + "This action cannot be undone. This will permanently remove the design token from your project.": "This action cannot be undone. This will permanently remove the design token from your project.", + "Token classes": "Token classes", + "Light": "Light", + "Dark": "Dark", + "Sample text with token styles applied": "Sample text with token styles applied", + "No match": "No match", + "None": "None", + "Blocks affected on": "Blocks affected on", + "Filter": "Filter", + "This page ({{count}})": "This page ({{count}})", + "Other pages ({{count}})": "Other pages ({{count}})", + "{{name}} ({{count}})": "{{name}} ({{count}})", + "Token name must be {{max}} characters or less": "Token name must be {{max}} characters or less", + "Only alphanumeric characters and hyphens allowed": "Only alphanumeric characters and hyphens allowed", + "Token name already exists": "Token name already exists", + "Edit {{name}}": "Edit {{name}}", + "Custom": "Custom", + "No custom {{label}} yet": "No custom {{label}} yet", + "Built-in edited": "Built-in edited", + "No built-in {{label}} edited": "No built-in {{label}} edited", + "Archived": "Archived", + "No archived {{label}}": "No archived {{label}}", + "Reusable class bundles shared by blocks across the site. Changes save as a draft and go live when you publish them.": "Reusable class bundles shared by blocks across the site. Changes save as a draft and go live when you publish them.", + "Manage": "Manage", + "Token updated successfully": "Token updated successfully", + "Please fill in both token name and classes": "Please fill in both token name and classes", + "Invalid design token name format": "Invalid design token name format", + "Token already exists": "Token already exists", + "Token added successfully": "Token added successfully", + "Token reset to built-in": "Token reset to built-in", + "Token archived successfully": "Token archived successfully", + "Token unarchived successfully": "Token unarchived successfully", + "Token deleted successfully": "Token deleted successfully", + "Create and manage reusable": "Create and manage reusable", + "Select a token to preview": "Select a token to preview", + "Unsaved Changes": "Unsaved Changes", + "You have unsaved changes. Are you sure you want to close? Your changes will be lost.": "You have unsaved changes. Are you sure you want to close? Your changes will be lost.", + "Continue Editing": "Continue Editing", + "Discard Changes": "Discard Changes", + "Built-in": "Built-in", + "Update": "Update", + "Create a reusable": "Create a reusable", + "Token Name": "Token Name", + "names cannot be changed": "names cannot be changed", + "Button-Primary, Card-Header, Text-Large etc.": "Button-Primary, Card-Header, Text-Large etc.", + "Reset to Built-in": "Reset to Built-in", + "Edited": "Edited", + "Used on this page": "Used on this page", + "Search built-in {{label}}": "Search built-in {{label}}", + "No {{label}} match your search": "No {{label}} match your search", + "Search custom {{label}}": "Search custom {{label}}", + "No custom": "No custom", + "yet": "yet", + "Add custom {{items}}": "Add custom {{items}}", + "Archive Design Token": "Archive Design Token", + "This token is used on": "This token is used on", + "pages": "pages", + "and": "and", + "partials": "partials", + "Archiving this token will remove the styling for those blocks.": "Archiving this token will remove the styling for those blocks.", + "Do you wish to continue?": "Do you wish to continue?", + "Archive": "Archive", + "Paste SVG code here": "Paste SVG code here", + "No fields found": "No fields found", + "Type any expression, close with": "Type any expression, close with", + "Search pages": "Search pages", + "New tab": "New tab", + "selected": "selected", + "Alt text": "Alt text", + "Enter alt text": "Enter alt text", + "No description": "No description", + "Move image up": "Move image up", + "Move image down": "Move image down", + "Remove image": "Remove image", + "Choose images": "Choose images", + "Replace video": "Replace video", + "Choose video": "Choose video", + "Enter video URL": "Enter video URL", + "Image Manager": "Image Manager", + "Video Manager": "Video Manager", + "Audio Manager": "Audio Manager", + "Document Manager": "Document Manager", + "All Manager": "All Manager", + "Enter audio URL": "Enter audio URL", + "Enter document URL": "Enter document URL", + "Enter all URL": "Enter all URL", + "Create {{name}}": "Create {{name}}", + "Create Global Block": "Create Global Block", + "Search Pages": "Search Pages", + "Search {{name}}": "Search {{name}}", + "Search Global Blocks": "Search Global Blocks", + "{{name}}s": "{{name}}s", + "Global Block": "Global Block", + "Global Blocks": "Global Blocks", + "Could not save the page. Please try again.": "Could not save the page. Please try again.", + "Theme Updated": "Theme Updated", + "{{userName}} updated the theme": "{{userName}} updated the theme", + "Design Tokens Updated": "Design Tokens Updated", + "{{userName}} updated the design tokens": "{{userName}} updated the design tokens", + "Unknown sync type": "Unknown sync type", + "This page shows {{label}} content, which can't be edited here.": "This page shows {{label}} content, which can't be edited here.", + "This page shows {{label}} content, which can't be edited here. Duplicate it to edit your own copy.": "This page shows {{label}} content, which can't be edited here. Duplicate it to edit your own copy.", + "Add New": "Add New", + "Update your page name": "Update your page name", + "Enter details to create a new page": "Enter details to create a new page", + "Slugs cannot start with a language code for primary page": "Slugs cannot start with a language code for primary page", + "Change Slug": "Change Slug", + "Changing the slug may have impact on your SEO. Please proceed with caution.": "Changing the slug may have impact on your SEO. Please proceed with caution.", + "Slug": "Slug", + "Slug should start with": "Slug should start with", + "Slug must start with /": "Slug must start with /", + "Enter page slug": "Enter page slug", + "Changing...": "Changing...", + "Delete Page": "Delete Page", + "Are you sure you want to move": "Are you sure you want to move", + "Are you sure you want to delete": "Are you sure you want to delete", + "to archive?": "to archive?", + "? This action cannot be undone.": "? This action cannot be undone.", + "Warning: Archiving this primary page will also remove": "Warning: Archiving this primary page will also remove", + "Warning: Trashing this primary page will also remove": "Warning: Trashing this primary page will also remove", + "Warning: Deleting this primary page will also remove": "Warning: Deleting this primary page will also remove", + "nested child page": "nested child page", + "nested child pages": "nested child pages", + "All associated language pages": "All associated language pages", + "Warning: This {{name}} is currently used in the following pages": "Warning: This {{name}} is currently used in the following pages", + "Language": "Language", + "Slug is required": "Slug is required", + "Slug must start with /{{lang}}/": "Slug must start with /{{lang}}/", + "A page with the slug {{slug}} already exists. Please choose a different slug.": "A page with the slug {{slug}} already exists. Please choose a different slug.", + "A page with this slug already exists. Please choose a different slug.": "A page with this slug already exists. Please choose a different slug.", + "{{slug}} must start with its language prefix": "{{slug}} must start with its language prefix", + "The slug format is invalid. Please use only lowercase letters, numbers, and hyphens.": "The slug format is invalid. Please use only lowercase letters, numbers, and hyphens.", + "You don't have permission to duplicate this page.": "You don't have permission to duplicate this page.", + "Failed to duplicate page. Please try again later.": "Failed to duplicate page. Please try again later.", + "Duplicate Page": "Duplicate Page", + "Create a copy of the page with a new name and slug": "Create a copy of the page with a new name and slug", + "Current Page Details": "Current Page Details", + "Invalid slug": "Invalid slug", + "Language variants": "Language variants", + "Current Page": "Current Page", + "Use": "Use", + "as identifier": "as identifier", + "Opens this item directly. It may not exist.": "Opens this item directly. It may not exist.", + "No pages found": "No pages found", + "Type a slug or identifier to open it directly.": "Type a slug or identifier to open it directly.", + "Create from scratch": "Create from scratch", + "Link {{label}}": "Link {{label}}", + "Select the page to link to": "Select the page to link to", + "A dynamic page needs a parent page": "A dynamic page needs a parent page", + "Dynamic slug is invalid": "Dynamic slug is invalid", + "Slug is invalid": "Slug is invalid", + "No {{label}} is available to link.": "No {{label}} is available to link.", + "Loading...": "Loading...", + "Select a page": "Select a page", + "Enter custom slug part (optional)": "Enter custom slug part (optional)", + "Complete Slug": "Complete Slug", + "A dynamic page needs a parent page. Choose one to see its slug.": "A dynamic page needs a parent page. Choose one to see its slug.", + "Adding...": "Adding...", + "Add page": "Add page", + "File too large": "File too large", + "Maximum file size is 1MB. Selected file is": "Maximum file size is 1MB. Selected file is", + "Failed to process image": "Failed to process image", + "Unknown error": "Unknown error", + "Mark as template": "Mark as template", + "Are you sure you want to mark this page as a template?": "Are you sure you want to mark this page as a template?", + "Templates can be used to create new pages with the same content.": "Templates can be used to create new pages with the same content.", + "Page Name": "Page Name", + "Description (Optional)": "Description (Optional)", + "Describe this template's purpose": "Describe this template's purpose", + "Preview Image (Optional)": "Preview Image (Optional)", + "Select image": "Select image", + "max 1mb": "max 1mb", + "Folder converted to page": "Folder converted to page", + "Convert to page": "Convert to page", + "Unpublish": "Unpublish", + "Try adjusting your search to find what you're looking for.": "Try adjusting your search to find what you're looking for.", + "Create reusable blocks to maintain consistency and design faster.": "Create reusable blocks to maintain consistency and design faster.", + "Add new page to start": "Add new page to start", + "Collapse All": "Collapse All", + "Expand All": "Expand All", + "Refresh pages list": "Refresh pages list", + "Search pages and blocks...": "Search pages and blocks...", + "Add Page": "Add Page", + "Toggle Untranslated Pages": "Toggle Untranslated Pages", + "Pages Manager": "Pages Manager", + "Manage your site structure": "Manage your site structure", + "Publishing…": "Publishing…", + "Open pages manager": "Open pages manager", + "Select parent page": "Select parent page", + "Search page...": "Search page...", + "Select none": "Select none", + "Added": "Added", + "Changed": "Changed", + "Removed": "Removed", + "Failed to save design tokens": "Failed to save design tokens", + "Unpublished changes": "Unpublished changes", + "Publish": "Publish", + "Every published page picks up the new token styles. The theme is not published.": "Every published page picks up the new token styles. The theme is not published.", + "Publish theme": "Publish theme", + "Publish theme?": "Publish theme?", + "Publishing the theme rebuilds all pages on the site with the new theme.": "Publishing the theme rebuilds all pages on the site with the new theme.", + "Translation Warning": "Translation Warning", + "1 block needs translations before publishing. Review it or continue anyway.": "1 block needs translations before publishing. Review it or continue anyway.", + "Open {{name}} in new tab": "Open {{name}} in new tab", + "Select block": "Select block", + "And 1 more block...": "And 1 more block...", + "You have some unpublished changes": "You have some unpublished changes", + "The following {{name}} are either unpublished or have unpublished changes.": "The following {{name}} are either unpublished or have unpublished changes.", + "Published": "Published", + "View Changes": "View Changes", + "Unpublished": "Unpublished", + "Publish {{name}} & Page": "Publish {{name}} & Page", + "SEO fields reset to defaults": "SEO fields reset to defaults", + "Failed to reset SEO fields": "Failed to reset SEO fields", + "JSON-LD reset to default": "JSON-LD reset to default", + "Failed to reset JSON-LD": "Failed to reset JSON-LD", + "Meta Tag fields reset to defaults": "Meta Tag fields reset to defaults", + "Failed to reset Meta Tag fields": "Failed to reset Meta Tag fields", + "JSON-LD is not valid JSON": "JSON-LD is not valid JSON", + "SEO & JSON-LD updated successfully": "SEO & JSON-LD updated successfully", + "Failed to update SEO & JSON-LD": "Failed to update SEO & JSON-LD", + "SEO field generated successfully": "SEO field generated successfully", + "Default page JSON-LD is empty": "Default page JSON-LD is empty", + "You don't have permission to edit SEO settings. Contact your administrator for access.": "You don't have permission to edit SEO settings. Contact your administrator for access.", + "SEO": "SEO", + "Meta Tags": "Meta Tags", + "JSON-LD": "JSON-LD", + "SEO Title": "SEO Title", + "Enter SEO title": "Enter SEO title", + "SEO Description": "SEO Description", + "Enter SEO description": "Enter SEO description", + "Canonical URL": "Canonical URL", + "Enter Canonical URL": "Enter Canonical URL", + "No Index": "No Index", + "Check this if you don't want search engines to index this page.": "Check this if you don't want search engines to index this page.", + "No Follow": "No Follow", + "Check this if you don't want search engines to follow links on this page.": "Check this if you don't want search engines to follow links on this page.", + "Open Graph": "Open Graph", + "Leave these empty to use the SEO Title and SEO Description from the SEO tab. Fill them in only to override.": "Leave these empty to use the SEO Title and SEO Description from the SEO tab. Fill them in only to override.", + "OG Title": "OG Title", + "Enter OG title": "Enter OG title", + "OG Description": "OG Description", + "Enter OG description": "Enter OG description", + "OG Image": "OG Image", + "Select OG image": "Select OG image", + "Enter JSON-LD": "Enter JSON-LD", + "Resetting...": "Resetting...", + "Reset to Default JSON-LD": "Reset to Default JSON-LD", + "Reset to Default Open Graph": "Reset to Default Open Graph", + "Reset to Default SEO": "Reset to Default SEO", + "You have unsaved SEO changes. Do you want to save them before closing?": "You have unsaved SEO changes. Do you want to save them before closing?", + "Your page title": "Your page title", + "Your page description will appear here. Add an SEO description to control what searchers see.": "Your page description will appear here. Add an SEO description to control what searchers see.", + "Search Result Preview": "Search Result Preview", + "Open preview in new tab": "Open preview in new tab", + "{{title}} (unpublished changes)": "{{title}} (unpublished changes)", + "Save draft": "Save draft", + "Save anyway": "Save anyway", + "View Unpublished changes": "View Unpublished changes", + "Publish with translation pages": "Publish with translation pages", + "Publish anyway": "Publish anyway", + "Open live page": "Open live page", + "Unmark as template": "Unmark as template", + "Are you sure you want to unmark this page as a template?": "Are you sure you want to unmark this page as a template?", + "Confirm action": "Confirm action", + "Are you sure you want to unpublish": "Are you sure you want to unpublish", + "Updating...": "Updating...", + "Duplicating...": "Duplicating...", + "Duplicate and edit": "Duplicate and edit", + "Reset": "Reset", + "View live": "View live", + "Done recording": "Done recording", + "Start voice input": "Start voice input", + "Error saving edited image:": "Error saving edited image:", + "Digital Asset Manager": "Digital Asset Manager", + "Website Assets": "Website Assets", + "Search assets...": "Search assets...", + "Deselect all": "Deselect all", + "Select all": "Select all", + "Clear selection": "Clear selection", + "Delete selected": "Delete selected", + "Select Asset": "Select Asset", + "No assets found": "No assets found", + "No assets found for your search: {{query}}": "No assets found for your search: {{query}}", + "Start uploading assets to get started": "Start uploading assets to get started", + "View Details": "View Details", + "View": "View", + "Asset URL copied to clipboard": "Asset URL copied to clipboard", + "Copy URL": "Copy URL", + "Edit Image": "Edit Image", + "Error loading pagination": "Error loading pagination", + "Delete Asset(s)": "Delete Asset(s)", + "Are you sure you want to move \"{{name}}\" to archive?": "Are you sure you want to move \"{{name}}\" to archive?", + "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.": "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.", + "Update this file": "Update this file", + "Save as new file": "Save as new file", + "Add text here": "Add text here", + "Selected image": "Selected image", + "Select Image": "Select Image", + "{{type}} copied to clipboard": "{{type}} copied to clipboard", + "Failed to copy {{type}}": "Failed to copy {{type}}", + "Image description generated successfully. Please save to apply.": "Image description generated successfully. Please save to apply.", + "Failed to generate image description": "Failed to generate image description", + "No Asset Found": "No Asset Found", + "There was an error loading the asset. Please try again later.": "There was an error loading the asset. Please try again later.", + "The asset you're looking for doesn't exist or has been removed.": "The asset you're looking for doesn't exist or has been removed.", + "Back to Assets": "Back to Assets", + "Try Again": "Try Again", + "Asset URL": "Asset URL", + "Download": "Download", + "Details": "Details", + "Format": "Format", + "Size": "Size", + "Dimensions": "Dimensions", + "Created": "Created", + "Used On": "Used On", + "Generate description with AI": "Generate description with AI", + "Enter a description for the asset": "Enter a description for the asset", + "Updating file...": "Updating file...", + "Saving to storage...": "Saving to storage...", + "Uploading file...": "Uploading file...", + "Please wait while we": "Please wait while we", + "update": "update", + "upload": "upload", + "your file...": "your file...", + "Image Optimization": "Image Optimization", + "Warning: Unoptimized images may affect performance and page load times": "Warning: Unoptimized images may affect performance and page load times", + "Drop your file here or": "Drop your file here or", + "Browse": "Browse", + "Upload via URL": "Upload via URL", + "Accepted:": "Accepted:", + "Paste direct image URL here (jpg, png, webp, etc.)...": "Paste direct image URL here (jpg, png, webp, etc.)...", + "\"{{name}}\" is not an accepted file type.": "\"{{name}}\" is not an accepted file type.", + "\"{{name}}\" is larger than the {{limit}} limit for {{type}}.": "\"{{name}}\" is larger than the {{limit}} limit for {{type}}.", + "Please enter a valid image URL (http or https).": "Please enter a valid image URL (http or https).", + "Failed to upload image from URL. Please check that the URL points to a valid image.": "Failed to upload image from URL. Please check that the URL points to a valid image.", + "Select a block first.": "Select a block first.", + "Ask to update content": "Ask to update content", + "Ask anything...": "Ask anything...", + "Include: ": "Include: ", + "Business name & industry (e.g. TechFlow is a project management": "Business name & industry (e.g. TechFlow is a project management", + "company": "company", + "Target audience (e.g. creative agencies)": "Target audience (e.g. creative agencies)", + "Unique value proposition (e.g. AI-driven scheduling)": "Unique value proposition (e.g. AI-driven scheduling)", + "Key products/services (e.g. AI-driven scheduling)": "Key products/services (e.g. AI-driven scheduling)", + "Enter Site Context:": "Enter Site Context:", + "Enhance with AI": "Enhance with AI", + "Look": "Look", + "Tone": "Tone", + "Banned Words": "Banned Words", + "Page purpose (e.g. This is the Services page targeting ": "Page purpose (e.g. This is the Services page targeting ", + "custom web design": "custom web design", + "Target keywords (e.g. custom web design)": "Target keywords (e.g. custom web design)", + "Primary H1 goal (e.g. Showcase our design process)": "Primary H1 goal (e.g. Showcase our design process)", + "Enter Page Context:": "Enter Page Context:", + "Please enter some site context to enhance": "Please enter some site context to enhance", + "Site context enhanced with AI!": "Site context enhanced with AI!", + "AI enhancement failed. Please try again.": "AI enhancement failed. Please try again.", + "Failed to enhance with AI": "Failed to enhance with AI", + "Please enter some page context to enhance": "Please enter some page context to enhance", + "Page context enhanced with AI!": "Page context enhanced with AI!", + "AI context saved successfully!": "AI context saved successfully!", + "Failed to save AI context": "Failed to save AI context", + "Manage Context": "Manage Context", + "Configure site and page context to help AI generate better, more": "Configure site and page context to help AI generate better, more", + "Website": "Website", + "Generation stopped": "Generation stopped", + "Generate image with AI": "Generate image with AI", + "Failed to get AI response": "Failed to get AI response", + "Response body is not readable": "Response body is not readable", + "Start a conversation with the AI assistant to add/edit current page": "Start a conversation with the AI assistant to add/edit current page", + "Generate image": "Generate image", + "Generate images with AI": "Generate images with AI", + "Describe the image you want to generate.": "Describe the image you want to generate.", + "Image generation failed. Try again": "Image generation failed. Try again", + "Aspect ratio": "Aspect ratio", + "Quality": "Quality", + "High": "High", + "Medium": "Medium", + "Low": "Low", + "Image configuration": "Image configuration", + "Ratio": "Ratio", + "Translate the content": "Translate the content", + "Content updated successfully.": "Content updated successfully.", + "Start a conversation with the AI assistant to translate/edit your content": "Start a conversation with the AI assistant to translate/edit your content", + "Only content can be edited in secondary languages. To edit layout, styles and more, switch to the default language.": "Only content can be edited in secondary languages. To edit layout, styles and more, switch to the default language.", + "Actions will work only on the selected block": "Actions will work only on the selected block", + "Stop generation": "Stop generation", + "{{model}} can't read images or files. Attachments were not sent — switch models to use them.": "{{model}} can't read images or files. Attachments were not sent — switch models to use them.", + "Generation stopped. The page was restored to how it was before this prompt.": "Generation stopped. The page was restored to how it was before this prompt.", + "Generation stopped.": "Generation stopped.", + "This conversation has a lot of context built up.": "This conversation has a lot of context built up.", + "Start new conversation": "Start new conversation", + "Describe the image you want to generate": "Describe the image you want to generate", + "Add image": "Add image", + "Add file": "Add file", + "Quick Action:": "Quick Action:", + "Translate Content": "Translate Content", + "to": "to", + "Entire Page": "Entire Page", + "Remove block from context": "Remove block from context", + "Page context": "Page context", + "Edit page context": "Edit page context", + "Website context": "Website context", + "Edit website context": "Edit website context", + "Collapse AI panel": "Collapse AI panel", + "Expand AI panel": "Expand AI panel", + "Current password is required": "Current password is required", + "Password must be at least 8 characters": "Password must be at least 8 characters", + "Password must be less than 128 characters": "Password must be less than 128 characters", + "Password must contain at least one uppercase letter": "Password must contain at least one uppercase letter", + "Password must contain at least one lowercase letter": "Password must contain at least one lowercase letter", + "Password must contain at least one number": "Password must contain at least one number", + "Password must contain at least one special character": "Password must contain at least one special character", + "Confirm password is required": "Confirm password is required", + "New password and confirm password do not match": "New password and confirm password do not match", + "New password must be different from current password": "New password must be different from current password", + "Validation failed": "Validation failed", + "User email not found": "User email not found", + "Failed to change password": "Failed to change password", + "Password updated successfully": "Password updated successfully", + "Change Password": "Change Password", + "Enter your current password and a new password.": "Enter your current password and a new password.", + "Current Password": "Current Password", + "Enter current password": "Enter current password", + "New Password": "New Password", + "Enter new password": "Enter new password", + "Confirm Password": "Confirm Password", + "Confirm new password": "Confirm new password", + "Blur field / deselect blocks": "Blur field / deselect blocks", + "Some files exceed the maximum size limit of": "Some files exceed the maximum size limit of", + "Optimize": "Optimize", + "Search images and videos...": "Search images and videos...", + "Search images...": "Search images...", + "No images or videos found": "No images or videos found", + "Drop images or videos here or use the Upload button to add them.": "Drop images or videos here or use the Upload button to add them.", + "Drop images here or use the Upload button to add them.": "Drop images here or use the Upload button to add them.", + "Video": "Video", + "More actions": "More actions", + "Load more": "Load more", + "Drop images or videos to upload": "Drop images or videos to upload", + "Drop images to upload": "Drop images to upload", + "Light mode": "Light mode", + "Dark mode": "Dark mode", + "Logout": "Logout", + "Are you sure you want to logout?": "Are you sure you want to logout?", + "You will be redirected to the login page.": "You will be redirected to the login page.", + "general:changesNotSaved": "general:changesNotSaved", + "general:stayOnThisPage": "general:stayOnThisPage", + "general:leaveAnyway": "general:leaveAnyway", + "general:leaveWithoutSaving": "general:leaveWithoutSaving", + "Failed to generate alt text": "Failed to generate alt text", + "Buy Credits": "Buy Credits", + "Cannot generate for placeholder image": "Cannot generate for placeholder image", + "Generate alt text with AI": "Generate alt text with AI", + "Failed to process image.": "Failed to process image.", + "Selected model does not support image references. Choose another model or remove the image.": "Selected model does not support image references. Choose another model or remove the image.", + "Failed to generate theme. Please try again.": "Failed to generate theme. Please try again.", + "AI generated invalid CSS. Please try a different description.": "AI generated invalid CSS. Please try a different description.", + "AI generated an incomplete theme. Missing required colors. Please try again.": "AI generated an incomplete theme. Missing required colors. Please try again.", + "Failed to generate theme with AI. Please try again.": "Failed to generate theme with AI. Please try again.", + "Generate theme with AI": "Generate theme with AI", + "Generate a complete theme": "Generate a complete theme", + "Describe a visual direction or add one reference image. AI will style colors, type, and components.": "Describe a visual direction or add one reference image. AI will style colors, type, and components.", + "Creative direction": "Creative direction", + "Example: Warm editorial style with confident typography, compact controls, and subtle paper-like depth…": "Example: Warm editorial style with confident typography, compact controls, and subtle paper-like depth…", + "A prompt is optional when a reference image is attached.": "A prompt is optional when a reference image is attached.", + "Reference image": "Reference image", + "max 5 MB": "max 5 MB", + "Theme reference preview": "Theme reference preview", + "Replace": "Replace", + "Remove reference image": "Remove reference image", + "Drop an image here, or browse": "Drop an image here, or browse", + "Selected model does not accept images": "Selected model does not accept images", + "Use a screenshot, moodboard, or brand reference": "Use a screenshot, moodboard, or brand reference", + "Choose an image-capable model to add a reference": "Choose an image-capable model to add a reference", + "Generating…": "Generating…", + "Generate theme": "Generate theme", + "Add Animation": "Add Animation", + "Animation": "Animation", + "Easing": "Easing", + "Duration (ms)": "Duration (ms)", + "Delay (ms)": "Delay (ms)", + "Once": "Once", + "Infinite": "Infinite", + "Preview animation": "Preview animation", + "Play": "Play", + "No animation added to this element": "No animation added to this element", + "Create using AI": "Create using AI", + "Describe your page and let AI build it for you.": "Describe your page and let AI build it for you.", + "AI is not configured. Please add an API key.": "AI is not configured. Please add an API key.", + "Start blank": "Start blank", + "Start with an empty canvas and build from scratch.": "Start with an empty canvas and build from scratch.", + "Choose template": "Choose template", + "Start with a pre-designed layout.": "Start with a pre-designed layout.", + "What kind of page do you want to build?": "What kind of page do you want to build?", + "Be as descriptive as possible. You can always edit the result later.": "Be as descriptive as possible. You can always edit the result later.", + "e.g. A modern landing page for a SaaS startup...": "e.g. A modern landing page for a SaaS startup...", + "How would you like to start?": "How would you like to start?", + "Choose a template": "Choose a template", + "Export": "Export", + "{{name}} Detected": "{{name}} Detected", + "This block contains one or more {{name}}. {{name}} will be merged into the library block": "This block contains one or more {{name}}. {{name}} will be merged into the library block", + "Generated image is in an unsupported format": "Generated image is in an unsupported format", + "No image generated yet": "No image generated yet", + "Use the AI panel on the left to generate an image": "Use the AI panel on the left to generate an image", + "Search Images": "Search Images", + "Something went wrong. Please try again": "Something went wrong. Please try again", + "Provider": "Provider", + "Search": "Search", + "eg. bakery shop": "eg. bakery shop", + "Search for images to get started": "Search for images to get started", + "Use Image": "Use Image", + "No images found for your search": "No images found for your search", + "Preview Image": "Preview Image", + "@": "@", + "This image will be added to your website assets": "This image will be added to your website assets", + "All available language page is created.": "All available language page is created.", + "Choose language": "Choose language", + "Choose language to add slug": "Choose language to add slug", + "Enter page name": "Enter page name", + "This page will use dynamic slug as defined in primary page": "This page will use dynamic slug as defined in primary page", + "Leave empty for home page": "Leave empty for home page", + "Add new language page": "Add new language page", + "A page for this language already exists.": "A page for this language already exists.", + "You need to create the": "You need to create the", + "page in the parent to add here.": "page in the parent to add here.", + "Edit language": "Edit language", + "Enter the details for the language": "Enter the details for the language", + "Switch to default language": "Switch to default language", + "Add language": "Add language", + "View languages": "View languages", + "Manage Languages": "Manage Languages", + "Page missing for": "Page missing for", + "language": "language", + "Page is not available in the": "Page is not available in the", + "language. Either create the page in the": "language. Either create the page in the", + "language or switch to the base language.": "language or switch to the base language.", + "this page": "this page", + "No issues found": "No issues found", + "This page has no validation errors or warnings.": "This page has no validation errors or warnings.", + "Monthly Credits": "Monthly Credits", + "Lifetime Credits": "Lifetime Credits", + "Add-on Credits": "Add-on Credits", + "Never expire": "Never expire", + "Total purchased": "Total purchased", + "Remaining": "Remaining", + "Total Available": "Total Available", + "Active in Another Tab": "Active in Another Tab", + "This page is currently being edited in another tab. You can continue editing here, which will close the editor in the other tab.": "This page is currently being edited in another tab. You can continue editing here, which will close the editor in the other tab.", + "Continue Editing Here": "Continue Editing Here", + "A team member": "A team member", + "AI is editing this page": "AI is editing this page", + "Editing is paused so your changes and the AI's changes don't overwrite each other.": "Editing is paused so your changes and the AI's changes don't overwrite each other.", + "Started by": "Started by", + "via {{tokenLabel}}": "via {{tokenLabel}}", + "AI editing since": "AI editing since", + "Last activity": "Last activity", + "Last action": "Last action", + "Stay on this page: it checks again every 30 to 90 seconds and reloads with the AI's changes as soon as the session ends. Sessions end automatically 5 minutes after the AI's last change.": "Stay on this page: it checks again every 30 to 90 seconds and reloads with the AI's changes as soon as the session ends. Sessions end automatically 5 minutes after the AI's last change.", + "Check now": "Check now", + "Handing this page over to AI...": "Handing this page over to AI...", + "Your changes could not be saved, so the page stays with you. The AI was told.": "Your changes could not be saved, so the page stays with you. The AI was told.", + "AI wants to edit this page": "AI wants to edit this page", + "{{name}}'s AI session ({{tokenLabel}}) asks to edit this page.": "{{name}}'s AI session ({{tokenLabel}}) asks to edit this page.", + "{{name}}'s AI session asks to edit this page.": "{{name}}'s AI session asks to edit this page.", + "Hand it over: your changes are saved and editing pauses until the AI finishes, then the page reloads with its changes.": "Hand it over: your changes are saved and editing pauses until the AI finishes, then the page reloads with its changes.", + "Keep editing: the AI is told the page is busy and does not change it.": "Keep editing: the AI is told the page is busy and does not change it.", + "Keep editing": "Keep editing", + "Hand over to AI": "Hand over to AI", + "No answer in {{seconds}} s keeps the page with you.": "No answer in {{seconds}} s keeps the page with you.", + "You can edit the page now": "You can edit the page now", + "This page is released by other user you can continue editing now": "This page is released by other user you can continue editing now", + "Page Locked for Editing": "Page Locked for Editing", + "Take Over Options": "Take Over Options", + "Take Over Request:": "Take Over Request:", + "Send a request to {{currentEditorName}} asking them to release the page. They can accept or decline your request.": "Send a request to {{currentEditorName}} asking them to release the page. They can accept or decline your request.", + "Request sent. If no response, try again or use force take over.": "Request sent. If no response, try again or use force take over.", + "Force Take Over": "Force Take Over", + "Immediately take control (use with caution)": "Immediately take control (use with caution)", + "I understand this will immediately close the editor for {{currentEditorName}}. I am using this option with caution.": "I understand this will immediately close the editor for {{currentEditorName}}. I am using this option with caution.", + "Attempting to forcefully take over this page. Please wait while we update the editing session.": "Attempting to forcefully take over this page. Please wait while we update the editing session.", + "Take Over Requested": "Take Over Requested", + "has requested to": "has requested to", + "editing this page.": "editing this page.", + "Do you want to allow them to continue?": "Do you want to allow them to continue?", + "Accept": "Accept", + "Reject": "Reject", + "From": "From", + "To": "To", + "Permanent": "Permanent", + "· returns 308 instead of 307": "· returns 308 instead of 307", + "· returns 307 instead of 308": "· returns 307 instead of 308", + "Enabled": "Enabled", + "Remove redirect?": "Remove redirect?", + "Are you sure you want to remove the redirect from": "Are you sure you want to remove the redirect from", + "Forward visitors from old paths to new ones. Changes take effect immediately.": "Forward visitors from old paths to new ones. Changes take effect immediately.", + "Redirects forward visitors from old paths to new ones. You have read-only access.": "Redirects forward visitors from old paths to new ones. You have read-only access.", + "1 rule": "1 rule", + "rules": "rules", + "of": "of", + "No redirects yet": "No redirects yet", + "Permanent (308) redirects get cached by browsers.": "Permanent (308) redirects get cached by browsers.", + "Redirects": "Redirects", + "Back to history": "Back to history", + "Revision": "Revision", + "Restoring this version": "Restoring this version", + "Matches the current tokens.": "Matches the current tokens.", + "Adds": "Adds", + "Changes": "Changes", + "Removes": "Removes", + "This revision has no tokens.": "This revision has no tokens.", + "archived": "archived", + "Restore this version": "Restore this version", + "Revision history": "Revision history", + "View revision history": "View revision history", + "Revisions": "Revisions", + "View revisions": "View revisions", + "{{label}} history": "{{label}} history", + "Theme history": "Theme history", + "History": "History", + "Back to theme history": "Back to theme history", + "This revision has no theme values.": "This revision has no theme values.", + "Every change to the {{noun}} is kept here, separately from the theme. Restoring keeps the current {{noun}} as a new revision unless you discard them.": "Every change to the {{noun}} is kept here, separately from the theme. Restoring keeps the current {{noun}} as a new revision unless you discard them.", + "No revisions yet. Change a token to create one.": "No revisions yet. Change a token to create one.", + "theme": "theme", + "Every theme save is kept here. Restoring keeps the current theme as a new revision unless you discard it.": "Every theme save is kept here. Restoring keeps the current theme as a new revision unless you discard it.", + "No theme revisions yet. Save a theme change to create one.": "No theme revisions yet. Save a theme change to create one.", + "No theme values": "No theme values", + "Search trash...": "Search trash...", + "Search archive...": "Search archive...", + "Search recycle bin...": "Search recycle bin...", + "Title": "Title", + "Restore": "Restore", + "Delete Permanently": "Delete Permanently", + "Are you sure you want to permanently delete": "Are you sure you want to permanently delete", + "This action cannot be undone.": "This action cannot be undone.", + "Restore Item": "Restore Item", + "Are you sure you want to restore": "Are you sure you want to restore", + "Show more": "Show more", + "Styles": "Styles", + "settings": "settings", + "{{label}} (current)": "{{label}} (current)", + "{{action}} {{label}}": "{{action}} {{label}}", + "No preview": "No preview", + "Current": "Current", + "Choose {{label}}": "Choose {{label}}", + "Search layouts": "Search layouts", + "No layouts match “{{query}}”.": "No layouts match “{{query}}”.", + "Table": "Table", + "table": "table", + "Table Head": "Table Head", + "TableHead": "TableHead", + "Table Body": "Table Body", + "TableBody": "TableBody", + "Table Row": "Table Row", + "TableRow": "TableRow", + "Table Cell": "Table Cell", + "TableCell": "TableCell", + "Content": "Content", + "basic": "basic", + "div": "div", + "header": "header", + "footer": "footer", + "section": "section", + "article": "article", + "aside": "aside", + "main": "main", + "nav": "nav", + "figure": "figure", + "details": "details", + "summary": "summary", + "dialog": "dialog", + "strike": "strike", + "caption": "caption", + "legend": "legend", + "figcaption": "figcaption", + "mark": "mark", + "Image quality": "Image quality", + "Default suits photos. Pick High for banners or any image with text on it: Default blurs small text.": "Default suits photos. Pick High for banners or any image with text on it: Default blurs small text.", + "Default (65)": "Default (65)", + "Maximum (100)": "Maximum (100)", + "High (85)": "High (85)", + "Balanced (65)": "Balanced (65)", + "Low (50)": "Low (50)", + "Off — serve original": "Off — serve original", + "Empty Box": "Empty Box", + "EmptyBox": "EmptyBox", + "Button": "Button", + "Button label": "Button label", + "Prefetch Link": "Prefetch Link", + "Icon": "Icon", + "Icon size": "Icon size", + "Icon position": "Icon position", + "Left": "Left", + "Right": "Right", + "Heading": "Heading", + "typography": "typography", + "Level": "Level", + "Paragraph": "Paragraph", + "Span": "Span", + "Rich Text": "Rich Text", + "RichText": "RichText", + "List": "List", + "List Item": "List Item", + "ListItem": "ListItem", + "web_blocks.icon": "web_blocks.icon", + "media": "media", + "Width": "Width", + "Height": "Height", + "Image": "Image", + "Lazy Load": "Lazy Load", + "Off = load right away. Inside a Repeater only the first item loads right away; the rest stay lazy.": "Off = load right away. Inside a Repeater only the first item loads right away; the rest stay lazy.", + "High priority (LCP image)": "High priority (LCP image)", + "Loads right away at high priority, even with Lazy Load on. Use on one image per page: the largest one visible on first paint.": "Loads right away at high priority, even with Lazy Load on. Use on one image per page: the largest one visible on first paint.", + "Mobile Image": "Mobile Image", + "Mobile": "Mobile", + "Mobile Width": "Mobile Width", + "Mobile Height": "Mobile Height", + "Enter alt text": "Enter alt text", + "Enter width": "Enter width", + "Enter height": "Enter height", + "Video source": "Video source", + "Video Title": "Video Title", + "Video URL": "Video URL", + "Poster URL": "Poster URL", + "Controls": "Controls", + "Autoplay": "Autoplay", + "Show Controls": "Show Controls", + "Loop Video": "Loop Video", + "Muted": "Muted", + "Youtube Video URL": "Youtube Video URL", + "Vimeo Video URL": "Vimeo Video URL", + "Enter Video URL": "Enter Video URL", + "Enter poster URL": "Enter poster URL", + "Custom HTML": "Custom HTML", + "advanced": "advanced", + "CustomHTML": "CustomHTML", + "Custom Script": "Custom Script", + "CustomScript": "CustomScript", + "Script": "Script", + "Runs after the visitor first scrolls, taps or presses a key, or 10 s after the page has loaded and gone idle. Add data-load=\"load\" to a Title', + limit: "12", + featured: "true", + styles: "dt#content-gutter-y bg-primary", + }, + }, + { + blockId: "link-1", + props: { + content: "About Us", + link: { type: "page", href: "/about", target: "_self" }, + }, + }, + ], + { resolveInternalLink }, + ); + + expect(updated).not.toHaveProperty("error"); + if (!("error" in updated)) { + const hero = updated.blocks.find((b) => b._id === "hero-1")!; + expect(hero.heading).toBe("New Title"); + expect(hero.limit).toBe(12); + expect(hero.featured).toBe(true); + expect(hero.styles).toBe("#styles:,dt#content-gutter-y bg-primary"); + + const link = updated.blocks.find((b) => b._id === "link-1")!; + expect(link.content).toBe("About Us"); + expect((link.link as any).href).toBe("pageType:page:p-about"); + + expect(updated.updatedBlockIds).toEqual(["hero-1", "link-1"]); + expect(updated.updatedBlocks).toHaveLength(2); + } + + // Explicit #styles: prefix is preserved verbatim + const explicitStyle = applyUpdateBlockProps(initial, [ + { blockId: "hero-1", props: { styles: "#styles:dt#card,p-8" } }, + ]); + expect(explicitStyle).not.toHaveProperty("error"); + if (!("error" in explicitStyle)) { + expect(explicitStyle.blocks[0]!.styles).toBe("#styles:dt#card,p-8"); + } + + // Reserved keys, unknown bids, and empty props fail cleanly + expect(applyUpdateBlockProps(initial, [{ blockId: "hero-1", props: { _type: "Box" } }])).toEqual( + expect.objectContaining({ error: expect.stringContaining('reserved property "_type"') }), + ); + expect(applyUpdateBlockProps(initial, [{ blockId: "missing", props: { heading: "X" } }])).toEqual( + expect.objectContaining({ error: expect.stringContaining('No block with bid "missing"') }), + ); + expect(applyUpdateBlockProps(initial, [{ blockId: "hero-1", props: {} }])).toEqual( + expect.objectContaining({ error: expect.stringContaining("at least one prop") }), + ); + }); + test("bind_prop validates existence, reserved props, and advertised paths", () => { const paths = { global: ["site.name"], page: ["product.title"] }; const bound = applyBindProp(baseBlocks(), "target", "content", "{{product.title}}", { diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts index 551947aca..3dce80345 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts @@ -1,6 +1,6 @@ import { canDeleteBlock } from "~/builder/core/functions/block-helpers"; import { generateUuid } from "~/builder/core/functions/common-functions"; -import { getRegisteredChaiBlocks, getRegisteredChaiBlock } from "~/registry"; +import { getRegisteredChaiBlocks, getRegisteredChaiBlock, syncChaiBlocksWithDefaultProps } from "~/registry"; import { hasOnlyRegisteredChaiPipes, isValidBindingTemplate, parseBindingExpression } from "~/render/binding-pipes"; import type { ChaiBlock } from "~/types/common"; import { @@ -10,6 +10,7 @@ import { replaceBlock, } from "~/utils/blocks-tree-ops"; import { getBlocksFromHTML, mergeBlocksWithExisting } from "~/utils/import-html/html-to-json"; +import { restoreBlockPropTypes } from "~/utils/import-html/restore-block-prop-types"; import { rewriteInternalLinks, rewriteInternalLinksInProps, @@ -29,6 +30,7 @@ export type AiEditExecutorOptions = { * text content (never resolved at render) is turned back into a path. */ resolveInternalLink?: InternalLinkResolver; + hiddenBlockTypes?: string[]; }; export type AiEditExecutorSuccess = { @@ -36,12 +38,19 @@ export type AiEditExecutorSuccess = { newBlockIds?: string[]; replacementBlocks?: ChaiBlock[]; insertedBlocks?: ChaiBlock[]; + updatedBlocks?: Array<{ _id: string } & Partial>; + updatedBlockIds?: string[]; parentId?: string; position?: number; removableIds?: string[]; skippedIds?: string[]; }; +export type BlockPropsUpdate = { + blockId: string; + props: Record; +}; + export type AiEditExecutorResult = AiEditExecutorSuccess | { error: string }; export const RESERVED_AI_PROPS = new Set([ @@ -317,10 +326,10 @@ export const applyAddBlocks = async ( }; }; -const validCustomBlockTypes = (): string[] => +const validCustomBlockTypes = (hiddenSet?: Set): string[] => Object.entries(getRegisteredChaiBlocks()) .map(([registryKey, block]) => block.type ?? registryKey) - .filter((type): type is string => typeof type === "string" && type.length > 0) + .filter((type): type is string => typeof type === "string" && type.length > 0 && !hiddenSet?.has(type)) .sort(); export const applyAddCustomBlock = ( @@ -331,8 +340,9 @@ export const applyAddCustomBlock = ( props: Record = {}, options: AiEditExecutorOptions = {}, ): AiEditExecutorResult => { - if (!getRegisteredChaiBlock(type)) { - const validTypes = validCustomBlockTypes(); + const hiddenSet = Array.isArray(options.hiddenBlockTypes) ? new Set(options.hiddenBlockTypes) : undefined; + if (hiddenSet?.has(type) || !getRegisteredChaiBlock(type)) { + const validTypes = validCustomBlockTypes(hiddenSet); return { error: `Unknown block type "${type}". Valid types: ${validTypes.length > 0 ? validTypes.join(", ") : "none registered"}.`, }; @@ -344,20 +354,222 @@ export const applyAddCustomBlock = ( if ("error" in target) return target; const sanitizedProps = sanitizeAiProps(props); - const block: ChaiBlock = { - _id: generateUuid(), - _type: type, - _parent: target.parentId, - ...(options.resolveInternalLink - ? rewriteInternalLinksInProps(sanitizedProps, options.resolveInternalLink) - : sanitizedProps), + const rootProps = options.resolveInternalLink + ? rewriteInternalLinksInProps(sanitizedProps, options.resolveInternalLink) + : sanitizedProps; + const insertedBlocks = buildCustomBlockTree(type, rootProps).map((block) => + block._parent ? block : { ...block, _parent: target.parentId }, + ); + return { + blocks: insertBlocksAtPosition(blocks, insertedBlocks, target.parentId, target.position), + insertedBlocks, + parentId: target.parentId, + position: target.position, + newBlockIds: insertedBlocks.map((block) => block._id), }; +}; + +/** + * A custom block as manual Add inserts it: its registered `blocks` template (slots, starter + * children) or the lone block, with fresh ids, `rootProps` on the root, registered defaults + * (styles etc.) filling every prop not set, and schema-typed prop coercion applied. + */ +export const buildCustomBlockTree = (type: string, rootProps: Record): ChaiBlock[] => { + const { blocks } = (getRegisteredChaiBlock(type) ?? {}) as { blocks?: ChaiBlock[] | (() => ChaiBlock[]) }; + const template = (typeof blocks === "function" ? blocks() : blocks) ?? []; + const templateIds = new Set(template.map((block) => block._id).filter(Boolean)); + // The root is the block of this type with no parent inside the template. + const rootIndex = template.findIndex( + (block) => block._type === type && !(block._parent && templateIds.has(block._parent)), + ); + const tree = + rootIndex < 0 + ? [{ _type: type } as ChaiBlock] + : [template[rootIndex], ...template.filter((_, index) => index !== rootIndex)]; + // One id per block; template ids only map parents, so a missing or repeated _id can't collide. + const newIds = tree.map(() => generateUuid()); + const idMap = new Map(); + tree.forEach((block, index) => { + if (block._id && !idMap.has(block._id)) idMap.set(block._id, newIds[index]); + }); + return restoreBlockPropTypes( + syncChaiBlocksWithDefaultProps( + tree.map((block, index) => ({ + ...block, + ...(index === 0 ? rootProps : {}), + _id: newIds[index], + _type: block._type, + // A parent outside the template falls back to the root rather than escaping it. + _parent: index === 0 || !block._parent ? null : (idMap.get(block._parent) ?? newIds[0]), + })), + ), + { htmlBooleanEmpty: false }, + ); +}; + +/** + * Insert a reusable library block (either stored `ChaiBlock[]` JSON or raw HTML) + * into a page with fresh block IDs, default props, hidden-type enforcement, and + * internal-link rewriting. Shared by Builder AI and MCP `add_library_block`. + */ +export const applyAddLibraryBlocks = async ( + blocks: ChaiBlock[], + libraryContent: ChaiBlock[] | string, + parentIdInput?: unknown, + positionInput?: unknown, + options: AiEditExecutorOptions = {}, +): Promise => { + const rawTemplate = + typeof libraryContent === "string" + ? await getBlocksFromHTML(libraryContent) + : Array.isArray(libraryContent) + ? libraryContent + : []; + const validTemplate = rawTemplate.filter( + (block): block is ChaiBlock => Boolean(block && typeof block === "object" && typeof block._type === "string"), + ); + if (validTemplate.length === 0) { + return { error: "Library block contains no valid blocks." }; + } + + const hiddenSet = Array.isArray(options.hiddenBlockTypes) ? new Set(options.hiddenBlockTypes) : undefined; + if (hiddenSet) { + const disallowed = validTemplate.find((block) => hiddenSet.has(block._type)); + if (disallowed) { + return { error: `Library block uses "${disallowed._type}", which is not available on this site or page.` }; + } + } + + const parentId = normalizeAiParentId(parentIdInput); + const position = normalizeAiPosition(positionInput); + const target = resolveInsertTarget(blocks, validTemplate[0]._type, parentId, position); + if ("error" in target) return target; + + // Remap all internal _id / _parent pointers to fresh UUIDs so repeated insertions never collide. + const newIds = validTemplate.map(() => generateUuid()); + const idMap = new Map(); + validTemplate.forEach((block, index) => { + if (block._id && !idMap.has(block._id)) idMap.set(block._id, newIds[index]); + }); + + const remapped = syncChaiBlocksWithDefaultProps( + validTemplate.map((block, index) => { + const next: ChaiBlock = { + ...block, + _id: newIds[index], + _parent: block._parent && idMap.has(block._parent) ? idMap.get(block._parent)! : target.parentId, + }; + delete (next as Record)._bid; + return next; + }), + ); + + const insertedBlocks = options.resolveInternalLink + ? rewriteInternalLinks(remapped, options.resolveInternalLink) + : remapped; + return { - blocks: insertBlocksAtPosition(blocks, [block], target.parentId, target.position), - insertedBlocks: [block], + blocks: insertBlocksAtPosition(blocks, insertedBlocks, target.parentId, target.position), + insertedBlocks, parentId: target.parentId, position: target.position, - newBlockIds: [block._id], + newBlockIds: insertedBlocks.map((block) => block._id), + }; +}; + +/** + * Patch props on one or more existing blocks directly in `ChaiBlock[]` JSON + * without an HTML round-trip. Validates the entire batch atomically, rejects + * reserved structural keys, sanitizes strings/nested values, preserves `#styles:` + * encoding on style props, rewrites internal page links, and coerces prop types + * against each block's registered schema. + */ +export const applyUpdateBlockProps = ( + blocks: ChaiBlock[], + updates: BlockPropsUpdate[], + options: AiEditExecutorOptions = {}, +): AiEditExecutorResult => { + if (!Array.isArray(updates) || updates.length === 0) { + return { error: "update_block_props requires a non-empty updates array." }; + } + + const nextById = new Map(blocks.map((block) => [block._id, block])); + const patchById = new Map>(); + const updatedOrder: string[] = []; + + for (const entry of updates) { + const blockId = typeof entry?.blockId === "string" ? entry.blockId.trim() : ""; + if (!blockId || !nextById.has(blockId)) { + return { error: `No block with bid "${blockId}" — call get_page_outline for valid bids.` }; + } + if (!entry.props || typeof entry.props !== "object" || Array.isArray(entry.props)) { + return { error: `update_block_props requires a props object for block "${blockId}".` }; + } + const rawKeys = Object.keys(entry.props); + if (rawKeys.length === 0) { + return { error: `update_block_props requires at least one prop to update for block "${blockId}".` }; + } + + for (const key of rawKeys) { + if (RESERVED_AI_PROPS.has(key)) { + return { error: `Cannot update reserved property "${key}" on block "${blockId}".` }; + } + } + + const current = nextById.get(blockId)!; + if (current._type === "PartialBlock" || current._type === "GlobalBlock") { + const nextPartialId = entry.props.partialBlockId ?? entry.props.globalBlock; + if (typeof nextPartialId === "string" && nextPartialId.trim().length > 0) { + const partialErr = options.validatePartialReference?.(nextPartialId); + if (partialErr) return { error: partialErr }; + } + } + + const sanitized = sanitizeAiProps(entry.props); + const normalized: Record = {}; + for (const [key, value] of Object.entries(sanitized)) { + const existingVal = current[key]; + const isStyleProp = + (typeof existingVal === "string" && existingVal.startsWith("#styles:")) || + key === "styles" || + key.endsWith("Styles"); + if (isStyleProp && typeof value === "string") { + const trimmed = value.trim(); + normalized[key] = trimmed.startsWith("#styles:") ? trimmed : `#styles:,${trimmed}`; + } else { + normalized[key] = value; + } + } + + const withLinks = options.resolveInternalLink + ? rewriteInternalLinksInProps(normalized, options.resolveInternalLink) + : normalized; + + const mergedRaw: ChaiBlock = { ...current, ...withLinks }; + const [coerced] = restoreBlockPropTypes([mergedRaw], { htmlBooleanEmpty: false }); + const updatedBlock = coerced ?? mergedRaw; + nextById.set(blockId, updatedBlock); + + if (!patchById.has(blockId)) { + updatedOrder.push(blockId); + patchById.set(blockId, {}); + } + const acc = patchById.get(blockId)!; + for (const key of Object.keys(withLinks)) { + acc[key] = updatedBlock[key]; + } + } + + const nextBlocks = blocks.map((block) => nextById.get(block._id) ?? block); + const updatedBlocks = updatedOrder.map( + (blockId) => ({ _id: blockId, ...patchById.get(blockId)! }) as { _id: string } & Partial, + ); + + return { + blocks: nextBlocks, + updatedBlocks, + updatedBlockIds: updatedOrder, + newBlockIds: updatedOrder, }; }; diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.test.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.test.ts index c67720c27..f643f8ea2 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.test.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.test.ts @@ -3,11 +3,15 @@ import { MockLanguageModelV3 } from "ai/test"; import { afterEach, describe, expect, it } from "vitest"; import { z } from "zod"; import { registerChaiBlock } from "~/registry"; +import { getChaiActionInstance } from "~/server/chai-actions/actions-registery"; import { getActiveChaiBuilderConfig } from "~/server/defaults/config-registry"; import { registerChaiAiCustomization, resetChaiAiCustomizersForTests } from "~/server/plugin-api/ai-customization"; import { useTestChaiConfig, withChaiConfig } from "~/tests/setup/chai-config"; +import { loadWebBlocks } from "~/web-blocks"; import { AIEditPageAction } from "./ai-edit-page-action"; +loadWebBlocks(); + // A real registered custom block, so the prompt's custom block catalog lists it. registerChaiBlock( (() => null) as any, @@ -74,9 +78,9 @@ function useScriptedModel(steps: StreamPart[][] = []) { } /** Runs the action as the dispatcher would and drains the streamed response. */ -async function run(data: Record) { +async function run(data: Record, contextOverrides: Record = {}) { const action = new AIEditPageAction(); - action.setContext({ action: "AI_EDIT_PAGE", userId: "u1", appId: "a1" }); + action.setContext({ action: "AI_EDIT_PAGE", userId: "u1", appId: "a1", ...contextOverrides } as any); const result = await action.execute({ model: "test-model", ...data } as any); const body = await result._streamResult.dataStream.text(); return { result, body }; @@ -167,6 +171,21 @@ describe("AIEditPageAction (tool-call / UIMessage flow)", () => { expect(system).not.toContain("{{DESIGN_TOKENS_LIST}}"); }); + it("omits options.hiddenBlockTypes from the custom block catalog", async () => { + const calls = useScriptedModel(); + await run({ + messages: [userMessage("m1", "hello")], + pageOutline: "box-1 | Box | Hero Section", + pageHtml: "
", + options: { + hiddenBlockTypes: ["ProductCard"], + }, + }); + + const system = systemOf(calls[0]); + expect(system).not.toContain("### ProductCard"); + }); + it("exposes the full tool set with read_block_html bound to the request pageHtml", async () => { const calls = useScriptedModel([toolCallStep("read_block_html", { blockIds: ["hero-1"] })]); await run({ @@ -174,16 +193,29 @@ describe("AIEditPageAction (tool-call / UIMessage flow)", () => { pageHtml: "

Hi

", }); - expect(toolNamesOf(calls[0])).toEqual([ - "add_blocks", - "add_custom_block", - "bind_prop", - "edit_block", - "get_pages_list", - "get_partial_blocks", - "read_block_html", - "remove_blocks", - ]); + const hasLibraryActions = Boolean( + getChaiActionInstance("GET_LIBRARIES") && + getChaiActionInstance("GET_LIBRARY_ITEMS") && + getChaiActionInstance("GET_LIBRARY_ITEM"), + ); + const hasMediaActions = Boolean(getChaiActionInstance("CREATE_ASSET")); + + expect(toolNamesOf(calls[0])).toEqual( + [ + "add_blocks", + "add_custom_block", + "bind_prop", + "edit_block", + "get_pages_list", + "get_partial_blocks", + "read_block_html", + "read_blocks", + "remove_blocks", + "update_block_props", + ...(hasLibraryActions ? ["add_library_block", "get_library_blocks"] : []), + ...(hasMediaActions ? ["upload_image"] : []), + ].sort(), + ); // The server executed read_block_html and handed the slice back to the model. expect(calls).toHaveLength(2); @@ -321,7 +353,14 @@ describe("AIEditPageAction (tool-call / UIMessage flow)", () => { // get_pages_list is a read-only lookup: linking one button is still a single-block edit. it("hands the model read, edit and scoped binding tools", async () => { const calls = await executeScoped(); - expect(toolNamesOf(calls[0])).toEqual(["bind_prop", "edit_block", "get_pages_list", "read_block_html"]); + expect(toolNamesOf(calls[0])).toEqual([ + "bind_prop", + "edit_block", + "get_pages_list", + "read_block_html", + "read_blocks", + "update_block_props", + ]); }); it("states the single-block scope in the system prompt", async () => { @@ -349,4 +388,137 @@ describe("AIEditPageAction (tool-call / UIMessage flow)", () => { expect(slices["hero-1"]).toBeUndefined(); }); }); + + describe("JSON blocks, language view & design system parity", () => { + it("derives page outline and language-view read_block_html directly from JSON blocks", async () => { + const calls = useScriptedModel([toolCallStep("read_block_html", { blockIds: ["h-1"] })]); + await run({ + messages: [userMessage("m1", "Edit heading")], + blocks: [ + { _id: "sec-1", _type: "Box", _name: "Hero", styles: "#styles:,p-8" }, + { + _id: "h-1", + _type: "Heading", + _parent: "sec-1", + tag: "h1", + content: "Hello", + "content-fr": "Bonjour", + styles: "#styles:,text-3xl", + }, + ], + pageId: "page-fr", + primaryPageId: "page-en", + pageName: "Accueil", + pageSlug: "/fr", + lang: "fr", + fallbackLang: "en", + variantLangs: ["fr"], + }); + + const system = systemOf(calls[0]); + // Outline was derived server-side from JSON blocks in the French language view + expect(system).toContain("sec-1 | Box | Hero"); + expect(system).toContain("Bonjour"); + expect(system).toContain("French (fr)"); + expect(toolNamesOf(calls[0])).toContain("get_page_blocks"); + expect(toolNamesOf(calls[0])).toContain("get_block_translations"); + expect(toolNamesOf(calls[0])).toContain("update_block_translations"); + expect(toolNamesOf(calls[0])).toContain("get_page_seo"); + expect(toolNamesOf(calls[0])).toContain("update_page_seo"); + + const slices = toolResultsOf(calls[1]).read_block_html as Record; + expect(slices["h-1"]).toContain("Bonjour"); + }); + + it("hides design-system prompt sections when feature is disabled and advertises them when enabled", async () => { + const offCalls = useScriptedModel(); + await run({ + messages: [userMessage("m1", "hi")], + blocks: [{ _id: "b1", _type: "Box" }], + }); + expect(systemOf(offCalls[0])).not.toContain("## Design System"); + expect(toolNamesOf(offCalls[0])).not.toContain("get_design_system"); + + const onCalls = useScriptedModel(); + withChaiConfig({ + features: { + ...getActiveChaiBuilderConfig().features, + aiCredits: false, + designSystem: { enabled: true, designChecks: "warn" }, + } as never, + }); + await run({ + messages: [userMessage("m1", "hi")], + blocks: [{ _id: "b1", _type: "Box" }], + }); + expect(systemOf(onCalls[0])).toContain("## Design System"); + expect(toolNamesOf(onCalls[0])).toContain("get_design_system"); + expect(toolNamesOf(onCalls[0])).toContain("check_page_design"); + expect(toolNamesOf(onCalls[0])).toContain("get_design_guide"); + }); + + it("enforces action-level userAccess and delegatedPermissions (Library Page Editor clamp)", async () => { + const calls = useScriptedModel(); + withChaiConfig({ + features: { + ...getActiveChaiBuilderConfig().features, + aiCredits: false, + designSystem: { enabled: true, designChecks: "warn" }, + } as never, + }); + + // Library Page Editor permissions: ["ai:use", "ai:read"] — no pages:* / theme:* / assets:* + await run( + { + messages: [userMessage("m1", "edit hero")], + blocks: [{ _id: "b1", _type: "Box" }], + pageId: "lib-1", + }, + { userAccess: { role: "editor", permissions: ["ai:use", "ai:read"] } }, + ); + + expect(toolNamesOf(calls[0])).toEqual([ + "add_blocks", + "add_custom_block", + "bind_prop", + "edit_block", + "read_block_html", + "read_blocks", + "remove_blocks", + "update_block_props", + ]); + // Prompt omits sections whose tools are unavailable + expect(systemOf(calls[0])).not.toContain("Call `get_pages_list`"); + expect(systemOf(calls[0])).not.toContain("get_partial_blocks"); + + // Delegated permissions clamp further restricts granted permissions + const clampedCalls = useScriptedModel(); + await run( + { + messages: [userMessage("m1", "edit hero")], + blocks: [{ _id: "b1", _type: "Box" }], + pageId: "p1", + }, + { + userAccess: { + role: "admin", + permissions: ["ai:use", "ai:read", "pages:read", "pages:update", "pages:edit_seo"], + }, + delegatedPermissions: ["ai:use", "pages:read"], + }, + ); + expect(toolNamesOf(clampedCalls[0])).toContain("get_pages_list"); + expect(toolNamesOf(clampedCalls[0])).toContain("get_page_seo"); + expect(toolNamesOf(clampedCalls[0])).not.toContain("update_page_seo"); + }); + + it("preserves $-sequences in page outline copy without regex replacement expansion", async () => { + const calls = useScriptedModel(); + await run({ + messages: [userMessage("m1", "hi")], + blocks: [{ _id: "h1", _type: "Heading", tag: "h1", content: "Save $100 with $$ and $& promo" }], + }); + expect(systemOf(calls[0])).toContain("Save $100 with $$ and $& promo"); + }); + }); }); diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts index fb1b48ec3..782f528fe 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts @@ -1,10 +1,23 @@ import { convertToModelMessages, UIMessage, stepCountIs } from "ai"; import { z } from "zod"; +import { buildPageOutlineForAi } from "~/builder/pages/panels/ai-panel/page-outline-for-ai"; import { AI_OMITTED_HTML_SENTINEL } from "~/constants/AI_TOOL_HISTORY"; +import { getRegisteredChaiFonts } from "~/registry"; import { throwAiChatError } from "~/server/chai-actions/ai/throw-ai-chat-error"; import { AIChatError, AIChatErrorCode } from "~/server/chai-actions/classes/chai-ai-chat-handler"; import { getEditPageToolsSystemPrompt } from "~/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt"; +import { runChaiAction } from "~/server/chai-actions/dispatch-action"; +import { resolveEffectivePermissions } from "~/server/rbac/effective-permissions"; +import { hasChaiPermission } from "~/server/rbac/permissions"; +import type { ChaiBlock } from "~/types/common"; +import { CHAI_DESIGN_SYSTEM_KEY, CHAI_PAGE_DESIGN_BRIEF_KEY } from "~/types/design-system"; +import { describePageLang, getPageLangInfo } from "~/utils/page-lang"; +import { toLanguageView } from "~/utils/page-translations"; import { ChaiAIActionData, ChaiBaseAiAction } from "../../base-ai-action"; +import { composeDesignBrief } from "../design/compose-design-brief"; +import { getDesignSystemFeature } from "../design/feature"; +import { isDesignSystemActive, readChaiDesignSystem, readChaiPageDesignBrief } from "../design-system-schema"; +import { readSiteDesignContextForApp } from "../page-tool-operations"; import { fillAiEditSystemPromptContext } from "./ai-edit-page-prompt-context"; import { buildAiEditPageTools } from "./ai-edit-page-tools"; @@ -25,10 +38,25 @@ const MAX_HISTORY_MESSAGES = 12; type AIEditPageActionData = Omit & { messages: UIMessage[]; + /** Current open page's blocks JSON (preferred — mirrors MCP's JSON state). */ + blocks?: ChaiBlock[]; + /** Legacy fallback HTML string when `blocks` is not provided. */ pageHtml?: string; pageOutline?: string; - /** Id of the page being edited — used to enforce partial nesting rules. */ + /** Active page row id (language variant row id on a variant, primary id on primary). */ pageId?: string; + /** Primary page id (defaults to `pageId`). */ + primaryPageId?: string; + pageName?: string; + pageSlug?: string; + /** Active language code ("" or fallbackLang on primary page, e.g. "fr" on variant). */ + lang?: string; + fallbackLang?: string; + /** Non-fallback languages configured for this page / site. */ + variantLangs?: string[]; + /** All configured non-fallback languages on the site. */ + languages?: string[]; + isPartial?: boolean; /** Set by the block floating AI action: confine the whole run to this bid. */ scopedBlockId?: string; }; @@ -39,10 +67,17 @@ export type AIEditPageStreamResponse = { }; /** - * Strip the (potentially huge) `html` tool inputs from all but the last - * assistant message. The current page state is always readable via the - * read_block_html tool, so stale HTML snapshots in history are dead weight. + * Strip large tool inputs/outputs from all but the last assistant message so + * multi-turn conversations and auto-continue steps stay compact. Current page + * state is always readable via read_block_html / get_page_blocks. */ +const PRUNED_OUTPUT_TOOLS = new Set([ + "tool-get_page_blocks", + "tool-read_blocks", + "tool-read_block_html", + "tool-get_block_translations", +]); + const pruneHistoryToolInputs = (messages: UIMessage[]): UIMessage[] => { const lastAssistantIndex = messages.findLastIndex((m) => m.role === "assistant"); return messages.map((message, index) => { @@ -52,29 +87,30 @@ const pruneHistoryToolInputs = (messages: UIMessage[]): UIMessage[] => { return { ...message, parts: message.parts.map((part: any) => { - if ( - typeof part?.type === "string" && - (part.type === "tool-edit_block" || part.type === "tool-add_blocks") && - part.input?.html - ) { + if (typeof part?.type !== "string") return part; + if ((part.type === "tool-edit_block" || part.type === "tool-add_blocks") && part.input?.html) { return { ...part, input: { ...part.input, html: AI_OMITTED_HTML_SENTINEL } }; } + if (PRUNED_OUTPUT_TOOLS.has(part.type) && part.state === "output-available" && part.output !== undefined) { + return { ...part, output: { omitted: true, note: "Previous output omitted; re-read if needed." } }; + } return part; }), }; }); }; +const asRecord = (value: unknown): Record => + typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record) : {}; + /** * Action to handle AI_EDIT_PAGE requests. * - * Streams an AI SDK v6 UIMessage response driven entirely by tool calls - * (edit_block / add_blocks / remove_blocks / add_custom_block / bind_prop - * client-side; read_block_html / get_partial_blocks server-side). - * - * The full page HTML is received per request but kept OUT of the model - * context — the model works from the compact page outline in the system - * prompt and reads block HTML on demand. + * Streams an AI SDK v6 UIMessage response driven by single-page tools synced + * with MCP: operates on `blocks: ChaiBlock[]` JSON (falling back to legacy + * `pageHtml` only when `blocks` is omitted), converts blocks to AI-HTML on + * demand via `blocksToAiHtml`, supports language-variant views, SEO, media + * uploads, and opt-in design system briefs/checks/theme tools. */ export class AIEditPageAction extends ChaiBaseAiAction { protected getValidationSchema() { @@ -83,14 +119,75 @@ export class AIEditPageAction extends ChaiBaseAiAction { + const feature = getDesignSystemFeature(); + if (!feature.enabled) return ""; + if (permissions !== undefined && (!permissions || !hasChaiPermission(permissions, "ai:read"))) return ""; + + try { + const appId = this.context?.appId; + if (!appId) return ""; + const targetPrimaryPageId = data.primaryPageId ?? data.pageId; + const [site, aiContext] = await Promise.all([ + readSiteDesignContextForApp(appId), + runChaiAction("AI_GET_CONTEXT", targetPrimaryPageId ? { pageId: targetPrimaryPageId } : {}) + .then((res) => res as { aiData?: { app?: unknown; page?: unknown } }) + .catch(() => null), + ]); + const app = asRecord(aiContext?.aiData?.app ?? site?.ai); + const pageAi = asRecord(aiContext?.aiData?.page); + const designSystem = readChaiDesignSystem(app[CHAI_DESIGN_SYSTEM_KEY]) ?? site?.designSystem ?? null; + const pageBrief = readChaiPageDesignBrief(pageAi[CHAI_PAGE_DESIGN_BRIEF_KEY]); + + // Only inject into the base prompt when the site design system is active or a page brief exists; + // otherwise the model keeps default styling rules and can call `get_design_system` on demand. + if (!isDesignSystemActive(feature, designSystem) && !pageBrief) return ""; + + return composeDesignBrief({ + siteName: site?.name, + designSystem, + product: app, + theme: site?.theme ?? null, + designTokens: site?.designTokens ?? data.designTokens ?? {}, + fonts: getRegisteredChaiFonts().map((font) => font.family), + page: targetPrimaryPageId + ? { name: data.pageName || "Current Page", slug: data.pageSlug || "", brief: pageBrief } + : null, + checks: feature.designChecks, + }); + } catch { + return ""; + } + } + async execute(data: AIEditPageActionData): Promise { if (!this.context) { throwAiChatError(new AIChatError("Context not set. Please try again.", AIChatErrorCode.INVALID_REQUEST, 500)); @@ -103,15 +200,62 @@ export class AIEditPageAction extends ChaiBaseAiAction outlineText); systemPrompt = fillAiEditSystemPromptContext(systemPrompt, data); + const langNote = describePageLang(langInfo); + if (langNote) { + systemPrompt += `\n\n## Current Page Language\n${langNote}`; + if (!langInfo.isLanguageVariant && data.variantLangs && data.variantLangs.length > 0) { + systemPrompt += `\nThis page has language variants: ${data.variantLangs.join(", ")}. When copy changes, follow any "Translations to sync" list returned by edit tools using update_block_translations.`; + } + } + + const designBriefSection = await this.resolveActiveDesignBriefSection(data, permissions); + if (designBriefSection) { + systemPrompt += `\n\n${designBriefSection}`; + } + if (scopedBlockId) { - // Block-scoped run (block floating AI). The tool set already makes a - // page-wide edit impossible; this tells the model why, so it explains - // the limit instead of silently failing tool calls. systemPrompt += `\n\n## Edit Scope: Single Block (STRICT)\n` + `You are editing ONLY the block with bid "${scopedBlockId}". The page outline above is read-only context.\n` + @@ -133,17 +277,7 @@ export class AIEditPageAction extends ChaiBaseAiAction { expect(catalog).toContain("### Hero"); expect(catalog).not.toContain("### Gallery"); }); + + it("omits blocks listed in hiddenBlockTypes", () => { + const catalog = buildCustomBlockCatalog("product", ["Gallery"]); + expect(catalog).toContain("### Hero"); + expect(catalog).not.toContain("### Gallery"); + }); + + it("ignores non-array hiddenBlockTypes input", () => { + const catalog = buildCustomBlockCatalog("product", "Gallery"); + expect(catalog).toContain("### Hero"); + expect(catalog).toContain("### Gallery"); + }); + + it("annotates multi-block groups so the AI picks ONE when entries are layout variants", () => { + registerChaiBlock(NullComponent, { + type: "FeaturedAltOne", + label: "Featured Alt One", + group: "featured-alt", + description: "First featured layout", + } as any); + registerChaiBlock(NullComponent, { + type: "FeaturedAltTwo", + label: "Featured Alt Two", + group: "featured-alt", + description: "Second featured layout", + } as any); + + const catalog = buildCustomBlockCatalog("page"); + expect(catalog).toContain( + "## Group: featured-alt (2 blocks — pick ONE if these are layout variants of the same section)", + ); + }); }); describe("custom catalog helpers", () => { it("lists the same blocks as the catalog, per page type", () => { - const types = (pageType: string) => getCustomCatalogBlocks(pageType).map(([key, block]) => block.type ?? key); + const types = (pageType: string, hidden?: string[]) => + getCustomCatalogBlocks(pageType, hidden).map(([key, block]) => block.type ?? key); expect(types("page")).toContain("Hero"); expect(types("page")).not.toContain("Gallery"); expect(types("product")).toContain("Gallery"); + expect(types("product", ["Gallery"])).not.toContain("Gallery"); + expect(types("product", ["Gallery"])).toContain("Hero"); expect(types("page")).not.toContain("Box"); }); diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts index e02a82e6b..24dbce124 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts @@ -63,11 +63,22 @@ export const isCustomCatalogBlock = (registryKey: string, block: RegisteredCusto }; /** The custom blocks available on a page type, as `[registryKey, block]` in registry order. */ -export const getCustomCatalogBlocks = (pageType?: string): [string, RegisteredCustomBlock][] => - Object.entries(getRegisteredChaiBlocks()).filter( - ([registryKey, block]) => - isCustomCatalogBlock(registryKey, block) && isBlockAvailableForPageType(block, pageType || "page"), - ); +export const getCustomCatalogBlocks = ( + pageType?: string, + hiddenBlockTypes?: unknown, +): [string, RegisteredCustomBlock][] => { + const hiddenSet = Array.isArray(hiddenBlockTypes) + ? new Set(hiddenBlockTypes.filter((type): type is string => typeof type === "string")) + : null; + return Object.entries(getRegisteredChaiBlocks()).filter(([registryKey, block]) => { + const blockType = block.type ?? registryKey; + return ( + isCustomCatalogBlock(registryKey, block) && + isBlockAvailableForPageType(block, pageType || "page") && + !(hiddenSet && hiddenSet.has(blockType)) + ); + }); +}; /** A prop the AI may set: style, runtime and hidden props are builder-managed. */ export const isCatalogProp = (prop: any): boolean => !prop?.styles && !prop?.runtime && !prop?.hidden; @@ -100,30 +111,50 @@ export const customBlockHtmlOpenTag = (blockType: string): string => { return derived === blockType ? `<${tag}>` : `<${tag} chai-type="${blockType}">`; }; -export const buildCustomBlockCatalog = (pageType?: string): string => { - const customBlockEntries = getCustomCatalogBlocks(pageType); +export const buildCustomBlockCatalog = (pageType?: string, hiddenBlockTypes?: unknown): string => { + const customBlockEntries = getCustomCatalogBlocks(pageType, hiddenBlockTypes); if (customBlockEntries.length === 0) { return "No custom blocks registered."; } - return customBlockEntries - .map(([registryKey, b]) => { - const blockType = b.type ?? registryKey; - const props = b.props?.schema?.properties - ? Object.entries(b.props.schema.properties as Record) - .filter(([, v]) => isCatalogProp(v)) - .map(([key, v]) => { - const type = Array.isArray(v?.type) ? v.type.join("|") : (v?.type ?? "any"); - const def = v?.default !== undefined ? ` (default: ${JSON.stringify(v.default)})` : ""; - const aiNote = b.aiProps?.includes(key) ? " [AI-settable]" : ""; - return ` - ${key} (${type})${def}${aiNote}: ${v?.title ?? key}`; - }) - .join("\n") - : " (no declared props)"; - const wrapperNote = b.wrapper ? " [wrapper — can contain child blocks]" : ""; - // b.description is defined on ChaiBlockConfig — use it as the primary AI hint - return `### ${blockType} → ${customBlockHtmlOpenTag(blockType)}${wrapperNote}\nDescription: ${b.description ?? b.label}\nProps:\n${props}`; + const grouped = new Map(); + for (const entry of customBlockEntries) { + const group = (entry[1].group?.trim() || "general").toLowerCase(); + const list = grouped.get(group); + if (list) list.push(entry); + else grouped.set(group, [entry]); + } + + const formatEntry = ([registryKey, b]: [string, RegisteredCustomBlock]): string => { + const blockType = b.type ?? registryKey; + const props = b.props?.schema?.properties + ? Object.entries(b.props.schema.properties as Record) + .filter(([, v]) => isCatalogProp(v)) + .map(([key, v]) => { + const type = Array.isArray(v?.type) ? v.type.join("|") : (v?.type ?? "any"); + const def = v?.default !== undefined ? ` (default: ${JSON.stringify(v.default)})` : ""; + const aiNote = b.aiProps?.includes(key) ? " [AI-settable]" : ""; + return ` - ${key} (${type})${def}${aiNote}: ${v?.title ?? key}`; + }) + .join("\n") + : " (no declared props)"; + const wrapperNote = b.wrapper ? " [wrapper — can contain child blocks]" : ""; + // b.description is defined on ChaiBlockConfig — use it as the primary AI hint + return `### ${blockType} → ${customBlockHtmlOpenTag(blockType)}${wrapperNote}\nDescription: ${b.description ?? b.label}\nProps:\n${props}`; + }; + + if (grouped.size === 1) { + return customBlockEntries.map(formatEntry).join("\n\n"); + } + + return Array.from(grouped.entries()) + .map(([group, entries]) => { + const heading = + entries.length > 1 + ? `## Group: ${group} (${entries.length} blocks — pick ONE if these are layout variants of the same section)` + : `## Group: ${group}`; + return `${heading}\n\n${entries.map(formatEntry).join("\n\n")}`; }) .join("\n\n"); }; @@ -233,8 +264,7 @@ export const buildPageTypeContext = (pageTypeKey: string | undefined): string => /** * Fill the shared context placeholders of an AI edit system prompt and append - * site/page information. Used by the page-edit action; the block-edit action - * can adopt it when it migrates. + * site/page information. Used by both page-edit and block-edit actions. */ export const fillAiEditSystemPromptContext = ( systemPrompt: string, @@ -242,7 +272,10 @@ export const fillAiEditSystemPromptContext = ( ): string => { let prompt = systemPrompt; prompt = prompt.replace("{{DESIGN_TOKENS_LIST}}", buildDesignTokensList(data.designTokens)); - prompt = prompt.replace("{{CUSTOM_BLOCK_CATALOG}}", buildCustomBlockCatalog(data?.options?.pageType)); + prompt = prompt.replace( + "{{CUSTOM_BLOCK_CATALOG}}", + buildCustomBlockCatalog(data?.options?.pageType, data?.options?.hiddenBlockTypes), + ); prompt = prompt.replace("{{DATA_BINDING_PATHS}}", buildDataBindingPathsText(data?.options?.dataBindingPaths)); prompt = prompt.replace("{{DATA_BINDING_PIPES}}", buildDataBindingPipesText()); prompt = prompt.replace("{{PAGE_TYPE_CONTEXT}}", buildPageTypeContext(data?.options?.pageType)); diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.test.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.test.ts index 26b4dd209..4ce0a2e04 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.test.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.test.ts @@ -1,9 +1,15 @@ import { describe, expect, it } from "vitest"; +import { getActiveChaiBuilderConfig } from "~/server/defaults/config-registry"; +import { useTestChaiConfig, withChaiConfig } from "~/tests/setup/chai-config"; import { withTableUnavailable } from "~/tests/setup/db-faults"; import { schema } from "~/tests/setup/test-db"; import { withTestDB } from "~/tests/setup/transaction-manager"; +import { PARTIAL_TAGS_METADATA_KEY } from "~/types/partial-blocks"; +import { loadWebBlocks } from "~/web-blocks"; import { buildAiEditPageTools, extractBlockHtmlSlices, isValidAiBindingTemplate } from "./ai-edit-page-tools"; +loadWebBlocks(); + const PAGE_HTML = `
@@ -102,19 +108,20 @@ describe("get_pages_list", () => { ]), ); - it("lists routable primary pages with a ready-to-use linkRef", async () => { + it("lists routable pages (including language variants) with ready-to-use linkRef and parent metadata", async () => { await seedPages(); const result = await getPagesList(); expect(result.pages).toEqual([ - { name: "Home", slug: "/", pageType: "page", linkRef: "pageType:page:home" }, - { name: "About", slug: "/about", pageType: "page", linkRef: `pageType:page:${ABOUT_ID}` }, + { id: "home", name: "Home", slug: "/", lang: "en", pageType: "page", parentId: null, parentSlug: null, linkRef: "pageType:page:home" }, + { id: ABOUT_ID, name: "About", slug: "/about", lang: "en", pageType: "page", parentId: null, parentSlug: null, linkRef: `pageType:page:${ABOUT_ID}` }, + { id: "about-fr", name: "À propos", slug: "/fr/a-propos", lang: "fr", pageType: "page", parentId: null, parentSlug: null, linkRef: `pageType:page:${ABOUT_ID}` }, ]); expect(result.note).toContain("linkRef"); }); it("is available to a block-scoped run", async () => { await seedPages(); - expect((await getPagesList("hero-1")).pages).toHaveLength(2); + expect((await getPagesList("hero-1")).pages).toHaveLength(3); }); }); @@ -189,21 +196,53 @@ describe("get_partial_blocks nesting filter", () => { await seedPartials([{ id: "header", name: "Header", partialBlocks: "" }]); await withTestDB(async ({ seed }) => { const otherApp = await seed("apps"); - await seed("appPages", { id: "home", name: "Home", slug: "/home", lang: "" }); - await seed("appPages", { id: "localized", name: "Localized", slug: "", lang: "fr" }); + await seed("appPages", { id: "home", name: "Home", slug: "/home", lang: "", pageType: "global" }); + await seed("appPages", { id: "localized", name: "Localized", slug: "", lang: "fr", pageType: "global" }); await seed("appPages", { id: "trashed", name: "Trashed", slug: "", lang: "", + pageType: "global", deletedAt: new Date().toISOString(), }); - await seed("appPages", { id: "foreign", name: "Foreign", slug: "", lang: "", app: otherApp.id }); + await seed("appPages", { id: "foreign", name: "Foreign", slug: "", lang: "", pageType: "global", app: otherApp.id }); }); const result = await getPartialBlocks("page-1"); expect(Object.keys(result.partials)).toEqual(["header"]); - expect(result.partials.header).toEqual({ name: "Header", description: "", type: "global" }); + expect(result.partials.header).toEqual({ name: "Header", description: "", type: "global", tags: [] }); + }); + + it("excludes slug-less rows whose pageType is not a partial and returns partial tags", async () => { + await withTestDB(async ({ seed }) => { + await seed("appPages", { + id: "nav-partial", + name: "Nav", + slug: "", + lang: "", + pageType: "global", + metadata: { description: "Main nav", [PARTIAL_TAGS_METADATA_KEY]: ["navigation", "header"] }, + }); + // A routable page whose slug hasn't been assigned yet must NOT appear as a partial. + await seed("appPages", { + id: "draft-unrouted", + name: "Draft Page", + slug: "", + lang: "", + pageType: "page", + metadata: {}, + }); + }); + + const result = await getPartialBlocks("page-1"); + expect(Object.keys(result.partials)).toEqual(["nav-partial"]); + expect(result.partials["nav-partial"]).toEqual({ + name: "Nav", + description: "Main nav", + type: "global", + tags: ["navigation", "header"], + }); }); it("surfaces a failed partial lookup", async () => { @@ -212,3 +251,215 @@ describe("get_partial_blocks nesting filter", () => { }); }); }); + +describe("JSON blocks, multilingual, SEO & design-system tools", () => { + const sampleBlocks = [ + { _id: "sec-1", _type: "Box", styles: "#styles:,p-8" }, + { + _id: "h-1", + _type: "Heading", + _parent: "sec-1", + tag: "h1", + content: "Welcome", + "content-fr": "Bienvenue", + styles: "#styles:,text-4xl", + }, + ]; + + it("reads language-view HTML from JSON blocks and raw translations from get_block_translations", async () => { + const tools = buildAiEditPageTools({ + blocks: sampleBlocks, + pageId: "page-fr", + primaryPageId: "page-en", + pageName: "Accueil", + pageSlug: "/fr", + lang: "fr", + fallbackLang: "en", + variantLangs: ["fr"], + }) as any; + + const slices = await tools.read_block_html.execute({ blockIds: ["h-1"] }); + expect(slices["h-1"]).toContain("Bienvenue"); + expect(slices["h-1"]).not.toContain("Welcome"); + + const jsonRead = await tools.read_blocks.execute({ blockIds: ["sec-1"], includeDescendants: true }); + expect(jsonRead.lang).toBe("fr"); + expect(jsonRead.blocks.map((b: any) => b._id)).toEqual(["sec-1", "h-1"]); + expect(jsonRead.blocks.find((b: any) => b._id === "h-1").content).toBe("Bienvenue"); + + const singleRead = await tools.read_blocks.execute({ blockIds: ["sec-1", "missing-id"] }); + expect(singleRead.blocks.map((b: any) => b._id)).toEqual(["sec-1"]); + expect(singleRead.missingIds).toEqual(["missing-id"]); + + const scopedTools = buildAiEditPageTools({ + blocks: sampleBlocks, + scopedBlockId: "sec-1", + lang: "fr", + fallbackLang: "en", + }) as any; + const scopedOk = await scopedTools.read_blocks.execute({ blockIds: ["h-1"] }); + expect(scopedOk.blocks.map((b: any) => b._id)).toEqual(["h-1"]); + const scopedRejected = await scopedTools.read_blocks.execute({ blockIds: ["outside-1"] }); + expect(scopedRejected).toEqual( + expect.objectContaining({ ok: false, error: expect.stringContaining("outside the current edit scope") }), + ); + + const pageBlocks = await tools.get_page_blocks.execute({}); + expect(pageBlocks.lang).toBe("fr"); + expect(pageBlocks.isLanguageVariant).toBe(true); + expect(pageBlocks.blocks.find((b: any) => b._id === "h-1").content).toBe("Bienvenue"); + + const translations = await tools.get_block_translations.execute({}); + expect(translations.lang).toBe("fr"); + expect(translations.entries).toEqual( + expect.arrayContaining([ + expect.objectContaining({ blockId: "h-1", prop: "content", source: "Welcome", translation: "Bienvenue" }), + ]), + ); + + const invalidLang = await tools.get_block_translations.execute({ lang: "de" }); + expect(invalidLang.error).toContain("not a configured site language"); + }); + + it("reads real site design system, tokens and theme from apps row in get_design_system and check_page_design", async () => { + useTestChaiConfig({}); + withChaiConfig({ + features: { + ...getActiveChaiBuilderConfig().features, + designSystem: { enabled: true, designChecks: "warn" }, + } as never, + }); + + await withTestDB(async ({ db, seed, inRequest }) => { + const { eq } = await import("drizzle-orm"); + await db + .update(schema.apps) + .set({ + name: "Acme Studio", + fallbackLang: "en", + languages: ["fr"], + designTokens: { "dt#acme-card": { name: "Acme Card", value: "rounded-xl p-6 bg-card" } } as any, + ai: { + bannedWords: "synergy", + designSystem: { + version: 1, + enabled: true, + northStar: "Swiss Editorial", + mode: "read", + overview: "Clean grid", + colors: "Monochrome + vermilion", + typography: "Tight display", + layout: "Generous whitespace", + elevation: "Flat", + shapes: "Sharp", + components: "dt#acme-card", + dosAndDonts: "No fluff", + }, + } as any, + }) + .where(eq(schema.apps.id, (await seed("appPages", { id: "ds-p1", name: "Home", slug: "/", lang: "" })).app)); + + await inRequest( + async () => { + const tools = buildAiEditPageTools({ + blocks: [ + { _id: "sec-1", _type: "Box", styles: "#styles:,dt#acme-card" }, + { _id: "h-1", _type: "Heading", _parent: "sec-1", tag: "h1", content: "Welcome", styles: "#styles:,text-4xl" }, + ], + pageId: "ds-p1", + primaryPageId: "ds-p1", + pageName: "Home", + pageSlug: "/", + }) as any; + + const ds = await tools.get_design_system.execute({}); + expect(ds.ok).toBe(true); + expect(ds.status).toBe("ready"); + expect(ds.brief).toContain("Swiss Editorial"); + expect(ds.brief).toContain("dt#acme-card"); + expect(ds.brief).toContain("Acme Studio"); + + const check = await tools.check_page_design.execute({}); + expect(check.ok).toBe(true); + expect(check.report).toContain("The site's design system is enabled"); + expect(check.report).not.toContain("unknown-design-token"); + + const pagesList = await tools.get_pages_list.execute({}); + expect(pagesList.fallbackLang).toBe("en"); + expect(pagesList.languages).toEqual(["fr"]); + }, + { permissions: ["ai:read", "ai:use", "pages:read"] }, + ); + }); + }); + + it("reads and updates draft SEO on the active page via get_page_seo and update_page_seo", async () => { + await withTestDB(async ({ seed, inRequest }) => { + await seed("appPages", { + id: "seo-page", + name: "About", + slug: "/about", + lang: "", + pageType: "page", + seo: { title: "Old Title", description: "Old Desc" }, + }); + + await inRequest( + async () => { + const tools = buildAiEditPageTools({ + blocks: sampleBlocks, + pageId: "seo-page", + primaryPageId: "seo-page", + pageName: "About", + pageSlug: "/about", + lang: "en", + fallbackLang: "en", + }) as any; + + const before = await tools.get_page_seo.execute({}); + expect(before.seo.title).toBe("Old Title"); + expect(before.seo.description).toBe("Old Desc"); + + const updated = await tools.update_page_seo.execute({ + title: "New Title", + metaOther: [{ name: "author", content: "Acme" }], + jsonLD: JSON.stringify({ "@context": "https://schema.org", "@type": "WebPage" }), + }); + expect(updated).toEqual({ ok: true, pageId: "seo-page", changedKeys: ["title", "metaOther", "jsonLD"] }); + + const after = await tools.get_page_seo.execute({}); + expect(after.seo.title).toBe("New Title"); + expect(after.seo.description).toBe("Old Desc"); + expect(after.metaTags.metaOther).toEqual({ author: "Acme" }); + expect(after.jsonLD).toEqual({ "@context": "https://schema.org", "@type": "WebPage" }); + }, + { permissions: ["pages:read", "pages:update", "pages:edit_seo"] }, + ); + }); + }); + + it("gates design system tools on feature flag and keeps theme/token mutations MCP-only", async () => { + useTestChaiConfig({}); + withChaiConfig({ + features: { + ...getActiveChaiBuilderConfig().features, + designSystem: { enabled: true, designChecks: "warn" }, + } as never, + }); + + const tools = buildAiEditPageTools({ + blocks: sampleBlocks, + pageId: "p1", + }) as any; + expect(tools.get_design_system).toBeDefined(); + expect(tools.save_design_system).toBeDefined(); + expect(tools.check_page_design).toBeDefined(); + expect(tools.get_design_guide).toBeDefined(); + expect(tools.update_site_theme).toBeUndefined(); + expect(tools.update_design_tokens).toBeUndefined(); + + const guide = await tools.get_design_guide.execute({ topic: "craft-floor" }); + expect(guide.ok).toBe(true); + expect(guide.guide).toContain("Craft floor"); + }); +}); diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.ts index 651f138fa..072f25a50 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-tools.ts @@ -1,19 +1,121 @@ import { tool, zodSchema } from "ai"; import { and, asc, eq, isNull, ne } from "drizzle-orm"; import { z } from "zod"; -import { MAX_PARTIAL_DEPTH } from "~/constants/PARTIAL_BLOCKS"; +import { getRegisteredChaiFonts } from "~/registry"; +import { getChaiActionInstance } from "~/server/chai-actions/actions-registery"; import { db, safeQuery, schema } from "~/server/chai-actions/db"; +import { runChaiAction } from "~/server/chai-actions/dispatch-action"; +import { applyChaiActionCacheEffects } from "~/server/chai-builder/action-cache-effects"; import { getInitializedStateWithUser } from "~/server/chai-builder/state"; +import { getResolvedPageTypes } from "~/server/defaults/config-registry"; +import { toSafeChaiMcpError } from "~/server/mcp/response"; +import { hasChaiPermission } from "~/server/rbac/permissions"; +import type { ChaiBlock } from "~/types/common"; +import { CHAI_DESIGN_SYSTEM_KEY, CHAI_PAGE_DESIGN_BRIEF_KEY, type ChaiPageDesignBrief } from "~/types/design-system"; import { extractBlockHtmlSlices } from "~/utils/export-html/extract-block-html-slices"; import { getLinkablePages, toPageLinkRef } from "~/utils/internal-link-refs"; -import { getPartialDepth, getPartialUsageDepth } from "~/utils/partial-nesting"; -import { AI_EDIT_TOOL_DESCRIPTIONS, buildAiEditToolFields } from "./ai-edit-tool-contract"; +import { getPageLangInfo, langLabel, langResponseFields } from "~/utils/page-lang"; +import { describeSeoPageLang, isPlainRecord, mergeSeoUpdate, normalizeStoredSeo, parseSeoPatch } from "~/utils/page-seo"; +import { toLanguageView } from "~/utils/page-translations"; +import { composeDesignBrief } from "../design/compose-design-brief"; +import { getDesignSystemFeature } from "../design/feature"; +import { DESIGN_GUIDES, getDesignGuide, type DesignGuideTopic } from "../design/guides"; +import { + designSystemStatus, + isDesignSystemActive, + readChaiDesignSystem, + readChaiPageDesignBrief, +} from "../design-system-schema"; +import { + buildBlockTranslationsPage, + collectSubtreeIds, + designSystemStatusLine, + extractDesignSystemPatch, + listAvailableLibraryBlocks, + readSiteDesignContextForApp, + runPageDesignCheckReport, + saveSiteDesignContextWithCas, + selectPartialBlocks, + sliceBlocksHtml, + sliceBlocksJson, + toDesignCheckContext, + type AppSiteDesignContext, + type LibraryDescriptor, + type LibraryItemDescriptor, +} from "../page-tool-operations"; +import { executeUploadImage, type CreatedAsset } from "../remote-image"; import { isValidAiBindingTemplate } from "./ai-edit-executors"; import type { AiDataBindingPaths } from "./ai-edit-page-prompt-context"; +import { + AI_EDIT_TOOL_DESCRIPTIONS, + AI_SHARED_TOOL_PERMISSIONS, + SHARED_AI_TOOL_FIELDS, +} from "./ai-edit-tool-contract"; export { extractBlockHtmlSlices, isValidAiBindingTemplate }; -const fields = buildAiEditToolFields(z); +export type BuildAiEditPageToolsOptions = { + /** Current page blocks JSON (preferred — mirrors MCP). */ + blocks?: ChaiBlock[]; + /** Legacy fallback HTML string when `blocks` is omitted. */ + pageHtml?: string; + scopedBlockId?: string; + /** Active page row id (language variant row id when editing a variant). */ + pageId?: string; + /** Primary page id (same as pageId on primary pages). */ + primaryPageId?: string; + pageName?: string; + pageSlug?: string; + /** Active content language (variant lang, or "" / fallbackLang on primary). */ + lang?: string; + fallbackLang?: string; + /** Variant languages configured for this page. */ + variantLangs?: string[]; + /** All configured non-fallback languages on the site. */ + languages?: string[]; + isPartial?: boolean; + dataBindingPaths?: AiDataBindingPaths; + /** + * Caller's effective RBAC permissions. When provided, every tool is checked against + * `AI_SHARED_TOOL_PERMISSIONS`; when omitted (direct unit tests), base tools stay enabled. + */ + permissions?: readonly string[] | null; + /** Current userId for authorship stamps (e.g. `save_design_system`). */ + userId?: string; +}; + +const fields = SHARED_AI_TOOL_FIELDS; + +const asRecord = (value: unknown): Record => + typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record) : {}; + +const formatErr = (err: unknown): string => toSafeChaiMcpError(err).replace(/^Error: /, ""); + +const hasToolPermissions = (permissions: readonly string[] | null | undefined, toolName: string): boolean => { + if (permissions === undefined) return true; + if (permissions === null) return false; + const required = AI_SHARED_TOOL_PERMISSIONS[toolName] ?? []; + return required.every((perm) => hasChaiPermission(permissions as string[], perm)); +}; + +async function runActionWithCache(name: string, input: unknown): Promise { + const result = (await runChaiAction(name, input)) as TResult; + try { + await applyChaiActionCacheEffects(name, result); + } catch (error) { + console.error(`[chai-ai] cache invalidation failed after ${name}:`, error); + } + return result; +} + +async function readSiteDesignContextViaAction(): Promise { + try { + const { appId } = getInitializedStateWithUser(); + return await readSiteDesignContextForApp(appId); + } catch { + return null; + } +} const buildBindPropTool = ({ dataBindingPaths, @@ -59,250 +161,258 @@ const buildBindPropTool = ({ ), }); -/** - * Read-only page lookup so a link can be written as a stable `pageType:` reference. - * Offered to block-scoped runs too: linking one button is a single-block edit. - */ const buildGetPagesListTool = () => tool({ description: AI_EDIT_TOOL_DESCRIPTIONS.get_pages_list, - inputSchema: zodSchema(z.object({})), - execute: async (): Promise<{ - pages: { name: string; slug: string; pageType: string; linkRef: string }[]; - note: string; - }> => { + inputSchema: zodSchema(z.object(fields.get_pages_list)), + execute: async ({ mode = "draft" }: { mode?: "draft" | "live" }) => { const { appId } = getInitializedStateWithUser(); + const pagesTable = mode === "live" ? schema.appPagesOnline : schema.appPages; + const whereTerms = [eq(pagesTable.app, appId), ne(pagesTable.slug, "")]; + if (mode === "draft") whereTerms.push(isNull(schema.appPages.deletedAt)); + const { data: pages, error } = await safeQuery(() => db .select({ - id: schema.appPages.id, - name: schema.appPages.name, - slug: schema.appPages.slug, - pageType: schema.appPages.pageType, - primaryPage: schema.appPages.primaryPage, - dynamic: schema.appPages.dynamic, + id: pagesTable.id, + name: pagesTable.name, + slug: pagesTable.slug, + lang: pagesTable.lang, + pageType: pagesTable.pageType, + primaryPage: pagesTable.primaryPage, + parent: pagesTable.parent, + dynamic: pagesTable.dynamic, }) - .from(schema.appPages) - .where( - and( - eq(schema.appPages.app, appId), - // Primary-language, routable pages: a link always anchors to the - // primary page, and partials (empty slug) have no URL to link to. - ne(schema.appPages.slug, ""), - eq(schema.appPages.lang, ""), - isNull(schema.appPages.deletedAt), - ), - ) - .orderBy(asc(schema.appPages.slug)), + .from(pagesTable) + .where(and(...whereTerms)) + .orderBy(asc(pagesTable.slug)), ); if (error) { throw new Error(`Failed to fetch pages: ${error.message}`); } + const site = await readSiteDesignContextForApp(appId); + const fallbackLang = site?.fallbackLang ?? ""; + const languages = site?.languages ?? []; + + const rows = (pages as any[]) ?? []; + const slugById = new Map(rows.map((p) => [p.id, p.slug])); + const linkableIds = new Set(getLinkablePages(rows).map((p) => p.id)); + return { - pages: getLinkablePages((pages as any[]) ?? []).map((page) => ({ - name: page.name, - slug: page.slug, - pageType: page.pageType ?? "page", - linkRef: toPageLinkRef(page), - })), + fallbackLang, + languages, + pages: rows + .filter((page) => linkableIds.has(page.id)) + .map((page) => ({ + id: page.id, + name: page.name, + slug: page.slug, + lang: page.lang || fallbackLang, + pageType: page.pageType ?? "page", + parentId: page.parent ?? null, + parentSlug: page.parent ? (slugById.get(page.parent) ?? null) : null, + linkRef: toPageLinkRef(page), + })), note: "Use linkRef as the href when linking to a page. Never write the slug — slugs change, a linkRef does not.", }; }, }); -/** - * Tools available to the AI during page editing (AI SDK v6 UIMessage flow). - * - * Client-executed tools (no execute()): the builder applies them to its JSON - * block state and reports back via addToolResult. HTML inside edit_block / - * add_blocks streams as tool-input deltas, which the client renders live on - * the canvas — this preserves the streaming preview the old text protocol had. - * - * Server-executed tools: get_partial_blocks and get_pages_list (DB lookups) and - * read_block_html (slices the per-request page HTML, which is intentionally kept OUT of the - * model context — the model sees only the page outline and reads on demand). - * - * NOTE for edit_block/add_blocks: `task` is declared before `html` on purpose — - * tool-input streaming parses fields in order, so the client learns the target - * and label before HTML starts flowing. - */ -const buildAllAiEditPageTools = ({ - pageHtml, - pageId, - dataBindingPaths, -}: { - pageHtml: string; - pageId?: string; - dataBindingPaths?: AiDataBindingPaths; -}) => ({ - read_block_html: tool({ - description: AI_EDIT_TOOL_DESCRIPTIONS.read_block_html, - // Typed inline (not via the loose shared factory) because this is the one - // shared tool with a server execute() — the factory's fields widen to `any`, - // which conflicts with the execute input type. The MCP side still sources - // this field shape from the shared contract. - inputSchema: zodSchema( - z.object({ - blockIds: z.array(z.string()).min(1).describe("bids of the blocks to read"), - }), - ), - execute: async ({ blockIds }: { blockIds: string[] }) => extractBlockHtmlSlices(pageHtml, blockIds), - }), - - edit_block: tool({ - description: AI_EDIT_TOOL_DESCRIPTIONS.edit_block, - inputSchema: zodSchema( - z.object({ - task: z.string().describe("Short user-facing progress label, e.g. 'Redesigning hero section'"), - ...fields.edit_block, - }), - ), - }), - - add_blocks: tool({ - description: AI_EDIT_TOOL_DESCRIPTIONS.add_blocks, - inputSchema: zodSchema( - z.object({ - task: z.string().describe("Short user-facing progress label, e.g. 'Adding pricing section'"), - ...fields.add_blocks, - }), - ), - }), - - remove_blocks: tool({ - description: AI_EDIT_TOOL_DESCRIPTIONS.remove_blocks, - inputSchema: zodSchema( - z.object({ - ...fields.remove_blocks, - task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Removing testimonial section'"), - }), - ), - }), - - add_custom_block: tool({ - description: AI_EDIT_TOOL_DESCRIPTIONS.add_custom_block, +const buildUpdateBlockTranslationsTool = (scopedBlockId?: string, scopedIds?: ReadonlySet) => + tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.update_block_translations, inputSchema: zodSchema( - z.object({ - task: z.string().nullish().describe("Short user-facing progress label"), - ...fields.add_custom_block, - }), + z + .object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Updating French translations'"), + lang: fields.update_block_translations.lang, + // AI SDK zodSchema() adds additionalProperties:false to z.record(), so use string/array/null + // (objects can be passed as JSON strings and are parsed client-side). + translations: z + .array( + z.object({ + blockId: z.string().describe("bid of the block"), + prop: z.string().describe('Translatable prop name as reported by get_block_translations, e.g. "content"'), + value: z + .union([z.string(), z.array(z.unknown()), z.null()]) + .describe( + 'Translated value (string for copy including HTML markup, JSON string for object props, or array). null or "" removes the translation so the source shows.', + ), + }), + ) + .min(1) + .max(500) + .describe("Translations to write; the whole batch is rejected if any entry is invalid."), + }) + .superRefine((input, context) => { + if (!scopedBlockId) return; + for (const [index, entry] of input.translations.entries()) { + const allowed = scopedIds ? scopedIds.has(entry.blockId) : entry.blockId === scopedBlockId; + if (!allowed) { + context.addIssue({ + code: "custom", + path: ["translations", index, "blockId"], + message: `Only block "${scopedBlockId}" and its descendants may be translated in this conversation`, + }); + } + } + }), ), - }), - - bind_prop: buildBindPropTool({ dataBindingPaths }), + }); - get_partial_blocks: tool({ - description: AI_EDIT_TOOL_DESCRIPTIONS.get_partial_blocks, - inputSchema: zodSchema(z.object({})), - execute: async (): Promise<{ - partials: Record; - note?: string; - }> => { - const { appId } = getInitializedStateWithUser(); - const { data: pages, error } = await safeQuery(() => - db - .select({ - id: schema.appPages.id, - name: schema.appPages.name, - metadata: schema.appPages.metadata, - pageType: schema.appPages.pageType, - partialBlocks: schema.appPages.partialBlocks, - }) - .from(schema.appPages) - .where( - and( - eq(schema.appPages.app, appId), - // Partials are slug-less pages (their page type has hasSlug: false). - // Match on empty slug rather than a specific pageType so all partial - // types (e.g. the built-in "global") are included. - eq(schema.appPages.slug, ""), - eq(schema.appPages.lang, ""), - isNull(schema.appPages.deletedAt), - ), - ), +const buildGetBlockTranslationsTool = ({ + blocks, + pageName, + targetPrimaryPageId, + langInfo, + variantLangs, + languages, + scopedBlockId, + scopedIds, +}: { + blocks: ChaiBlock[]; + pageName: string; + targetPrimaryPageId?: string; + langInfo: ReturnType; + variantLangs: string[]; + languages: string[]; + scopedBlockId?: string; + scopedIds?: ReadonlySet; +}) => + tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_block_translations, + inputSchema: zodSchema(z.object(fields.get_block_translations)), + execute: async (args: { lang?: string; blockIds?: string[]; missingOnly?: boolean; offset?: number }) => { + const site = await readSiteDesignContextViaAction(); + const configured = [...new Set([...languages, ...variantLangs, ...(site?.languages ?? [])])].filter( + (code) => code && code !== langInfo.fallbackLang, ); + const knownNote = configured.length + ? ` Configured translation languages: ${configured.map(langLabel).join(", ")}.` + : " The site has no other languages configured."; - if (error) { - throw new Error(`Failed to fetch partial blocks: ${error.message}`); + const targetLang = (args.lang || (langInfo.isLanguageVariant ? langInfo.lang : "")).trim(); + if (!targetLang) { + return { error: `Pass lang — the target language code.${knownNote}` }; } - - const partialPages = (pages as any[]) ?? []; - // partialId -> partial ids it contains (the denormalized closure column) - const dependencies: Record = {}; - partialPages.forEach((page: any) => { - dependencies[page.id] = ((page.partialBlocks as string) ?? "").split("|").filter(Boolean); - }); - - // Nesting rules: the partial chain below any page is capped at - // MAX_PARTIAL_DEPTH. Editing a partial means candidates land at - // (levels above it + 1) already, shrinking the depth budget. - const editingPartial = pageId ? pageId in dependencies : false; - const chainAbove = editingPartial ? 1 + getPartialUsageDepth(pageId!, dependencies) : 0; - const allowedTargetDepth = MAX_PARTIAL_DEPTH - chainAbove; - - if (editingPartial && allowedTargetDepth < 1) { + if (targetLang === langInfo.fallbackLang) { return { - partials: {}, - note: - "This partial is already used inside another partial, so it sits at the maximum nesting depth " + - `(${MAX_PARTIAL_DEPTH} levels). No partial blocks can be added here — tell the user why.`, + error: `${langLabel(targetLang)} is the site fallback language; edit its copy directly with edit_block.${knownNote}`, }; } + if (configured.length > 0 && !configured.includes(targetLang)) { + return { error: `${langLabel(targetLang)} is not a configured site language.${knownNote}` }; + } - const result: Record = {}; - partialPages.forEach((page: any) => { - // Never offer the page being edited (self-nesting), anything that - // contains it (cycle), or partials whose subtree is too deep to fit. - if (pageId && page.id === pageId) return; - if (pageId && dependencies[page.id]!.includes(pageId)) return; - if (getPartialDepth(page.id, dependencies) > allowedTargetDepth) return; - const meta = (page.metadata as any) ?? {}; - result[page.id] = { - name: page.name, - description: meta.description ?? "", - type: page.pageType ?? "partial", - }; - }); + let requestedIds = args.blockIds; + if (scopedBlockId && scopedIds) { + if (requestedIds && requestedIds.length > 0) { + const outOfScope = requestedIds.filter((id) => !scopedIds.has(id)); + if (outOfScope.length > 0) { + return { + error: `bid ${outOfScope.join(", ")} is outside the current edit scope "${scopedBlockId}".`, + }; + } + } else { + requestedIds = [...scopedIds]; + } + } + + const page = buildBlockTranslationsPage(blocks, targetLang, { ...args, blockIds: requestedIds }); return { - partials: result, - ...(editingPartial - ? { - note: `You are editing a partial: only partials that fit within the maximum nesting depth (${MAX_PARTIAL_DEPTH} levels) are listed.`, - } - : {}), + pageName, + primaryPageId: targetPrimaryPageId ?? null, + lang: targetLang, + fallbackLang: langInfo.fallbackLang, + languageVariantExists: variantLangs.includes(targetLang) || targetLang === langInfo.lang, + ...page, }; }, - }), - - get_pages_list: buildGetPagesListTool(), -}); - -/** - * Tools for a block-scoped run (the block floating AI action). - * - * The model is handed *only* read + edit for the one selected block (plus the - * read-only get_pages_list lookup), so a - * page-wide edit is not something it can express: add_blocks, remove_blocks, - * add_custom_block is absent from the tool set entirely, and - * read_block_html/edit_block refuse any bid other than the scoped one. - * Prompt wording alone is not enough here — the tool surface is the boundary. - */ + }); + +const readSlicesFromInput = ( + viewBlocks: ChaiBlock[] | undefined, + pageHtml: string, + blockIds: string[], +): Record => (viewBlocks ? sliceBlocksHtml(viewBlocks, blockIds) : extractBlockHtmlSlices(pageHtml, blockIds)); + const buildBlockScopedAiEditPageTools = ({ - pageHtml, + blocks, + pageHtml = "", scopedBlockId, + primaryPageId, + pageId, + pageName = "Current Page", + lang, + fallbackLang, + variantLangs = [], + languages = [], dataBindingPaths, -}: { - pageHtml: string; - scopedBlockId: string; - dataBindingPaths?: AiDataBindingPaths; -}) => { + permissions, +}: Required> & BuildAiEditPageToolsOptions) => { const outOfScope = (blockId: string) => `ERROR: bid "${blockId}" is outside the current edit scope. Only the selected block "${scopedBlockId}" ` + `may be read or edited in this conversation.`; - return { + const langInfo = getPageLangInfo({ lang, fallbackLang }); + const viewBlocks = blocks && langInfo.isLanguageVariant ? toLanguageView(blocks, langInfo.lang) : blocks; + const scopedIds = blocks ? collectSubtreeIds(blocks, [scopedBlockId]) : new Set([scopedBlockId]); + const targetPrimaryPageId = primaryPageId ?? pageId; + + const tools: Record = { + read_blocks: tool({ + description: + `Read the raw JSON of the selected block "${scopedBlockId}" (or its descendants when includeDescendants is true). ` + + "Prefer this over read_block_html when updating props with update_block_props. Only this block and its descendants may be read.", + inputSchema: zodSchema( + z.object({ + blockIds: z.array(z.string()).min(1).describe(`bids within "${scopedBlockId}" and its descendants`), + includeDescendants: fields.read_blocks.includeDescendants, + }), + ), + execute: async ({ blockIds, includeDescendants }: { blockIds: string[]; includeDescendants?: boolean }) => { + const rejected = blockIds.filter((id) => !scopedIds.has(id)); + if (rejected.length > 0) { + return { ok: false, error: outOfScope(rejected[0]!) }; + } + if (!viewBlocks) { + return { ok: false, error: "Block JSON is unavailable for this request; call read_block_html instead." }; + } + const { blocks: found, missingIds } = sliceBlocksJson(viewBlocks, blockIds, { includeDescendants }); + return { + ...langResponseFields(langInfo), + blocks: found, + ...(missingIds.length > 0 ? { missingIds } : {}), + }; + }, + }), + + update_block_props: tool({ + description: + `Patch JSON props on the selected block "${scopedBlockId}" or its descendants without rewriting HTML. ` + + "Preferred over edit_block for copy, style, media, link, and custom-block prop edits. Call read_blocks first.", + inputSchema: zodSchema( + z + .object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Updating heading copy'"), + ...fields.update_block_props, + }) + .superRefine((input, context) => { + for (const [index, entry] of input.updates.entries()) { + if (!scopedIds.has(entry.blockId)) { + context.addIssue({ + code: "custom", + path: ["updates", index, "blockId"], + message: `Only block "${scopedBlockId}" and its descendants may be updated in this conversation`, + }); + } + } + }), + ), + }), + read_block_html: tool({ description: `Read the full current HTML of the selected block "${scopedBlockId}". ` + @@ -318,7 +428,7 @@ const buildBlockScopedAiEditPageTools = ({ if (rejected.length > 0) { return Object.fromEntries(rejected.map((id) => [id, outOfScope(id)])); } - return extractBlockHtmlSlices(pageHtml, [scopedBlockId]); + return readSlicesFromInput(viewBlocks, pageHtml, [scopedBlockId]); }, }), @@ -334,34 +444,520 @@ const buildBlockScopedAiEditPageTools = ({ }), ), }), + bind_prop: buildBindPropTool({ dataBindingPaths, scopedBlockId }), - get_pages_list: buildGetPagesListTool(), }; + + if (hasToolPermissions(permissions, "get_pages_list")) { + tools.get_pages_list = buildGetPagesListTool(); + } + + const hasMultilingual = Boolean(langInfo.isLanguageVariant || variantLangs.length > 0); + if (hasMultilingual && blocks !== undefined && hasToolPermissions(permissions, "get_block_translations")) { + tools.get_block_translations = buildGetBlockTranslationsTool({ + blocks, + pageName, + targetPrimaryPageId, + langInfo, + variantLangs, + languages, + scopedBlockId, + scopedIds, + }); + } + if (hasMultilingual && hasToolPermissions(permissions, "update_block_translations")) { + tools.update_block_translations = buildUpdateBlockTranslationsTool(scopedBlockId, scopedIds); + } + + return tools; }; -export const buildAiEditPageTools = ({ - pageHtml, - scopedBlockId, - pageId, - dataBindingPaths, -}: { - pageHtml: string; - scopedBlockId?: string; - pageId?: string; - dataBindingPaths?: AiDataBindingPaths; -}) => - scopedBlockId - ? buildBlockScopedAiEditPageTools({ pageHtml, scopedBlockId, dataBindingPaths }) - : buildAllAiEditPageTools({ pageHtml, pageId, dataBindingPaths }); +const buildAllAiEditPageTools = (options: BuildAiEditPageToolsOptions) => { + const { + blocks, + pageHtml = "", + pageId, + primaryPageId, + pageName = "Current Page", + pageSlug = "", + lang, + fallbackLang, + variantLangs = [], + languages = [], + isPartial = false, + dataBindingPaths, + permissions, + userId, + } = options; + + const langInfo = getPageLangInfo({ lang, fallbackLang }); + const viewBlocks = blocks && langInfo.isLanguageVariant ? toLanguageView(blocks, langInfo.lang) : blocks; + const targetPrimaryPageId = primaryPageId ?? pageId; + const designFeature = getDesignSystemFeature(); + + const tools: Record = { + read_blocks: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.read_blocks, + inputSchema: zodSchema(z.object(fields.read_blocks)), + execute: async ({ blockIds, includeDescendants }: { blockIds: string[]; includeDescendants?: boolean }) => { + if (!viewBlocks) { + return { ok: false, error: "Block JSON is unavailable for this request; call read_block_html instead." }; + } + const { blocks: found, missingIds } = sliceBlocksJson(viewBlocks, blockIds, { includeDescendants }); + return { + ...langResponseFields(langInfo), + blocks: found, + ...(missingIds.length > 0 ? { missingIds } : {}), + }; + }, + }), + + update_block_props: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.update_block_props, + inputSchema: zodSchema( + z.object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Updating hero copy'"), + ...fields.update_block_props, + }), + ), + }), + + read_block_html: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.read_block_html, + inputSchema: zodSchema( + z.object({ + blockIds: z.array(z.string()).min(1).describe("bids of the blocks to read"), + }), + ), + execute: async ({ blockIds }: { blockIds: string[] }) => readSlicesFromInput(viewBlocks, pageHtml, blockIds), + }), + + edit_block: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.edit_block, + inputSchema: zodSchema( + z.object({ + task: z.string().describe("Short user-facing progress label, e.g. 'Redesigning hero section'"), + ...fields.edit_block, + }), + ), + }), + + add_blocks: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.add_blocks, + inputSchema: zodSchema( + z.object({ + task: z.string().describe("Short user-facing progress label, e.g. 'Adding pricing section'"), + ...fields.add_blocks, + }), + ), + }), + + remove_blocks: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.remove_blocks, + inputSchema: zodSchema( + z.object({ + ...fields.remove_blocks, + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Removing testimonial section'"), + }), + ), + }), + + add_custom_block: tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.add_custom_block, + inputSchema: zodSchema( + z.object({ + task: z.string().nullish().describe("Short user-facing progress label"), + ...fields.add_custom_block, + }), + ), + }), + + bind_prop: buildBindPropTool({ dataBindingPaths }), + }; + + if (viewBlocks !== undefined && hasToolPermissions(permissions, "get_page_blocks")) { + tools.get_page_blocks = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_page_blocks, + inputSchema: zodSchema(z.object(fields.get_page_blocks)), + execute: async () => ({ + pageId: pageId ?? null, + primaryPageId: targetPrimaryPageId ?? null, + name: pageName, + slug: pageSlug, + ...langResponseFields(langInfo), + blocks: viewBlocks, + }), + }); + } + + if (hasToolPermissions(permissions, "get_partial_blocks")) { + tools.get_partial_blocks = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_partial_blocks, + inputSchema: zodSchema(z.object(fields.get_partial_blocks)), + execute: async () => { + const { appId } = getInitializedStateWithUser(); + const { data: pages, error } = await safeQuery(() => + db + .select({ + id: schema.appPages.id, + name: schema.appPages.name, + slug: schema.appPages.slug, + metadata: schema.appPages.metadata, + pageType: schema.appPages.pageType, + partialBlocks: schema.appPages.partialBlocks, + }) + .from(schema.appPages) + .where( + and( + eq(schema.appPages.app, appId), + eq(schema.appPages.slug, ""), + eq(schema.appPages.lang, ""), + isNull(schema.appPages.deletedAt), + ), + ), + ); + + if (error) { + throw new Error(`Failed to fetch partial blocks: ${error.message}`); + } + + return selectPartialBlocks((pages as any[]) ?? [], getResolvedPageTypes(), { + currentPageId: targetPrimaryPageId, + }); + }, + }); + } + + const hasLibraryActions = Boolean( + getChaiActionInstance("GET_LIBRARIES") && + getChaiActionInstance("GET_LIBRARY_ITEMS") && + getChaiActionInstance("GET_LIBRARY_ITEM"), + ); + if (hasLibraryActions && hasToolPermissions(permissions, "get_library_blocks")) { + tools.get_library_blocks = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_library_blocks, + inputSchema: zodSchema(z.object(fields.get_library_blocks)), + execute: async (input: { query?: string; group?: string }) => { + try { + const result = await listAvailableLibraryBlocks( + { + getLibraries: () => runChaiAction("GET_LIBRARIES", {}) as Promise, + getLibraryItems: (id) => runChaiAction("GET_LIBRARY_ITEMS", { id }) as Promise, + }, + input, + ); + if (result.blocks.length === 0) { + return { + ok: true, + blocks: [], + groups: result.groups, + total: 0, + note: + result.groups.length > 0 + ? `No library blocks matched. Available groups: ${result.groups.join(", ")}.` + : "No library blocks are available for this site.", + }; + } + return { ok: true, ...result }; + } catch (error) { + return { ok: false, error: formatErr(error) }; + } + }, + }); + } + + if (hasLibraryActions && hasToolPermissions(permissions, "add_library_block")) { + tools.add_library_block = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.add_library_block, + inputSchema: zodSchema( + z.object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Adding hero section'"), + ...fields.add_library_block, + }), + ), + }); + } + + if (hasToolPermissions(permissions, "get_pages_list")) { + tools.get_pages_list = buildGetPagesListTool(); + } + + // --- Multilingual tools (single page, active when page/site has translations) --- + const hasMultilingual = Boolean(langInfo.isLanguageVariant || variantLangs.length > 0); + if (hasMultilingual && blocks !== undefined && hasToolPermissions(permissions, "get_block_translations")) { + tools.get_block_translations = buildGetBlockTranslationsTool({ + blocks, + pageName, + targetPrimaryPageId, + langInfo, + variantLangs, + languages, + }); + } + + if (hasMultilingual && hasToolPermissions(permissions, "update_block_translations")) { + tools.update_block_translations = buildUpdateBlockTranslationsTool(); + } + + // --- SEO tools (single open non-partial page) --- + if (pageId && !isPartial && hasToolPermissions(permissions, "get_page_seo")) { + tools.get_page_seo = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_page_seo, + inputSchema: zodSchema(z.object(fields.get_page_seo)), + execute: async () => { + const draft = (await runChaiAction("GET_DRAFT_PAGE", { id: pageId })) as { seo?: unknown }; + const normalized = normalizeStoredSeo(draft?.seo); + return { + pageId, + primaryPageId: targetPrimaryPageId ?? pageId, + name: pageName, + slug: pageSlug, + ...langResponseFields(langInfo), + languageNote: describeSeoPageLang(langInfo), + inheritsPrimaryJsonLD: langInfo.isLanguageVariant && normalized.jsonLD === null, + ...normalized, + }; + }, + }); + } + + if (pageId && !isPartial && hasToolPermissions(permissions, "update_page_seo")) { + tools.update_page_seo = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.update_page_seo, + inputSchema: zodSchema( + z.object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Updating page SEO'"), + title: fields.update_page_seo.title, + description: fields.update_page_seo.description, + canonicalUrl: fields.update_page_seo.canonicalUrl, + noIndex: fields.update_page_seo.noIndex, + noFollow: fields.update_page_seo.noFollow, + ogTitle: fields.update_page_seo.ogTitle, + ogDescription: fields.update_page_seo.ogDescription, + ogImage: fields.update_page_seo.ogImage, + // AI SDK zodSchema() adds additionalProperties:false to z.record(), so expose + // metaOther as {name, content}[] and jsonLD as a JSON string | null for strict models. + metaOther: z + .array(z.object({ name: z.string(), content: z.string() })) + .optional() + .describe('Extra pairs. Replaces the whole set; pass [] to remove them all.'), + jsonLD: z + .union([z.string(), z.null()]) + .optional() + .describe("JSON-LD document serialized as a JSON string. Replaces the whole document; null or '{}' clears it."), + }), + ), + execute: async ({ task: _task, ...rawArgs }: Record) => { + const args: Record = { ...rawArgs }; + if (Array.isArray(rawArgs.metaOther)) { + const pairs: Record = {}; + for (const entry of rawArgs.metaOther as Array<{ name?: unknown; content?: unknown }>) { + if (typeof entry?.name === "string" && typeof entry?.content === "string") { + pairs[entry.name] = entry.content; + } + } + args.metaOther = pairs; + } + const parsed = parseSeoPatch(args); + if (!parsed.ok) return { ok: false, error: parsed.message }; + let current: Record = {}; + try { + const draft = (await runChaiAction("GET_DRAFT_PAGE", { id: pageId })) as { seo?: unknown }; + if (isPlainRecord(draft?.seo)) current = draft.seo; + } catch (err) { + return { ok: false, error: `Failed to read current SEO (${formatErr(err)})` }; + } + const { seo, changedKeys } = mergeSeoUpdate(current, parsed.patch); + try { + await runActionWithCache("UPDATE_PAGE", { id: pageId, seo, addInRevision: true }); + } catch (err) { + return { ok: false, error: `Failed to update page SEO (${formatErr(err)})` }; + } + return { ok: true, pageId, changedKeys }; + }, + }); + } + + // --- Media upload tool (when media backend is registered) --- + if (getChaiActionInstance("CREATE_ASSET") && hasToolPermissions(permissions, "upload_image")) { + tools.upload_image = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.upload_image, + inputSchema: zodSchema( + z.object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Uploading image'"), + ...fields.upload_image, + }), + ), + execute: async ({ task: _task, ...args }: Record) => { + const result = await executeUploadImage(args, { + createAsset: (payload) => runActionWithCache("CREATE_ASSET", payload), + getFallbackLang: async () => { + if (langInfo.fallbackLang) return langInfo.fallbackLang; + const site = await readSiteDesignContextViaAction(); + return site?.fallbackLang || "en"; + }, + formatError: formatErr, + }); + if (!result.ok) return { ok: false, error: result.message }; + return { + ok: true, + url: result.asset.url, + assetId: result.asset.id, + width: result.asset.width, + height: result.asset.height, + summary: result.text, + }; + }, + }); + } + + // --- Design system & theme tools (opt-in via designSystem feature) --- + if (designFeature.enabled) { + const hasAiContextActions = + Boolean(getChaiActionInstance("AI_GET_CONTEXT")) && Boolean(getChaiActionInstance("AI_SAVE_CONTEXT")); + + if (hasAiContextActions && hasToolPermissions(permissions, "get_design_system")) { + tools.get_design_system = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_design_system, + inputSchema: zodSchema(z.object(fields.get_design_system)), + execute: async ({ includeTokenValues }: { includeTokenValues?: boolean }) => { + const sitePromise = readSiteDesignContextViaAction(); + let context: { aiData?: { app?: unknown; page?: unknown } }; + try { + context = (await runChaiAction( + "AI_GET_CONTEXT", + targetPrimaryPageId ? { pageId: targetPrimaryPageId } : {}, + )) as { aiData?: { app?: unknown; page?: unknown } }; + } catch (err) { + return { ok: false, error: `Could not read the site's AI settings (${formatErr(err)})` }; + } + const app = asRecord(context?.aiData?.app); + const pageAi = asRecord(context?.aiData?.page); + const designSystem = readChaiDesignSystem(app[CHAI_DESIGN_SYSTEM_KEY]); + const site = await sitePromise; + return { + ok: true, + status: designSystemStatus(designSystem), + brief: composeDesignBrief({ + siteName: site?.name, + designSystem, + product: app, + theme: site?.theme ?? null, + designTokens: site?.designTokens ?? {}, + fonts: getRegisteredChaiFonts().map((font) => font.family), + page: targetPrimaryPageId + ? { + name: pageName, + slug: pageSlug, + brief: readChaiPageDesignBrief(pageAi[CHAI_PAGE_DESIGN_BRIEF_KEY]), + } + : null, + includeTokenValues: includeTokenValues === true, + checks: designFeature.designChecks, + }), + }; + }, + }); + } + + if (hasAiContextActions && hasToolPermissions(permissions, "save_design_system")) { + tools.save_design_system = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.save_design_system, + inputSchema: zodSchema( + z.object({ + task: z.string().nullish().describe("Short user-facing progress label, e.g. 'Saving design system'"), + ...fields.save_design_system, + }), + ), + execute: async ({ task: _task, ...args }: Record) => { + const patch = extractDesignSystemPatch(args); + const touchesSystem = Object.keys(patch).length > 0 || args.replace === true; + const product = asRecord(args.product); + const pageBrief = args.pageBrief as Omit | undefined; + + if (!touchesSystem && Object.keys(product).length === 0 && !pageBrief) { + return { ok: false, error: "Nothing to save. Pass design-system fields, product, or pageBrief." }; + } + if (pageBrief && !targetPrimaryPageId) { + return { ok: false, error: "Cannot save pageBrief: no active page id." }; + } + + const site = await saveSiteDesignContextWithCas(patch, product, { + touchesSystem, + replace: args.replace === true, + userId, + source: "builder", + readContext: () => runChaiAction("AI_GET_CONTEXT", {}) as Promise<{ aiData?: { app?: unknown } }>, + saveContext: (payload) => runChaiAction("AI_SAVE_CONTEXT", payload), + formatError: formatErr, + }); + if (!site.ok) return { ok: false, error: site.message }; + + if (pageBrief && targetPrimaryPageId) { + try { + await runChaiAction("AI_SAVE_CONTEXT", { + type: "page", + pageId: targetPrimaryPageId, + merge: true, + aiData: { designBrief: { ...pageBrief, updatedAt: new Date().toISOString() } }, + }); + } catch (err) { + return { ok: false, error: `Could not save page brief (${formatErr(err)})` }; + } + } + + const lines = ["### Saved"]; + if (site.next) lines.push(`- North star: ${site.next.northStar}`, designSystemStatusLine(site.next)); + if (Object.keys(product).length) lines.push(`- Site context updated: ${Object.keys(product).join(", ")}.`); + if (pageBrief) lines.push(`- Page brief saved for "${pageName}" (${pageSlug || "partial"}).`); + return { ok: true, summary: lines.join("\n") }; + }, + }); + } + + if (viewBlocks !== undefined && hasToolPermissions(permissions, "check_page_design")) { + tools.check_page_design = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.check_page_design, + inputSchema: zodSchema(z.object(fields.check_page_design)), + execute: async ({ blockIds }: { blockIds?: string[] }) => { + const site = await readSiteDesignContextViaAction(); + const ctx = site ? toDesignCheckContext(site, { isPartial, includeTheme: true }) : { isPartial }; + const report = runPageDesignCheckReport(viewBlocks, ctx, { + pageName, + blockIds, + active: isDesignSystemActive(designFeature, site?.designSystem), + outlineHint: "Check the page outline for valid bids.", + }); + if (!report.ok) return { ok: false, error: report.message }; + return { ok: true, errors: report.errors, warnings: report.warnings, report: report.text }; + }, + }); + } + + if (hasToolPermissions(permissions, "get_design_guide")) { + tools.get_design_guide = tool({ + description: AI_EDIT_TOOL_DESCRIPTIONS.get_design_guide, + inputSchema: zodSchema(z.object(fields.get_design_guide)), + execute: async ({ topic }: { topic: DesignGuideTopic }) => { + if (!Object.hasOwn(DESIGN_GUIDES, topic)) { + return { ok: false, error: `Unknown topic "${String(topic)}". Topics: ${Object.keys(DESIGN_GUIDES).join(", ")}.` }; + } + return { ok: true, topic, guide: getDesignGuide(topic) }; + }, + }); + } + } + + return tools; +}; + +export const buildAiEditPageTools = (options: BuildAiEditPageToolsOptions) => + options.scopedBlockId + ? buildBlockScopedAiEditPageTools({ ...options, scopedBlockId: options.scopedBlockId }) + : buildAllAiEditPageTools(options); export type AiEditPageTools = ReturnType; export type AiEditPageToolName = keyof AiEditPageTools; -/** Tools the client must execute (no server execute()). */ -export const CLIENT_EXECUTED_AI_EDIT_TOOLS = [ - "edit_block", - "add_blocks", - "remove_blocks", - "add_custom_block", - "bind_prop", -] as const; +/** Tools the client must execute against the Jotai block store (no server execute()). */ +export { CLIENT_EXECUTED_AI_EDIT_TOOLS } from "~/constants/AI_TOOL_HISTORY"; diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-tool-contract.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-tool-contract.ts index 04777ac28..d9502705a 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-tool-contract.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-tool-contract.ts @@ -1,41 +1,63 @@ +import { z } from "zod"; +import { DESIGN_GUIDE_TOPICS } from "~/server/chai-actions/ai/design/guides"; +import { + chaiDesignSystemPatchShape as DS, + chaiPageDesignBriefInputShape, +} from "~/server/chai-actions/ai/design-system-schema"; +import { formatBytes, MCP_IMAGE_MAX_BYTES } from "~/server/chai-actions/ai/remote-image-constants"; +import { designTokenUpdateSchema } from "~/server/chai-actions/website/design-token-updates"; +import { chaiThemePatchShape } from "~/server/chai-actions/website/theme-patch"; + /** * Single source of truth for the AI page-edit tool contract, shared by two * surfaces: * - * - the builder (AI SDK v6 `tool()` in ai-edit-page-tools.ts), which prepends a - * `task` progress-label field and executes edits on the client's JSON state; - * - the MCP server (mcp-handler raw Zod shapes in lib/mcp/tools/*), which - * prepends a `url` field and applies edits to the page's draft blocks. + * - the builder (AI SDK v6 `tool()` in ai-edit-page-tools.ts), which operates + * on the single open page and prepends a `task` progress-label field; + * - the MCP server (src/plugins/mcp/server/tools/*), which operates across + * pages and prepends a `url` field. * - * The field builders take the caller's `z` instance because the app (zod v3) and - * the SDK (zod v4) resolve different `zod` copies — exporting schema *objects* - * would bind them to one version. `buildAiEditToolFields(z)` returns raw field - * records (no `z.object(...)`) so each surface composes its own object shape. + * Keeping descriptions, permissions, and input field shapes here ensures MCP + * and Builder AI stay permanently in lockstep (verified by builder-ai-mcp-sync.test.ts). */ /** Any Zod-like namespace (v3 or v4) — only the subset used below is required. */ type ZodLike = { string: () => any; number: () => any; + boolean: () => any; any: () => any; array: (schema: any) => any; + object: (shape: any) => any; record: (keys: any, values: any) => any; }; export const AI_EDIT_TOOL_DESCRIPTIONS = { + read_blocks: + "Read the JSON of one or more existing blocks by bid (set includeDescendants: true to inspect a whole section). " + + "PREFERRED over read_block_html for inspecting or editing copy, styles, media, links, and custom-block or library-block props with update_block_props.", + update_block_props: + "Patch JSON props on one or more existing blocks by bid without rewriting HTML. " + + "PREFERRED over edit_block for copy, styles, images, links, and custom-block or library-block prop updates. Call read_blocks first to inspect current props.", read_block_html: "Read the full current HTML of one or more existing blocks by their bid (from the page outline). " + - "ALWAYS call this before edit_block — never guess a block's markup. Batch all bids you need into one call.", + "Use only when restructuring HTML markup with edit_block; for prop, copy, or style edits prefer read_blocks and update_block_props.", + get_page_blocks: + "Get current draft blocks and page metadata as raw JSON. Use this for inspection or export; for editing, prefer the page outline, then read_blocks (or read_block_html for HTML rewrites). Keep raw block JSON internal unless the user explicitly asks for it.", edit_block: - "Replace one existing block (identified by bid) with new HTML. The html must be the complete replacement " + - "for the target element. Call read_block_html for the target first.", + "Replace one existing block (identified by bid) with new HTML when restructuring markup or child hierarchy. " + + "For copy, style, media, link, or custom-block prop changes, prefer read_blocks + update_block_props instead. Call read_block_html for the target first.", add_blocks: "Insert new HTML into the page. Use for new sections/elements built from standard HTML and special blocks " + "(repeater, partial-block, icon). Do NOT use for registered custom blocks — use add_custom_block.", remove_blocks: "Remove one or more existing blocks from the page by their block IDs (bid attribute). Use when the user asks to delete, clear, or replace content.", add_custom_block: - "Add a registered custom block to the page using its schema-validated props. Use this instead of HTML for registered custom blocks. Unknown types return an error listing valid types.", + "Add ONE registered custom block to the page using its schema-validated props. Prefer this over add_blocks whenever a cataloged custom block fits the requested section or component. When multiple variants exist for the same section, pick the single best fit and insert only one — never add multiple variants for one request unless asked. Unknown types return an error listing valid types.", + get_library_blocks: + "List reusable pre-built blocks from the site's block library (sections, hero layouts, forms, cards, etc.). Call before building a section from scratch when no registered custom block fits; filter optionally by query or group.", + add_library_block: + "Insert ONE reusable block from the site's block library by its blockId (from get_library_blocks). Pick the single best-fitting template per requested section (never add multiple alternatives unless asked). Generates fresh IDs and returns the inserted block IDs and outline so you can refine copy or props afterward with read_blocks and update_block_props.", bind_prop: "Set a data binding on a specific prop of an existing block. The binding path must come from the page's available data binding paths provided in your context — do not invent paths.", get_partial_blocks: @@ -48,8 +70,62 @@ export const AI_EDIT_TOOL_DESCRIPTIONS = { get_page_outline: "Get the compact outline of a page: one line per block as `bid | type | name | text`, indented by nesting. " + "Call this first to understand a page's structure, then read_block_html for the blocks you want to edit.", + get_block_translations: + "Read a page's per-language copy for one language: every translatable block prop with its fallback-language source and the stored translation (null when that language still shows the source). kind text is copy to translate; kind asset (images, links, video URLs) is overridden per language only when the user asks. Use missingOnly: true to find untranslated copy. Paged by 150 entries via nextOffset.", + update_block_translations: + "Write translated values for one language onto the page's blocks, as prop-{lang} next to the fallback-language prop, without touching the fallback-language copy or the layout. Use when translating a page and after any copy edit that returns \"Translations to sync\". Translate from the source, keep the same value shape, HTML markup, {{bindings}} exactly, and URLs. null or empty string removes a translation. The batch is validated as a whole.", + get_page_seo: + "Read the page's draft SEO as structured JSON: search title, description, canonical URL and robots flags; Open Graph title, description and image plus extra meta name/content pairs; and the JSON-LD document. Call this before update_page_seo so a partial update starts from the current values.", + update_page_seo: + "Update the page's draft SEO fields: title, description, canonicalUrl, noIndex, noFollow, ogTitle, ogDescription, ogImage, metaOther and jsonLD. Only the fields you pass change; metaOther and jsonLD replace the whole set or document. Write SEO text in the page's content language.", + upload_image: + `Upload an image into this site's media library and return its permanent URL. Pass exactly one of dataUrl (a base64 "data:image/…;base64,…" URL) or sourceUrl (a public http(s) URL downloaded server-side up to ${formatBytes(MCP_IMAGE_MAX_BYTES)}). ` + + "Uploading only stores the image: place it with edit_block or add_blocks using the returned URL, alt text in the page's language, and the reported width/height.", + get_design_system: + "Read the site's design system at the start of any task that adds or restyles content: its written rules (north star, colours, typography, layout, elevation, shapes, components, do's and don'ts), site context, theme fonts/radius/colours, design tokens, and the page's brief. When enabled it also returns the rules in force. When none is set up, keep the usual styling rules and start setup only when the user asks.", + save_design_system: + "Save the site's design system after the user approved it in setup (see get_design_guide, topic setup), or update part of it later. Only the fields you pass change. A new design system needs northStar and mode and is saved disabled until the user confirms enabled: true. Also saves site context (product) and pageBrief.", + check_page_design: + "Run deterministic design checks on the page's draft blocks and list findings, errors first: AI-template tells, steps outside the site's system (raw palette colours, unknown/archived dt# tokens, off-theme fonts, banned words), and craft problems (heading order, hover states, touch targets, measure, theme contrast). Pass blockIds to scope to specific blocks and their descendants.", + get_design_guide: + "Get a design playbook written for this builder: setup, craft-floor, critique, audit, polish, typography, color, layout, motion, copy, bolder, quieter. Call it before acting on that kind of request.", + update_site_theme: + "Change the site-wide theme draft: heading and body fonts, base radius, and colours as [light, dark] pairs. Only what you pass changes. Use for a site-wide restyle the user approved, never to fix one page. Fonts must be registered and every surface/foreground pair must stay readable.", + update_design_tokens: + "Restyle the site's existing design tokens (dt# class recipes such as dt#btn-primary or dt#card) so a component changes everywhere at once. Never creates a new token. Call get_design_system with includeTokenValues first to see current values.", } as const; +/** + * Canonical permissions required for each shared tool across MCP and Builder AI. + * Builder AI hides tools whose permissions the caller lacks (when userAccess is present). + */ +export const AI_SHARED_TOOL_PERMISSIONS: Record = { + read_blocks: ["pages:read"], + update_block_props: ["pages:read", "pages:update"], + read_block_html: ["pages:read"], + get_page_blocks: ["pages:read"], + edit_block: ["pages:read", "pages:update"], + add_blocks: ["pages:read", "pages:update"], + remove_blocks: ["pages:read", "pages:update"], + add_custom_block: ["pages:read", "pages:update"], + get_library_blocks: ["library:read"], + add_library_block: ["library:read", "pages:read", "pages:update"], + bind_prop: ["pages:read", "pages:update"], + get_partial_blocks: ["pages:read"], + get_pages_list: ["pages:read"], + get_block_translations: ["pages:read"], + update_block_translations: ["pages:read", "pages:update"], + get_page_seo: ["pages:read"], + update_page_seo: ["pages:read", "pages:update", "pages:edit_seo"], + upload_image: ["assets:create"], + get_design_system: ["ai:read", "pages:read"], + save_design_system: ["ai:read", "ai:use", "pages:read"], + check_page_design: ["ai:read", "pages:read"], + get_design_guide: ["pages:read"], + update_site_theme: ["theme:edit"], + update_design_tokens: ["design_tokens:edit"], +}; + /** * How both surfaces must author links to site pages. Executors back this up by * rewriting a slug that matches a known page, but only a reference the model @@ -63,42 +139,261 @@ export const AI_INTERNAL_LINK_RULES = [ ] as const; /** - * Per-tool input field records (excluding the surface-specific `task`/`url` - * fields). Field order is deliberate for edit_block/add_blocks: non-html fields - * come before `html` so streaming clients learn the target before HTML flows. + * Per-tool input field records for the core block-edit tools (excluding the + * surface-specific `task`/`url` fields). Takes a Zod-like namespace so callers + * with separate zod copies can compose their own object shape. */ -export const buildAiEditToolFields = (z: ZodLike) => ({ +export const buildAiEditToolFields = (zInstance: ZodLike) => ({ + read_blocks: { + blockIds: zInstance.array(zInstance.string()).min(1).describe("bids of the blocks to read"), + includeDescendants: zInstance + .boolean() + .optional() + .describe("When true, also return every descendant block of each requested bid. Defaults to false."), + }, + update_block_props: { + updates: zInstance + .array( + zInstance.object({ + blockId: zInstance.string().describe("bid of the block to update"), + props: zInstance + .record(zInstance.string(), zInstance.any()) + .describe( + "JSON object of camelCase props to merge onto the block (only pass changed keys). Preserve '#styles:' prefix on style props.", + ), + }), + ) + .min(1) + .max(50) + .describe("One or more block prop patches applied atomically; all updates are validated together."), + }, read_block_html: { - blockIds: z.array(z.string()).min(1).describe("bids of the blocks to read"), + blockIds: zInstance.array(zInstance.string()).min(1).describe("bids of the blocks to read"), }, edit_block: { - blockId: z.string().describe("bid of the block to replace"), - html: z.string().describe("Full replacement HTML for the target element"), + blockId: zInstance.string().describe("bid of the block to replace"), + html: zInstance.string().describe("Full replacement HTML for the target element"), }, add_blocks: { // nullish: models routinely send null instead of omitting optional fields - parentId: z.string().nullish().describe("bid of the parent container; omit to add at page root"), - position: z.number().nullish().describe("Child index position; -1 or omit to append at end"), - html: z.string().describe("HTML to insert"), + parentId: zInstance.string().nullish().describe("bid of the parent container; omit to add at page root"), + position: zInstance.number().nullish().describe("Child index position; -1 or omit to append at end"), + html: zInstance.string().describe("HTML to insert"), }, remove_blocks: { - ids: z.array(z.string()).min(1).describe("Array of block IDs (bid attribute values) to remove"), + ids: zInstance.array(zInstance.string()).min(1).describe("Array of block IDs (bid attribute values) to remove"), }, add_custom_block: { - type: z.string().describe("Block type exactly as listed in the catalog, e.g. 'ProductCard'"), - parentId: z.string().nullish().describe("bid of the parent block, or omit to add at page root"), - position: z.number().nullish().describe("Child index position; -1 or omit to append at end"), - props: z - .record(z.string(), z.any()) + type: zInstance.string().describe("Block type exactly as listed in the catalog, e.g. 'ProductCard'"), + parentId: zInstance.string().nullish().describe("bid of the parent block, or omit to add at page root"), + position: zInstance.number().nullish().describe("Child index position; -1 or omit to append at end"), + props: zInstance + .record(zInstance.string(), zInstance.any()) .describe( "Block props as a JSON object using camelCase keys matching the catalog schema. Use {{path.to.data}} values for bound props.", ), }, + add_library_block: { + blockId: zInstance.string().describe("ID of the library block returned by get_library_blocks"), + parentId: zInstance.string().nullish().describe("bid of the parent block, or omit to add at page root"), + position: zInstance.number().nullish().describe("Child index position; -1 or omit to append at end"), + }, bind_prop: { - blockId: z.string().describe("bid of the block to update"), - propName: z.string().describe("camelCase prop name on the block"), - bindingPath: z + blockId: zInstance.string().describe("bid of the block to update"), + propName: zInstance.string().describe("camelCase prop name on the block"), + bindingPath: zInstance .string() .describe("Full binding expression including double braces, e.g. '{{product.name}}' or '{{$index.title}}'"), }, }); + +const dsSection = (field: keyof typeof DS, what: string) => DS[field].describe(`${what} Markdown; null empties it.`); + +/** + * Canonical input field records for ALL shared single-page tools (excluding `url` / `task`). + * Consumed by both MCP tool metas and Builder AI `ai-edit-page-tools.ts` so field names + * and validation stay permanently in sync. + */ +export const SHARED_AI_TOOL_FIELDS = { + ...buildAiEditToolFields(z), + get_page_blocks: {}, + get_partial_blocks: {}, + get_library_blocks: { + query: z + .string() + .optional() + .describe("Optional case-insensitive keyword filter matching block name, group, or description."), + group: z + .string() + .optional() + .describe('Optional case-insensitive group/category filter (e.g. "hero", "section", "cta").'), + }, + get_pages_list: { + mode: z + .enum(["draft", "live"]) + .optional() + .default("draft") + .describe('Whether to list draft or live (published) pages. Defaults to "draft".'), + }, + get_block_translations: { + lang: z + .string() + .optional() + .describe( + 'Language code to read translations for, e.g. "en". Defaults to the active variant language; required on a primary-language page.', + ), + blockIds: z.array(z.string()).optional().describe("Limit to these bids. Omit for the whole page."), + missingOnly: z + .boolean() + .optional() + .describe("True to return only text props that have no translation in this language yet."), + offset: z.number().int().min(0).optional().describe("Entry offset for paging; pass the previous nextOffset."), + }, + update_block_translations: { + lang: z + .string() + .optional() + .describe( + 'Language code the values are written in, e.g. "en". Defaults to the active variant language; required on a primary-language page. Never the site fallback language.', + ), + translations: z + .array( + z.object({ + blockId: z.string().describe("bid of the block"), + prop: z.string().describe('Translatable prop name as reported by get_block_translations, e.g. "content"'), + value: z + .union([z.string(), z.array(z.unknown()), z.record(z.string(), z.unknown()), z.null()]) + .describe( + 'Translated value, same shape as the source (string for copy, including any HTML markup). null or "" removes the translation so the source shows.', + ), + }), + ) + .min(1) + .max(500) + .describe("Translations to write; the whole batch is rejected if any entry is invalid."), + }, + get_page_seo: {}, + update_page_seo: { + title: z + .string() + .max(2000) + .optional() + .describe("Search/browser title (). Pass an empty string to clear it."), + description: z.string().max(2000).optional().describe("Meta description. Pass an empty string to clear it."), + canonicalUrl: z + .string() + .max(2000) + .optional() + .describe( + "Canonical URL: absolute http(s) URL, absolute path starting with /, or a {{binding}}. Empty string falls back to the page path.", + ), + noIndex: z.boolean().optional().describe("True to add noindex to the robots meta tag."), + noFollow: z.boolean().optional().describe("True to add nofollow to the robots meta tag."), + ogTitle: z.string().max(2000).optional().describe("Open Graph title; falls back to title when empty."), + ogDescription: z + .string() + .max(2000) + .optional() + .describe("Open Graph description; falls back to description when empty."), + ogImage: z + .string() + .max(2000) + .optional() + .describe("Open Graph image: absolute http(s) URL, absolute path starting with /, or a {{binding}}."), + metaOther: z + .record(z.string(), z.string()) + .optional() + .describe('Extra <meta name="key" content="value"> pairs. Replaces the whole set; pass {} to remove them all.'), + jsonLD: z + .union([z.record(z.string(), z.unknown()), z.array(z.unknown()), z.string(), z.null()]) + .optional() + .describe( + "JSON-LD document as an object, an array of objects, or its JSON string. Replaces the whole document; null or {} clears it.", + ), + }, + upload_image: { + dataUrl: z + .string() + .optional() + .describe( + 'Base64 data URL of the image, e.g. "data:image/png;base64,iVBORw0K…". Mutually exclusive with sourceUrl.', + ), + sourceUrl: z + .string() + .optional() + .describe( + "Public http(s) URL of an image to download server-side. Mutually exclusive with dataUrl. Private, loopback and internal addresses are refused.", + ), + name: z + .string() + .max(200) + .optional() + .describe( + 'File name for the media library. The extension is set from the actual image type; defaults to the source file name or "image".', + ), + folderId: z + .string() + .max(200) + .optional() + .describe("Media-library folder to file the image under. Omit for the library root."), + alt: z + .string() + .max(500) + .optional() + .describe( + "Short description of the image, stored on the asset in the site's fallback language. Also use it as the alt attribute when placing the image on a page.", + ), + }, + get_design_system: { + includeTokenValues: z + .boolean() + .optional() + .describe("Also list the classes of every design token (needed before restyling tokens)."), + }, + save_design_system: { + enabled: DS.enabled.describe( + "true only after the user confirmed enabling the design system for the site; false pauses it (nothing is enforced).", + ), + northStar: DS.northStar.describe("One line naming the creative direction. Required when creating."), + mode: DS.mode.describe( + "Default visitor mode: persuade (marketing), operate (tools), read (docs), experience (portfolio). Required when creating.", + ), + colorStrategy: DS.colorStrategy.describe("restrained, committed, full-palette or drenched; null clears it."), + overview: dsSection("overview", "Creative north star, personality, key characteristics."), + colors: dsSection("colors", "Colour roles and named rules, in theme terms."), + typography: dsSection("typography", "Type roles as class recipes (Display, H1, H2, H3, Body, Small)."), + layout: dsSection("layout", "Section padding, container, grid, spacing rhythm, responsive changes."), + elevation: dsSection("elevation", "Shadows or tonal layering, and when each is used."), + shapes: dsSection("shapes", "Radius, borders, recurring geometry."), + components: dsSection("components", "Which existing dt# token or recipe to use for each job, with states."), + dosAndDonts: dsSection("dosAndDonts", "Concrete guardrails."), + antiReferences: DS.antiReferences.describe("Looks this site refuses; null clears them."), + product: z + .strictObject({ + siteContext: z.string().max(4000).optional(), + tone: z.string().max(200).optional(), + bannedWords: z.string().max(1000).optional(), + }) + .optional() + .describe("Site context learned in the interview: siteContext, tone, bannedWords (comma-separated)."), + replace: z.boolean().optional().describe("Start over instead of changing the saved design system."), + pageBrief: z + .strictObject(chaiPageDesignBriefInputShape) + .optional() + .describe("The page's brief: mode, thesis (the idea it owns), story, firstViewport, notes."), + }, + check_page_design: { + blockIds: z + .array(z.string()) + .max(200) + .optional() + .describe("Check only these blocks and their descendants (bids from the page outline)."), + }, + get_design_guide: { + topic: z.enum(DESIGN_GUIDE_TOPICS).describe("The playbook to return."), + }, + update_site_theme: chaiThemePatchShape, + update_design_tokens: { + tokens: z.array(designTokenUpdateSchema).min(1).max(40).describe("The tokens to change."), + }, +}; diff --git a/src/server/chai-actions/ai/design/compose-design-brief.ts b/src/server/chai-actions/ai/design/compose-design-brief.ts new file mode 100644 index 000000000..3855ee21b --- /dev/null +++ b/src/server/chai-actions/ai/design/compose-design-brief.ts @@ -0,0 +1,214 @@ +import { CHAI_BUILT_IN_DESIGN_TOKENS } from "~/constants/BUILTIN_TOKENS"; +import { CHAI_THEME_OPTIONAL_COLOR_KEYS } from "~/constants/THEME_COLOR_KEYS"; +import { designSystemStatus, missingDesignSystemSections } from "~/server/chai-actions/ai/design-system-schema"; +import type { ChaiTheme } from "~/types/chaibuilder-editor-props"; +import { + CHAI_DESIGN_SYSTEM_SECTIONS, + CHAI_DESIGN_SYSTEM_SECTION_TITLES, + type ChaiDesignChecksMode, + type ChaiDesignSystem, + type ChaiPageDesignBrief, +} from "~/types/design-system"; +import type { ChaiDesignTokens } from "~/types/types"; +import { rulesInForce } from "./rules-in-force"; + +/** @internal */ +export type DesignBriefInput = { + siteName?: string; + designSystem: ChaiDesignSystem | null; + /** The site AI context: siteContext, tone, look, bannedWords. */ + product: Record<string, unknown>; + theme: Partial<ChaiTheme> | null; + designTokens: ChaiDesignTokens; + /** Font families the site can use (the registered fonts). */ + fonts: string[]; + page?: { name: string; slug: string; brief: ChaiPageDesignBrief | null } | null; + includeTokenValues?: boolean; + checks: ChaiDesignChecksMode; +}; + +export const NOT_SET_UP_BRIEF = `# Design system: not set up +This site has no design system. Keep following the styling instructions as they are; there are no extra rules to apply. +Do not start a design-system setup on your own. When the user asks for one, asks for a new look or a redesign, or wants their pages to look consistent, offer it in one line, and start only when they ask for it or say yes: then call get_design_guide with topic "setup" and follow it. +What follows is the site's current look, the starting point for a setup.`; + +const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max).trimEnd()}…` : text); +const str = (value: unknown) => (typeof value === "string" ? value.trim() : ""); + +function productSection(product: Record<string, unknown>): string | null { + const lines = [ + str(product.siteContext) && `- About the site: ${clip(str(product.siteContext), 1200)}`, + str(product.tone) && `- Tone: ${str(product.tone)}`, + str(product.look) && `- Look (from the AI settings): ${str(product.look)}`, + str(product.bannedWords) && `- Banned words: ${str(product.bannedWords)}`, + ].filter(Boolean); + return lines.length ? `## Site context\n${lines.join("\n")}` : null; +} + +function systemSections(ds: ChaiDesignSystem): string { + const head = [ + `North star: ${ds.northStar}`, + `Default visitor mode: ${ds.mode}${ds.colorStrategy ? ` · Colour strategy: ${ds.colorStrategy}` : ""}`, + ].join("\n"); + const sections = CHAI_DESIGN_SYSTEM_SECTIONS.map( + (section) => `## ${CHAI_DESIGN_SYSTEM_SECTION_TITLES[section]}\n${ds[section].trim() || "(not written yet)"}`, + ); + const anti = ds.antiReferences?.length + ? [`## Refuses\n${ds.antiReferences.map((item) => `- ${item}`).join("\n")}`] + : []; + return [head, ...sections, ...anti].join("\n\n"); +} + +const COLOR_ROWS: string[][] = [ + ["background", "foreground"], + ["card", "card-foreground"], + ["popover", "popover-foreground"], + ["primary", "primary-foreground"], + ["secondary", "secondary-foreground"], + ["muted", "muted-foreground"], + ["accent", "accent-foreground"], + ["destructive", "destructive-foreground"], + ["border", "input", "ring"], +]; + +function radiusLine(radius: string | undefined): string | null { + if (!radius) return null; + const px = /^(\d+(?:\.\d+)?)px$/.exec(radius); + if (!px) return `- Radius: ${radius} (rounded-lg).`; + const value = Number(px[1]); + const step = (n: number) => `${Math.max(0, value - n)}px`; + return `- Radius: ${radius}: rounded-lg is ${radius}, rounded-md ${step(2)}, rounded-sm ${step(4)}.`; +} + +function themeSection(theme: Partial<ChaiTheme> | null, fonts: string[]): string | null { + if (!theme) return null; + const lines: string[] = []; + const heading = theme.fontFamily?.heading; + const body = theme.fontFamily?.body; + if (heading || body) { + lines.push( + `- Fonts: headings "${heading ?? "?"}" (font-heading, applied to h1–h6 automatically); text "${body ?? "?"}" (font-body, applied to the page body).`, + ); + } + const radius = radiusLine(theme.borderRadius); + if (radius) lines.push(radius); + + const colors = (theme.colors ?? {}) as Record<string, [string, string] | undefined>; + const describe = (key: string) => { + const pair = colors[key]; + return Array.isArray(pair) ? `${key} ${pair[0]} | ${pair[1]}` : null; + }; + const extras: string[][] = []; + for (let i = 0; i < CHAI_THEME_OPTIONAL_COLOR_KEYS.length; i += 2) { + extras.push([CHAI_THEME_OPTIONAL_COLOR_KEYS[i], CHAI_THEME_OPTIONAL_COLOR_KEYS[i + 1]]); + } + const rows = [...COLOR_ROWS, ...extras].map((row) => row.map(describe).filter(Boolean).join(" · ")).filter(Boolean); + if (rows.length) { + lines.push( + `- Colours as light | dark, used as bg-*, text-* and border-* utilities:\n${rows.map((row) => ` ${row}`).join("\n")}`, + ); + } + if (fonts.length) { + lines.push( + fonts.length <= 60 + ? `- Fonts the site can use: ${fonts.join(", ")}.` + : `- ${fonts.length} fonts are registered; the theme accepts registered families only.`, + ); + } + return lines.length ? `## Theme (draft values)\n${lines.join("\n")}` : null; +} + +const tokenFamily = (id: string) => id.slice(3).split("-")[0]; + +function tokensSection(siteTokens: ChaiDesignTokens, includeValues: boolean): string { + const lines: string[] = []; + + const restyled = new Set( + Object.keys(CHAI_BUILT_IN_DESIGN_TOKENS).filter((id) => { + const override = siteTokens[id]; + return override && !override.archived && override.value !== CHAI_BUILT_IN_DESIGN_TOKENS[id].value; + }), + ); + const families = new Map<string, string[]>(); + for (const id of Object.keys(CHAI_BUILT_IN_DESIGN_TOKENS)) { + if (siteTokens[id]?.archived) continue; + const family = tokenFamily(id); + families.set(family, [...(families.get(family) ?? []), `${id}${restyled.has(id) ? "*" : ""}`]); + } + lines.push(...[...families.values()].map((ids) => `- ${ids.join(", ")}`)); + const custom = Object.entries(siteTokens).filter( + ([id, token]) => !(id in CHAI_BUILT_IN_DESIGN_TOKENS) && token && !token.archived, + ); + + const valueLines: string[] = []; + if (includeValues) { + for (const [id, token] of Object.entries(CHAI_BUILT_IN_DESIGN_TOKENS)) { + if (siteTokens[id]?.archived) continue; + valueLines.push(`- ${id} (${token.name}): ${siteTokens[id]?.value ?? token.value}`); + } + } else { + for (const id of restyled) valueLines.push(`- ${id} (restyled): ${clip(siteTokens[id].value, 160)}`); + } + for (const [id, token] of custom) { + valueLines.push( + `- ${id} "${token.name}"${token.description ? ` (${token.description})` : ""}: ${clip(token.value, 160)}`, + ); + } + + return [ + `## Design tokens\nReuse these; never invent one. Put them first in a class list: class="dt#btn dt#btn-primary px-6". * marks a built-in this site restyled.`, + lines.join("\n"), + ...(valueLines.length ? [`Values:\n${valueLines.join("\n")}`] : []), + ].join("\n"); +} + +function pageSection(page: NonNullable<DesignBriefInput["page"]>, suggest: boolean): string | null { + const title = `## Page brief: ${page.name} (${page.slug || "partial"})`; + if (!page.brief) { + return suggest + ? `${title}\nNone yet. Before building this page from scratch, propose one (visitor mode, thesis, first viewport) and save it with save_design_system (url and pageBrief).` + : null; + } + const b = page.brief; + const lines = [ + `- Visitor mode: ${b.mode}`, + `- Thesis: ${b.thesis}`, + b.story && `- Story: ${b.story}`, + b.firstViewport && `- First viewport: ${b.firstViewport}`, + b.notes && `- Notes: ${b.notes}`, + ].filter(Boolean); + return `${title}\n${lines.join("\n")}`; +} + +/** + * The design brief an agent (MCP or Builder AI) works from: the site's written design system, + * the theme and tokens that are its values, the page brief, and — only when the design system + * is enabled — the rules in force. + * @internal + */ +export function composeDesignBrief(input: DesignBriefInput): string { + const status = designSystemStatus(input.designSystem); + const baseline = [ + productSection(input.product), + themeSection(input.theme, input.fonts), + tokensSection(input.designTokens, input.includeTokenValues === true), + ]; + if (status === "not_set_up" || !input.designSystem) { + return [NOT_SET_UP_BRIEF, ...baseline].filter((part): part is string => !!part).join("\n\n"); + } + const ds = input.designSystem; + const enabled = status !== "disabled"; + + const header = enabled + ? `# Design system: enabled${status === "partial" ? ` (incomplete: ${missingDesignSystemSections(ds).join(", ")} not written yet)` : ""}\nFollow it on every page you build or edit${input.siteName ? ` on ${input.siteName}` : ""}. The theme and tokens are the values; the sections are the rules for using them. Never invent a palette, font, radius or card style for one page.` + : `# Design system: saved, not enabled\nThis site has a saved design system that is NOT enabled: keep following the styling instructions as they are, and treat what follows as reference only. Enable it only when the user confirms, with save_design_system and enabled: true.`; + + const parts = [ + header, + systemSections(ds), + ...baseline, + input.page ? pageSection(input.page, enabled) : null, + enabled ? rulesInForce(input.checks) : null, + ]; + return parts.filter((part): part is string => !!part).join("\n\n"); +} diff --git a/src/server/chai-actions/ai/design/feature.ts b/src/server/chai-actions/ai/design/feature.ts new file mode 100644 index 000000000..0b9e1ec27 --- /dev/null +++ b/src/server/chai-actions/ai/design/feature.ts @@ -0,0 +1,30 @@ +import { getConfigFeatures } from "~/server/defaults/config-registry"; +import type { ChaiDesignChecksMode, ChaiDesignSystemFeature } from "~/types/design-system"; +import type { ResolvedChaiBuilderServerConfig } from "~/types/server-config"; + +/** + * The deployment switch for the design-system tools across MCP and Builder AI. + * + * `true` turns it on with warning-level design checks; `{ designChecks: "strict" }` makes + * error findings reject a block write; `"off"` keeps the tools without write-time checks. + * Omitted or false: nothing is registered and every existing flow is unchanged. + * @internal + */ +export type ChaiDesignSystemOption = boolean | { designChecks?: ChaiDesignChecksMode }; + +export const DESIGN_SYSTEM_OFF: ChaiDesignSystemFeature = { enabled: false, designChecks: "off" }; + +/** The feature value to store, or null when the option leaves the feature off (no key is set). */ +export function resolveDesignSystemFeature(option: ChaiDesignSystemOption | undefined): ChaiDesignSystemFeature | null { + if (!option) return null; + if (option === true) return { enabled: true, designChecks: "warn" }; + return { enabled: true, designChecks: option.designChecks ?? "warn" }; +} + +/** The switch at request time. @internal */ +export function getDesignSystemFeature(): ChaiDesignSystemFeature { + return getConfigFeatures().designSystem ?? DESIGN_SYSTEM_OFF; +} + +export const isDesignSystemFeatureOn = (config: Readonly<ResolvedChaiBuilderServerConfig>): boolean => + config.features?.designSystem?.enabled === true; diff --git a/src/server/chai-actions/ai/design/guides/index.ts b/src/server/chai-actions/ai/design/guides/index.ts new file mode 100644 index 000000000..d75b61601 --- /dev/null +++ b/src/server/chai-actions/ai/design/guides/index.ts @@ -0,0 +1,43 @@ +import { BANS, CRAFT_FLOOR } from "../rules-in-force"; +import { + AUDIT_GUIDE, + BOLDER_GUIDE, + COLOR_GUIDE, + COPY_GUIDE, + CRITIQUE_GUIDE, + LAYOUT_GUIDE, + MOTION_GUIDE, + POLISH_GUIDE, + QUIETER_GUIDE, + TYPOGRAPHY_GUIDE, +} from "./refine"; +import { SETUP_GUIDE } from "./setup"; + +const CRAFT_FLOOR_GUIDE = `# Craft floor +The quality floor every page should meet, and the patterns that make a page read as machine-made. + +${CRAFT_FLOOR} + +${BANS} + +check_page_design verifies what can be read from the blocks; look at the preview for the rest.`; + +export const DESIGN_GUIDES = { + setup: SETUP_GUIDE, + "craft-floor": CRAFT_FLOOR_GUIDE, + critique: CRITIQUE_GUIDE, + audit: AUDIT_GUIDE, + polish: POLISH_GUIDE, + typography: TYPOGRAPHY_GUIDE, + color: COLOR_GUIDE, + layout: LAYOUT_GUIDE, + motion: MOTION_GUIDE, + copy: COPY_GUIDE, + bolder: BOLDER_GUIDE, + quieter: QUIETER_GUIDE, +} as const; + +export type DesignGuideTopic = keyof typeof DESIGN_GUIDES; +export const DESIGN_GUIDE_TOPICS = Object.keys(DESIGN_GUIDES) as [DesignGuideTopic, ...DesignGuideTopic[]]; + +export const getDesignGuide = (topic: DesignGuideTopic): string => DESIGN_GUIDES[topic]; diff --git a/src/server/chai-actions/ai/design/guides/refine.ts b/src/server/chai-actions/ai/design/guides/refine.ts new file mode 100644 index 000000000..2478f5cd4 --- /dev/null +++ b/src/server/chai-actions/ai/design/guides/refine.ts @@ -0,0 +1,97 @@ +/** + * Refinement playbooks: what to change, what stays, and how to verify, for each kind of + * design request. Shared by Builder AI and MCP `get_design_guide`. + */ + +export const TYPOGRAPHY_GUIDE = `# Typography +Use when type feels generic, flat or hard to read. +Assess first: is the hierarchy obvious without reading? Are there more sizes than roles? Is body text comfortable at mobile width? +- Headings take the theme heading font automatically (h1–h6); text takes the body font. Switch with font-heading or font-body; never font-serif, font-sans or font-[…], which bypass the theme. +- Define roles, not sizes: 4–6 class recipes in the design system's Typography section (Display, H1, H2, H3, Body, Small) and reuse them. Example H2: "text-3xl md:text-4xl font-semibold tracking-tight text-balance". +- Build contrast with several means at once: size, weight, space and colour (text-foreground against text-muted-foreground). +- Body: text-base or text-lg with leading-relaxed; measure 65–75 characters (max-w-prose, max-w-2xl). +- Display: tighten tracking on large sizes (tracking-tight), cap at text-6xl, scale down on mobile (text-4xl md:text-6xl). +- Light text on dark surfaces needs one step more leading and weight. +- One h1 per page; don't skip levels; choose the level for structure and the size with classes. +Avoid: uppercase tracked kickers above headings, monospace as decoration, whole paragraphs in italics, long centred paragraphs. +Verify: check_page_design (heading-order, multiple-h1, off-theme-font, long-measure), then read the page by its headings alone.`; + +export const COLOR_GUIDE = `# Colour +Assess first: which colours are brand commitments, what each surface, text, action and state uses, and whether colour leads the eye to the primary action. +- Colour only through theme roles: background/foreground, card, muted, accent, primary, secondary, destructive, border, input, ring. Every surface pairs with its -foreground. +- Keep the design system's strategy (restrained, committed, full palette or drenched). Let one colour own a deliberate region or role; don't sprinkle accents. +- Secondary text: text-muted-foreground, or a tint of the surface's foreground (text-primary-foreground/80). Never gray on colour. +- Quiet emphasis with tints: bg-primary/10 text-primary for badges and highlights. +- Contrast: body 4.5:1, large text and controls 3:1, in light AND dark. Dark mode is designed, not inverted. +- A palette change is a site-wide theme change (the theme tools), never raw classes on one page. +Avoid: purple-to-blue gradients, gradient text, pure black or white fills, raw palette classes (bg-blue-600, text-gray-500), hex values in classes, colour as the only signal. +Verify: check_page_design (raw-palette-color, gray-on-colored-bg, same-family-pair, theme-contrast).`; + +export const LAYOUT_GUIDE = `# Layout and spacing +Assess first (squint test): what is read first, second, third? Do related items group without boxes? Is the rhythm deliberate or monotonous? +- Every page section uses dt#content-gutter-y on the outer <section> and dt#site-content-width dt#content-gutter-x on its inner content wrapper (never hand-written section py-/px-/max-w- or breakpoint prefixes on dt# tokens); reuse one internal spacing scale across pages (e.g. stack gap-4 / gap-8, grid gap-6). +- Tight inside a group, generous between groups; more space above a heading than below it. +- Group by proximity before adding containers; use gap for sibling rhythm. +- Vary composition between sections (split, full-bleed image, list, quote, figures row) inside the same grammar; don't repeat heading + three cards down the page. +- Density follows use: marketing pages breathe, tools are compact. +- Mobile first: stack on small screens and reflow at md/lg; primary actions at least 44px tall. +Avoid: cards inside cards, boxing every block, centring everything, the same spacing everywhere, wrapper divs that do nothing. +Verify: check_page_design (section-layout-tokens, nested-cards, repeated-section-layout, small-touch-target), then look at the preview at mobile width.`; + +export const MOTION_GUIDE = `# Motion +- One authored moment per page (the hero reveal, one key illustration), easing out, 400–700ms. Other sections arrive without an entrance animation. +- Entrance animations use data-animation as described in the Animation instructions, never on content that must be visible at first paint. +- Hover and focus: transition-colors with duration-150 or duration-200. +- Motion must explain (reveal, connect, confirm), not decorate, and must respect reduced-motion settings. +Avoid: the same fade-in on every section, bounce or elastic easing, word-by-word text animations, scroll hijacking. +Verify: check_page_design (identical-entrance-animation).`; + +export const CRITIQUE_GUIDE = `# Critique +Deliver a review, not edits, unless the user asked for fixes. +1. Read: get_page_outline, read_block_html for the key sections, check_page_design. +2. Judge against the design system first (does the page follow its rules, north star and visitor mode?), then the visitor: can they tell what this is and what to do within five seconds? +3. Report: + - Overall impression (two sentences) and the single biggest opportunity. + - What works (two or three specifics). + - Priority issues (three to five), each tagged P0 (broken or blocking) to P3 (polish), with the block (bid), why it matters, the concrete fix, and the guide topic that applies. + - Visitor check: two visitors from the site's audience, and where each gets stuck. +4. Close with one to three pointed questions. +Write directly; never "consider exploring".`; + +export const AUDIT_GUIDE = `# Audit (technical quality) +Score 0–4 each, total /20: Accessibility (contrast, heading order, alt text, labels, focus), Responsiveness (mobile layout, touch targets, overflow), Theming (theme colours and fonts, tokens, dark mode), Consistency with the design system, Content (placeholder copy, empty links, banned words). +Use check_page_design for the mechanical pass and add what it cannot see: alt-text quality, link targets, copy. +Report the score and the findings, each tagged P0–P3 with the bid, the standard (WCAG where it applies) and the fix. Only real findings; no generic advice.`; + +export const POLISH_GUIDE = `# Polish +Polish is refinement, never a hidden redesign: keep the visual language, the content and the scope. +1. Get the system with get_design_system. Classify each inconsistency: a missing rule (propose adding it to the design system), a one-off style (replace it with the shared recipe or token), a mismatch with comparable sections, or a local defect. +2. Evidence: check_page_design on the page, then the preview at mobile and desktop widths. +3. Fix in order: broken, missing states, flow, visual inconsistencies, cleanup. +4. Pass over hierarchy, spacing rhythm, type roles, colour roles and contrast, states (hover, focus-visible, disabled, empty, error), copy (actions named, consistent terms) and alt text. +5. Run check_page_design again; stop when the errors are gone and every remaining warning is deliberate. Report what changed and what you verified.`; + +export const BOLDER_GUIDE = `# Bolder +Raise one named target to the conviction the rest of the page implies. Everything else stays exactly as it is. +- Use the system's own vocabulary at fuller strength: the display type role, a stronger dose of the chosen colour strategy, a full-bleed image, tighter tracking, a heavier weight. +- Make one decisive move completely instead of nudging five things. +- Contrast the target with its neighbours so it reads as a peak. +- Skeleton test: strip the copy. Does the structure alone still say what this section is? +No colours, fonts or effects the design system does not have; gradient text and glow are not boldness.`; + +export const QUIETER_GUIDE = `# Quieter +Lower the intensity; keep the personality and the function. +- Colour: move from full-strength fills to tints (bg-primary to bg-primary/10 with text-primary) or neutral surfaces; let neutrals dominate. +- Weight: step weights down (font-bold to font-semibold), thin or drop borders, remove decorative shadows. +- Space: add whitespace instead of dividers and boxes. +- Motion: remove flourishes; keep only functional transitions. +Keep the hierarchy: never make everything the same size or weight. Never gray text on a coloured surface.`; + +export const COPY_GUIDE = `# Copy +- Write in the page's content language and the design system's voice; never use the site's banned words. +- A heading names the benefit or the thing, not a slogan; one idea per heading. +- Buttons and links name the action and its object ("Book a table", "Download the menu"), never a bare "Submit", "Click here" or "Learn more". +- Errors name the problem and the way out. Empty states say what will appear and how to start. +- Prove, don't claim: specifics, numbers and examples over adjectives ("baked at 4am every day" over "fresh"). +- Cut filler: "We are passionate about…", "In today's fast-paced world…", "Unlock", "Elevate", "Seamless". +Verify: check_page_design (banned-word), then read the page aloud quickly.`; diff --git a/src/server/chai-actions/ai/design/guides/setup.ts b/src/server/chai-actions/ai/design/guides/setup.ts new file mode 100644 index 000000000..c1481be5e --- /dev/null +++ b/src/server/chai-actions/ai/design/guides/setup.ts @@ -0,0 +1,33 @@ +export const SETUP_GUIDE = `# Design system setup + +Goal: one written design system that every page of this site follows. You interview, propose ONE direction, the user approves, you save it, and it takes effect only when the user confirms enabling it. Do this only because the user asked for it or accepted your offer. + +## 0. Read what exists +Call get_design_system (fonts, palette, tokens, site context) and get_pages_list; read one or two finished pages with get_page_outline and read_block_html. The current look is evidence: ask whether to keep and sharpen it or to replace it. + +## 1. Interview — at most 3 questions per round, then wait +- Who is the main visitor, in what situation, and what must they do or believe? +- What does this business make possible, and what is genuinely different about it? +- What must be kept: logo, colours, fonts, voice, words to avoid, proof you can show? +Ask a second round only for real gaps. Never ask for CSS values, hex codes or a style label ("modern", "minimal"). + +## 2. Derive one direction +- Name the mechanism in one sentence: what the site does for the visitor. +- List seven concrete visual systems from the audience's own world (tools, publications, signage, packaging, places they know) across at least three material families. Fuse the strongest into ONE direction. +- Anti-reference check: if someone could guess the look from the category alone, rework it. Refuse the category default and the stock AI looks: cream + serif display + terracotta; near-black + neon glow; purple-to-blue gradient on white; everything in rounded cards. +- Light or dark: write one sentence of physical scene (who, where, under what light) and let it decide. +- Colour strategy: restrained (neutrals + one accent), committed (one colour on 30–60% of the surface), full palette (3–4 named roles) or drenched (colour as the surface). +- Visitor mode: persuade (marketing), operate (tools), read (docs), experience (portfolio). + +## 3. Propose in one message +- North star (one line) and the direction in 3–4 sentences, naming what it refuses. +- Theme: heading and body fonts from the site's available fonts, a radius, and the palette as [light, dark] hex pairs, every surface/foreground pair at 4.5:1 or better. +- Component styling through the EXISTING dt# tokens (buttons, cards, inputs, badges): what changes on each. Never propose a new token. +- The eight sections as short named rules with exact classes: Overview; Colors; Typography (Display/H1/H2/H3/Body/Small as class recipes); Layout (dt#content-gutter-y on outer sections, dt#site-content-width dt#content-gutter-x on inner wrappers, grid, rhythm); Elevation & depth; Shapes; Components (which token for which job); Do's and don'ts. +Ask for approval or one round of changes. + +## 4. Save, then enable +1. save_design_system with northStar, mode, colorStrategy, the sections and antiReferences. It is saved disabled. +2. If the user wants the new look now and the tools are available, apply the theme with update_site_theme and the token restyles with update_design_tokens. They stay draft; publish_site_theme takes them live only after the user approves. +3. Ask: "Enable this design system for the site? From then on every page follows it and edits are checked against it." Only on a yes: save_design_system with enabled: true. +Then build, following get_design_system.`; diff --git a/src/server/chai-actions/ai/design/rules-in-force.ts b/src/server/chai-actions/ai/design/rules-in-force.ts new file mode 100644 index 000000000..c1b2e2a13 --- /dev/null +++ b/src/server/chai-actions/ai/design/rules-in-force.ts @@ -0,0 +1,44 @@ +import type { ChaiDesignChecksMode } from "~/types/design-system"; + +/** + * The craft floor, the bans and the workflow — handed to an agent (MCP or Builder AI) + * only for a site whose design system is enabled. Written for ChaiBuilder's medium: + * Tailwind utilities, theme colour roles, the site's existing `dt#` tokens, blocks written as AI-HTML. + */ + +export const CRAFT_FLOOR = `Craft floor +- Contrast: body text at least 4.5:1, large text 3:1, in light and dark. Secondary text uses text-muted-foreground (or a tint of the surface's foreground), never raw gray. +- Space: every page section uses dt#content-gutter-y on the outer <section> and dt#site-content-width dt#content-gutter-x on its inner content wrapper (never hand-written section py-/px-/max-w-); tight inside a group, generous between groups, more space above a heading than below it. +- Type: body measure 65–75 characters (max-w-prose or max-w-2xl); display headings at most text-6xl; obvious steps between levels; exactly one h1 per page. +- Depth: a shadow has blur and an offset; no zero-blur block shadows. +- Motion: one authored moment per page, easing out; never the same entrance on every section. +- States: hover, focus-visible, disabled, loading, empty and error wherever they apply. Buttons and links name the action ("Book a table", not "Submit").`; + +export const BANS = `Never +- Gradient text, purple-to-blue gradients, or gray text on a coloured surface. +- Eyebrow or kicker labels above headings. +- Raw palette or hex colours (bg-blue-600, text-gray-500, bg-[#…]) instead of theme colours; font-serif, font-sans or font-[…] instead of the theme fonts; monospace as a "technical" costume. +- Emoji or unicode glyphs as icons: use <chai-icon> with a Lucide name. +- Cards inside cards, or the same section composition repeated down the page. +- Invented or archived dt# tokens. Never invent a token: use an existing one or theme utilities. +- Light or dark chosen by category instead of by the design system.`; + +export function rulesInForce(checks: ChaiDesignChecksMode): string { + const checkLine = + checks === "off" + ? "- Run check_page_design before asking to publish and fix its errors. A clean check is evidence, not proof." + : `- Every block write returns a Design check line for the blocks it changed${checks === "strict" ? "; a write with error findings is rejected and nothing is saved" : ""}. Fix errors before moving on, and run check_page_design before asking to publish. A clean check is evidence, not proof.`; + return `## Rules in force + +Workflow +- Before writing blocks, read a finished section of this site (get_page_outline, then read_block_html) and reuse its section padding, container width, heading roles and button tokens, so the new page reads as the same site. +- Put dt# tokens first in a class list (class="dt#btn dt#btn-primary px-6"); restyle a component through its token, not block by block. +- Headings take the theme heading font on their own and text the body font; use font-heading or font-body only to switch. Colour only through theme roles: bg-primary with text-primary-foreground, bg-card with text-card-foreground, bg-muted with text-muted-foreground, text-foreground, border-border. +${checkLine} +- For a critique, an audit, a polish, or a request to make something bolder, quieter, better typeset, more colourful, better laid out, animated or clearer, call get_design_guide with that topic first. Change what was named; keep everything else. +- Prove, don't claim: say what you checked (pairs, states, measure), never only that the page is "polished". + +${CRAFT_FLOOR} + +${BANS}`; +} diff --git a/src/server/chai-actions/ai/page-tool-operations.ts b/src/server/chai-actions/ai/page-tool-operations.ts new file mode 100644 index 000000000..acff84f94 --- /dev/null +++ b/src/server/chai-actions/ai/page-tool-operations.ts @@ -0,0 +1,539 @@ +import { pick } from "lodash-es"; +import { MAX_PARTIAL_DEPTH } from "~/constants/PARTIAL_BLOCKS"; +import { ActionError } from "~/server/chai-actions/action-error"; +import { getAppRow } from "~/server/chai-actions/apps/app-store"; +import { getConfigSiteSettingsTransform } from "~/server/defaults/config-registry"; +import { + chaiDesignSystemPatchShape, + designSystemStatus, + mergeChaiDesignSystem, + missingDesignSystemSections, + readChaiDesignSystem, + type ChaiDesignSystemPatch, +} from "~/server/chai-actions/ai/design-system-schema"; +import { chaiThemePatchSchema } from "~/server/chai-actions/website/theme-patch"; +import type { ChaiTheme } from "~/types/chaibuilder-editor-props"; +import type { ChaiBlock } from "~/types/common"; +import { CHAI_DESIGN_SYSTEM_KEY, type ChaiDesignSystem } from "~/types/design-system"; +import { PARTIAL_TAGS_METADATA_KEY } from "~/types/partial-blocks"; +import type { ChaiDesignTokens } from "~/types/types"; +import { + filterFindingsToBlocks, + formatDesignFindings, + runDesignChecks, + type ChaiDesignCheckContext, +} from "~/utils/design-checks"; +import { collectSubtreeIds } from "~/utils/blocks-tree-ops"; +import { blocksToAiHtml } from "~/utils/export-html/blocks-to-ai-html"; +import { extractBlockHtmlSlices } from "~/utils/export-html/extract-block-html-slices"; +import { isPartialPageTypeKey, type PageTypeCandidate } from "~/utils/page-type-helpers"; +import { collectTranslations, type TranslationEntry } from "~/utils/page-translations"; +import { getPartialDepth, getPartialUsageDepth } from "~/utils/partial-nesting"; +import { formatZodIssues } from "./design-system-schema"; + +/** + * Shared single-page AI/MCP operations over `ChaiBlock[]` JSON, site settings, + * design system, SEO, translations, and partials. + * + * Both Builder AI (`ai-edit-page-tools.ts`) and MCP (`src/plugins/mcp/server/tools/*`) + * delegate to these functions so behavior stays identical across surfaces. + */ + +const isRecord = (value: unknown): value is Record<string, unknown> => + typeof value === "object" && value !== null && !Array.isArray(value); + +const asRecord = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {}); + +/** + * Render only the requested root block subtrees from `ChaiBlock[]` JSON and slice by bid. + * Mirrors MCP `read_block_html` exactly so Builder AI and MCP produce identical HTML. + */ +export function sliceBlocksHtml(blocks: ChaiBlock[], blockIds: string[]): Record<string, string> { + const requested = new Set(blockIds); + const byId = new Map(blocks.map((b) => [b._id, b])); + const hasRequestedAncestor = (id: string): boolean => { + const seen = new Set<string>(); + let parent = byId.get(id)?._parent ?? null; + while (parent && !seen.has(parent)) { + if (requested.has(parent)) return true; + seen.add(parent); + parent = byId.get(parent)?._parent ?? null; + } + return false; + }; + const rootIds = blockIds.filter((id) => byId.has(id) && !hasRequestedAncestor(id)); + const pageHtml = blocksToAiHtml(blocks, rootIds); + return extractBlockHtmlSlices(pageHtml, blockIds); +} + +/** + * Return raw `ChaiBlock` JSON slices by bid, optionally including every descendant + * in document order. Shared by Builder AI and MCP `read_blocks`. + */ +export function sliceBlocksJson( + blocks: ChaiBlock[], + blockIds: string[], + options: { includeDescendants?: boolean } = {}, +): { blocks: ChaiBlock[]; missingIds: string[] } { + const byId = new Map(blocks.map((block) => [block._id, block])); + const foundIds: string[] = []; + const missingIds: string[] = []; + for (const id of blockIds) { + if (byId.has(id)) { + foundIds.push(id); + } else if (!missingIds.includes(id)) { + missingIds.push(id); + } + } + const targetIds = options.includeDescendants ? collectSubtreeIds(blocks, foundIds) : new Set(foundIds); + return { + blocks: blocks.filter((block) => targetIds.has(block._id)), + missingIds, + }; +} + +export const MAX_TRANSLATION_ENTRIES = 150; + +export function buildBlockTranslationsPage( + blocks: ChaiBlock[], + lang: string, + options: { blockIds?: string[]; missingOnly?: boolean; offset?: number } = {}, +): { total: number; nextOffset: number | null; entries: TranslationEntry[] } { + const offset = Math.max(0, Number(options.offset) || 0); + const all = collectTranslations(blocks, lang, { + blockIds: options.blockIds, + missingOnly: Boolean(options.missingOnly), + }); + const entries = all.slice(offset, offset + MAX_TRANSLATION_ENTRIES); + const nextOffset = offset + MAX_TRANSLATION_ENTRIES < all.length ? offset + MAX_TRANSLATION_ENTRIES : null; + return { total: all.length, nextOffset, entries }; +} + +export type PartialPageRow = { + id: string; + name?: string | null; + slug?: string | null; + pageType?: string | null; + metadata?: unknown; + partialBlocks?: string | null; +}; + +export type PartialBlockSummary = { + name?: string; + description?: string; + type?: string; + tags: string[]; +}; + +/** + * Filter site pages down to valid partial blocks (verified by registered pageType), + * including `tags`, and optionally enforcing self-nesting / cycle / `MAX_PARTIAL_DEPTH` + * rules when `currentPageId` is provided. + */ +export function selectPartialBlocks( + pages: PartialPageRow[], + pageTypes: PageTypeCandidate[], + options: { currentPageId?: string } = {}, +): { partials: Record<string, PartialBlockSummary>; note?: string } { + const partialPages = (pages ?? []).filter( + (page) => (page.slug ?? "") === "" && isPartialPageTypeKey(page.pageType, pageTypes), + ); + + const dependencies: Record<string, string[]> = {}; + for (const page of partialPages) { + dependencies[page.id] = (page.partialBlocks ?? "").split("|").filter(Boolean); + } + + const pageId = options.currentPageId; + const editingPartial = Boolean(pageId && pageId in dependencies); + const chainAbove = editingPartial ? 1 + getPartialUsageDepth(pageId!, dependencies) : 0; + const allowedTargetDepth = MAX_PARTIAL_DEPTH - chainAbove; + + if (editingPartial && allowedTargetDepth < 1) { + return { + partials: {}, + note: + "This partial is already used inside another partial, so it sits at the maximum nesting depth " + + `(${MAX_PARTIAL_DEPTH} levels). No partial blocks can be added here — tell the user why.`, + }; + } + + const result: Record<string, PartialBlockSummary> = {}; + for (const page of partialPages) { + if (pageId) { + if (page.id === pageId) continue; + if (dependencies[page.id]!.includes(pageId)) continue; + if (getPartialDepth(page.id, dependencies) > allowedTargetDepth) continue; + } + const meta = asRecord(page.metadata); + const rawTags = meta[PARTIAL_TAGS_METADATA_KEY]; + result[page.id] = { + name: page.name ?? undefined, + description: typeof meta.description === "string" ? meta.description : "", + type: page.pageType ?? "partial", + tags: Array.isArray(rawTags) ? rawTags.filter((tag): tag is string => typeof tag === "string") : [], + }; + } + + if (editingPartial) { + return { + partials: result, + note: `You are editing a partial: only partials that fit within the maximum nesting depth (${MAX_PARTIAL_DEPTH} levels) are listed.`, + }; + } + + return { partials: result }; +} + +/** @internal */ +export type SiteDesignContext = { + name: string; + theme: Partial<ChaiTheme> | null; + designTokens: ChaiDesignTokens; + /** The raw site AI context (`apps.ai`). */ + ai: Record<string, unknown>; + designSystem: ChaiDesignSystem | null; +}; + +export function toSiteDesignContext(settings: Record<string, unknown> | null | undefined): SiteDesignContext | null { + if (!settings || !isRecord(settings)) return null; + const ai = asRecord(settings.ai); + return { + name: typeof settings.name === "string" ? settings.name : "", + theme: isRecord(settings.theme) ? (settings.theme as Partial<ChaiTheme>) : null, + designTokens: isRecord(settings.designTokens) ? (settings.designTokens as ChaiDesignTokens) : {}, + ai, + designSystem: readChaiDesignSystem(ai[CHAI_DESIGN_SYSTEM_KEY]), + }; +} + +export type AppSiteDesignContext = SiteDesignContext & { + fallbackLang: string; + languages: string[]; +}; + +/** + * Read the full draft `apps` row (including `name`, `ai`, `theme`, `designTokens`, + * `fallbackLang`, `languages`) after applying the host's `transformSiteSettings` hook — + * mirroring MCP's `cb.getSiteSettings()` without stripping `ai`/`name` like `GetWebsiteSettingsAction`. + */ +export async function readSiteDesignContextForApp(appId: string): Promise<AppSiteDesignContext | null> { + try { + const { data: appRow, error } = await getAppRow(appId, { draft: true }); + if (error || !appRow) return null; + const transform = getConfigSiteSettingsTransform(); + const transformed = (transform ? await transform(appRow, { appId, draftMode: true }) : appRow) as Record< + string, + unknown + >; + const base = toSiteDesignContext(transformed); + if (!base) return null; + return { + ...base, + fallbackLang: typeof transformed.fallbackLang === "string" ? transformed.fallbackLang : "", + languages: Array.isArray(transformed.languages) ? (transformed.languages as string[]) : [], + }; + } catch { + return null; + } +} + +export function toDesignCheckContext( + site: SiteDesignContext, + options: { isPartial?: boolean; includeTheme?: boolean } = {}, +): ChaiDesignCheckContext { + const bannedWords = site.ai.bannedWords; + return { + theme: options.includeTheme ? site.theme : null, + designTokens: site.designTokens, + bannedWords: + typeof bannedWords === "string" || Array.isArray(bannedWords) ? (bannedWords as string | string[]) : null, + isPartial: options.isPartial, + }; +} + +/** The given blocks and everything inside them. */ +export { collectSubtreeIds }; + +const MAX_CHECK_LISTED = 40; + +export function runPageDesignCheckReport( + blocks: ChaiBlock[], + ctx: ChaiDesignCheckContext, + options: { pageName: string; blockIds?: string[]; active: boolean; outlineHint?: string }, +): + | { ok: true; text: string; errors: number; warnings: number } + | { ok: false; message: string } { + let findings = runDesignChecks(blocks, ctx); + const requested = Array.isArray(options.blockIds) ? options.blockIds : []; + if (requested.length) { + const known = new Set(blocks.map((block) => block._id)); + const missing = requested.filter((id) => !known.has(id)); + if (missing.length === requested.length) { + const hint = options.outlineHint ?? "Call get_page_outline for valid bids."; + return { + ok: false, + message: `Error: No block with bid ${missing.join(", ")} on "${options.pageName}". ${hint}`, + }; + } + findings = filterFindingsToBlocks(findings, collectSubtreeIds(blocks, requested)); + } + + const errors = findings.filter((finding) => finding.severity === "error").length; + const warnings = findings.length - errors; + const scope = requested.length ? ` (blocks ${requested.join(", ")} and what is inside them)` : ""; + const lines = [ + `### Design check: "${options.pageName}"${scope}`, + findings.length ? `- ${errors} error(s), ${warnings} warning(s).` : "- No findings.", + options.active + ? "- The site's design system is enabled: fix every error before asking to publish; keep a warning only when it is deliberate." + : "- The site has no enabled design system: these are general quality checks, to act on as the user wants.", + ]; + if (findings.length) lines.push("", formatDesignFindings(findings, MAX_CHECK_LISTED)); + lines.push("", "A clean check is evidence, not proof: look at the preview as well."); + return { ok: true, text: lines.join("\n"), errors, warnings }; +} + +export const DESIGN_SYSTEM_PATCH_KEYS = Object.keys(chaiDesignSystemPatchShape) as Array<keyof ChaiDesignSystemPatch>; + +export function extractDesignSystemPatch(args: Record<string, unknown>): ChaiDesignSystemPatch { + return pick(args, DESIGN_SYSTEM_PATCH_KEYS) as ChaiDesignSystemPatch; +} + +export function designSystemStatusLine(ds: ChaiDesignSystem): string { + const status = designSystemStatus(ds); + const missing = missingDesignSystemSections(ds); + const sections = missing.length + ? ` Sections not written yet: ${missing.join(", ")}.` + : " All eight sections are written."; + if (status === "disabled") { + return `- Status: saved, NOT enabled. Nothing is enforced until the user confirms enabling it; then call save_design_system with enabled: true.${sections}`; + } + return `- Status: enabled. Every page now follows it; read it with get_design_system before building.${sections}`; +} + +const SAVE_ATTEMPTS = 3; +const isConflict = (err: unknown) => err instanceof ActionError && err.code === "CONFLICT"; + +export type SiteDesignSaveResult = { ok: true; next: ChaiDesignSystem | null } | { ok: false; message: string }; + +/** + * Shared CAS read-patch-write for `apps.ai.designSystem` + product keys. + */ +export async function saveSiteDesignContextWithCas( + patch: ChaiDesignSystemPatch, + product: Record<string, unknown>, + options: { + touchesSystem: boolean; + replace: boolean; + userId?: string; + source: "mcp" | "builder"; + readContext: () => Promise<{ aiData?: { app?: unknown } }>; + saveContext: (payload: Record<string, unknown>) => Promise<unknown>; + formatError: (err: unknown) => string; + }, +): Promise<SiteDesignSaveResult> { + for (let attempt = 1; ; attempt++) { + let stored: unknown = null; + let next: ChaiDesignSystem | null = null; + if (options.touchesSystem) { + try { + const context = await options.readContext(); + stored = asRecord(context?.aiData?.app)[CHAI_DESIGN_SYSTEM_KEY] ?? null; + } catch (err) { + return { ok: false, message: `Error: Could not read the site's AI settings (${options.formatError(err)})` }; + } + const merged = mergeChaiDesignSystem(readChaiDesignSystem(stored), patch, { + replace: options.replace, + updatedBy: options.userId, + source: options.source, + }); + if (!merged.ok) return { ok: false, message: `Error: ${merged.message}` }; + next = merged.next; + } + + const siteData = { ...(next ? { [CHAI_DESIGN_SYSTEM_KEY]: next } : {}), ...product }; + if (Object.keys(siteData).length === 0) return { ok: true, next }; + try { + await options.saveContext({ + type: "app", + merge: true, + aiData: siteData, + ...(options.touchesSystem ? { expectedDesign: stored } : {}), + }); + return { ok: true, next }; + } catch (err) { + if (options.touchesSystem && isConflict(err) && attempt < SAVE_ATTEMPTS) continue; + return { ok: false, message: `Error: Could not save (${options.formatError(err)})` }; + } + } +} + +export type UpdateThemeActionResult = { changed: string[]; weakContrast: string[] }; + +export async function executeUpdateSiteThemePatch( + args: Record<string, unknown>, + deps: { + updateTheme: (patch: Record<string, unknown>) => Promise<UpdateThemeActionResult>; + formatError: (err: unknown) => string; + publishHint?: string; + }, +): Promise<{ ok: true; text: string; changed: string[] } | { ok: false; message: string }> { + const parsed = chaiThemePatchSchema.safeParse({ + ...(args.fontFamily !== undefined ? { fontFamily: args.fontFamily } : {}), + ...(args.borderRadius !== undefined ? { borderRadius: args.borderRadius } : {}), + ...(args.colors !== undefined ? { colors: args.colors } : {}), + }); + if (!parsed.success) return { ok: false, message: `Error: ${formatZodIssues(parsed.error)}` }; + const patch = parsed.data; + if ( + !patch.fontFamily?.heading && + !patch.fontFamily?.body && + !patch.borderRadius && + !Object.keys(patch.colors ?? {}).length + ) { + return { ok: false, message: "Error: nothing to change. Pass fontFamily, borderRadius or colors." }; + } + + let result: UpdateThemeActionResult; + try { + result = await deps.updateTheme(patch as Record<string, unknown>); + } catch (err) { + return { ok: false, message: `Error: Could not update the theme (${deps.formatError(err)})` }; + } + if (result.changed.length === 0) { + return { ok: true, text: "Nothing changed: the theme already has these values.", changed: [] }; + } + + const weak = result.weakContrast ?? []; + const lines = [ + "### Theme draft updated", + `- Changed: ${result.changed.join(", ")}.`, + ...(weak.length ? [`- ⚠️ Below 4.5:1 (fine for large text only): ${weak.join("; ")}.`] : []), + deps.publishHint ?? + "- Page previews use the new theme now. The live site keeps the old one until the user approves publish_site_theme.", + ]; + return { ok: true, text: lines.join("\n"), changed: result.changed }; +} + +export type UpdateTokensActionResult = { updated: Array<{ id: string; name: string; value: string }> }; + +export async function executeUpdateDesignTokensPatch( + args: Record<string, unknown>, + deps: { + updateTokens: (tokens: unknown) => Promise<UpdateTokensActionResult>; + formatError: (err: unknown) => string; + publishHint?: string; + }, +): Promise<{ ok: true; text: string; updatedIds: string[] } | { ok: false; message: string }> { + let result: UpdateTokensActionResult; + try { + result = await deps.updateTokens(args.tokens); + } catch (err) { + return { ok: false, message: `Error: Could not update the design tokens (${deps.formatError(err)})` }; + } + + return { + ok: true, + updatedIds: result.updated.map((token) => token.id), + text: [ + "### Design tokens draft updated", + ...result.updated.map((token) => `- ${token.id} (${token.name}): ${token.value}`), + deps.publishHint ?? + "- Every block using these tokens shows the change in previews now. The live site keeps the old values until the user approves publish_site_theme.", + ].join("\n"), + }; +} + +export type LibraryDescriptor = { + id: string; + name?: string | null; +}; + +export type LibraryItemDescriptor = { + id: string; + name?: string | null; + group?: string | null; + description?: string | null; + library?: string | null; +}; + +export type NormalizedLibraryBlock = { + id: string; + name: string; + group: string; + description: string | null; + libraryId: string; + libraryName: string; +}; + +const MAX_LIBRARY_BLOCKS_LISTED = 100; + +/** + * List available library blocks across every library registered for this site, + * deduplicated by block id and filtered by optional `group` and `query`. + * Shared by Builder AI and MCP `get_library_blocks`. + */ +export async function listAvailableLibraryBlocks( + deps: { + getLibraries: () => Promise<LibraryDescriptor[]>; + getLibraryItems: (libraryId: string) => Promise<LibraryItemDescriptor[]>; + }, + options: { query?: string; group?: string } = {}, +): Promise<{ + blocks: NormalizedLibraryBlock[]; + groups: string[]; + total: number; + truncated: boolean; +}> { + const libraries = (await deps.getLibraries()) ?? []; + const itemLists = await Promise.all( + libraries.map(async (library) => { + try { + const items = (await deps.getLibraryItems(library.id)) ?? []; + return { library, items }; + } catch { + return { library, items: [] as LibraryItemDescriptor[] }; + } + }), + ); + + const seen = new Set<string>(); + const all: NormalizedLibraryBlock[] = []; + for (const { library, items } of itemLists) { + const libraryName = library.name?.trim() || library.id; + for (const item of items) { + if (!item?.id || seen.has(item.id)) continue; + seen.add(item.id); + all.push({ + id: item.id, + name: item.name?.trim() || item.id, + group: item.group?.trim() || "general", + description: item.description?.trim() || null, + libraryId: item.library?.trim() || library.id, + libraryName, + }); + } + } + + const groups = Array.from(new Set(all.map((b) => b.group))).sort((a, b) => a.localeCompare(b)); + const groupFilter = options.group?.trim().toLowerCase() ?? ""; + const queryFilter = options.query?.trim().toLowerCase() ?? ""; + + const filtered = all.filter((block) => { + if (groupFilter && !block.group.toLowerCase().includes(groupFilter)) return false; + if (queryFilter) { + const haystack = `${block.name} ${block.group} ${block.description ?? ""} ${block.id}`.toLowerCase(); + if (!haystack.includes(queryFilter)) return false; + } + return true; + }); + + const truncated = filtered.length > MAX_LIBRARY_BLOCKS_LISTED; + return { + blocks: truncated ? filtered.slice(0, MAX_LIBRARY_BLOCKS_LISTED) : filtered, + groups, + total: filtered.length, + truncated, + }; +} diff --git a/src/server/chai-actions/ai/remote-image-constants.ts b/src/server/chai-actions/ai/remote-image-constants.ts new file mode 100644 index 000000000..7c3b40ae9 --- /dev/null +++ b/src/server/chai-actions/ai/remote-image-constants.ts @@ -0,0 +1,12 @@ +/** + * Pure constants shared by client-safe `upload_image` schemas and the + * server-only remote-image fetcher. No node imports. + */ + +/** Largest image the server will fetch from a sourceUrl. */ +export const MCP_IMAGE_MAX_BYTES = 25 * 1024 * 1024; + +/** Per-hop budget covering DNS resolution and the fetch. */ +export const MCP_IMAGE_TIMEOUT_MS = 15_000; + +export const formatBytes = (bytes: number): string => `${Math.round(bytes / (1024 * 1024))} MB`; diff --git a/src/server/chai-actions/ai/remote-image.ts b/src/server/chai-actions/ai/remote-image.ts new file mode 100644 index 000000000..574afe2d1 --- /dev/null +++ b/src/server/chai-actions/ai/remote-image.ts @@ -0,0 +1,591 @@ +/** + * Turning a client's `dataUrl` / `sourceUrl` argument into image bytes with SSRF guards, + * plus shared media-library asset upload logic for Builder AI and MCP `upload_image`. + * + * Known limitation: DNS rebinding between the address check and the fetch. + * Closing it fully needs a pinned-IP connection with a manual Host header, + * which breaks TLS SNI and certificate validation — the same trade-off made + * for authenticated, `assets:create`-permissioned callers (MCP tokens and + * authenticated Builder AI sessions). + */ +import { lookup } from "node:dns/promises"; +import { isIP } from "node:net"; +import { extensionForMime, withExtension } from "~/constants/ASSET_TYPES"; +import { MCP_IMAGE_MAX_BYTES, MCP_IMAGE_TIMEOUT_MS, formatBytes } from "./remote-image-constants"; + +export { MCP_IMAGE_MAX_BYTES, MCP_IMAGE_TIMEOUT_MS, formatBytes }; + +/** Hops followed after the first request. */ +export const MCP_IMAGE_MAX_REDIRECTS = 3; + +export type RemoteImage = { + bytes: Uint8Array; + mimeType: string; + finalUrl?: string; +}; + +export type ImageSourceResult = { ok: true; image: RemoteImage } | { ok: false; message: string }; + +const fail = (message: string): ImageSourceResult => ({ + ok: false, + message: `Error: ${message}`, +}); + +const BLOCKED_IPV4: Array<[string, number]> = [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], + ["127.0.0.0", 8], + ["169.254.0.0", 16], + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.0.2.0", 24], + ["192.88.99.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["198.51.100.0", 24], + ["203.0.113.0", 24], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +]; + +function ipv4ToInt(ip: string): number | null { + const parts = ip.split("."); + if (parts.length !== 4) return null; + let value = 0; + for (const part of parts) { + if (!/^\d{1,3}$/.test(part)) return null; + const octet = Number(part); + if (octet > 255) return null; + value = value * 256 + octet; + } + return value; +} + +function isBlockedIpv4(ip: string): boolean { + const value = ipv4ToInt(ip); + if (value === null) return true; + return BLOCKED_IPV4.some(([network, prefix]) => { + const base = ipv4ToInt(network); + if (base === null) return false; + const size = 2 ** (32 - prefix); + return value >= base && value < base + size; + }); +} + +export function parseIpv6(ip: string): number[] | null { + let text = ip.trim(); + if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1); + text = text.split("%")[0]; + if (!text) return null; + + let tail = ""; + const lastColon = text.lastIndexOf(":"); + const maybeV4 = text.slice(lastColon + 1); + if (maybeV4.includes(".")) { + const value = ipv4ToInt(maybeV4); + if (value === null) return null; + tail = `${Math.floor(value / 0x10000).toString(16)}:${(value % 0x10000).toString(16)}`; + text = `${text.slice(0, lastColon + 1)}${tail}`; + } + + const doubleColonParts = text.split("::"); + if (doubleColonParts.length > 2) return null; + + const toGroups = (segment: string): number[] | null => { + if (!segment) return []; + const groups: number[] = []; + for (const part of segment.split(":")) { + if (!/^[0-9a-f]{1,4}$/i.test(part)) return null; + groups.push(parseInt(part, 16)); + } + return groups; + }; + + if (doubleColonParts.length === 1) { + const groups = toGroups(text); + return groups && groups.length === 8 ? groups : null; + } + + const head = toGroups(doubleColonParts[0]); + const rest = toGroups(doubleColonParts[1]); + if (!head || !rest) return null; + const missing = 8 - head.length - rest.length; + if (missing < 1) return null; + return [...head, ...Array<number>(missing).fill(0), ...rest]; +} + +function ipv4FromGroups(groups: number[], start: number): string { + const high = groups[start]; + const low = groups[start + 1]; + return [high >> 8, high & 0xff, low >> 8, low & 0xff].join("."); +} + +function embeddedIpv4(groups: number[]): string { + return ipv4FromGroups(groups, 6); +} + +const isNat64Shape = (groups: number[]) => groups.slice(2, 6).every((group) => group === 0); + +function isBlockedIpv6(ip: string): boolean { + const groups = parseIpv6(ip); + if (!groups) return true; + + const isZeroPrefix = (count: number) => groups.slice(0, count).every((group) => group === 0); + + if (groups.every((group) => group === 0)) return true; + if (isZeroPrefix(7) && groups[7] === 1) return true; + + if (isZeroPrefix(5) && groups[5] === 0xffff) return isBlockedIpv4(embeddedIpv4(groups)); + if (isZeroPrefix(6)) return isBlockedIpv4(embeddedIpv4(groups)); + if (groups[0] === 0x0064 && groups[1] === 0xff9b && isNat64Shape(groups)) return isBlockedIpv4(embeddedIpv4(groups)); + + if (groups[0] === 0x2002) return isBlockedIpv4(ipv4FromGroups(groups, 1)); + if (groups[0] === 0x2001 && groups[1] === 0x0000) { + if (isBlockedIpv4(ipv4FromGroups(groups, 2))) return true; + const client = [groups[6] ^ 0xffff, groups[7] ^ 0xffff]; + return isBlockedIpv4(ipv4FromGroups([...groups.slice(0, 6), ...client], 6)); + } + + if ((groups[0] & 0xfe00) === 0xfc00) return true; + if ((groups[0] & 0xffc0) === 0xfe80) return true; + if ((groups[0] & 0xffc0) === 0xfec0) return true; + if ((groups[0] & 0xff00) === 0xff00) return true; + if (groups[0] === 0x0100 && groups.slice(1, 4).every((g) => g === 0)) return true; + if (groups[0] === 0x2001 && groups[1] === 0x0002 && groups[2] === 0) return true; + if (groups[0] === 0x2001 && groups[1] === 0x0db8) return true; + if (groups[0] === 0x3fff && (groups[1] & 0xf000) === 0) return true; + + return false; +} + +export function isBlockedIpAddress(address: string): boolean { + const value = address.trim().replace(/^\[|\]$/g, ""); + const version = isIP(value); + if (version === 4) return isBlockedIpv4(value); + if (version === 6) return isBlockedIpv6(value); + return true; +} + +export type UrlCheckResult = { ok: true; url: URL } | { ok: false; message: string }; + +export function checkImageUrlShape(raw: string): UrlCheckResult { + let url: URL; + try { + url = new URL(raw.trim()); + } catch { + return { ok: false, message: "Error: sourceUrl is not a valid URL." }; + } + + if (url.protocol !== "https:" && url.protocol !== "http:") { + return { + ok: false, + message: `Error: sourceUrl must be an http or https URL (got "${url.protocol}").`, + }; + } + + if (url.username || url.password) { + return { ok: false, message: "Error: sourceUrl must not contain credentials." }; + } + + const hostname = url.hostname.replace(/^\[|\]$/g, ""); + if (!hostname) return { ok: false, message: "Error: sourceUrl has no host." }; + + const lower = hostname.toLowerCase(); + if (lower === "localhost" || lower.endsWith(".localhost")) { + return { ok: false, message: "Error: sourceUrl must point to a public host." }; + } + + if (isIP(hostname) && isBlockedIpAddress(hostname)) { + return { ok: false, message: `Error: sourceUrl resolves to a non-public address (${hostname}).` }; + } + + if (url.port && url.port !== "80" && url.port !== "443") { + return { + ok: false, + message: `Error: sourceUrl must use the default http/https port (got port ${url.port}).`, + }; + } + + return { ok: true, url }; +} + +type LookupAddresses = (hostname: string) => Promise<string[]>; + +const defaultLookupAddresses: LookupAddresses = async (hostname) => { + const records = await lookup(hostname, { all: true, verbatim: true }); + return records.map((record) => record.address); +}; + +function withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> { + let timer: ReturnType<typeof setTimeout>; + const deadline = new Promise<T>((_, reject) => { + timer = setTimeout(() => reject(new Error("timed out")), ms); + timer.unref?.(); + }); + return Promise.race([promise, deadline]).finally(() => clearTimeout(timer)); +} + +export async function validateImageUrl( + raw: string, + lookupAddresses: LookupAddresses = defaultLookupAddresses, + timeoutMs: number = MCP_IMAGE_TIMEOUT_MS, +): Promise<UrlCheckResult> { + const shape = checkImageUrlShape(raw); + if (!shape.ok) return shape; + + const hostname = shape.url.hostname.replace(/^\[|\]$/g, ""); + if (isIP(hostname)) return shape; + + let addresses: string[]; + try { + addresses = await withDeadline(lookupAddresses(hostname), timeoutMs); + } catch { + return { ok: false, message: `Error: could not resolve the host of sourceUrl (${hostname}).` }; + } + + if (addresses.length === 0) { + return { ok: false, message: `Error: could not resolve the host of sourceUrl (${hostname}).` }; + } + + const blocked = addresses.find((address) => isBlockedIpAddress(address)); + if (blocked) { + return { ok: false, message: `Error: sourceUrl resolves to a non-public address (${blocked}).` }; + } + + return shape; +} + +export function parseImageDataUrl(value: string, maxBytes: number = MCP_IMAGE_MAX_BYTES): ImageSourceResult { + const match = /^data:([^;,]*)((?:;[^;,]*)*),([\s\S]*)$/.exec(value.trim()); + if (!match) { + return fail('dataUrl must be a base64 data URL, e.g. "data:image/png;base64,iVBORw0K…".'); + } + + const [, rawMime, params, payload] = match; + if ( + !params + .split(";") + .map((param) => param.trim().toLowerCase()) + .includes("base64") + ) { + return fail('dataUrl must be base64-encoded (";base64," before the data).'); + } + + const mimeType = rawMime.trim().toLowerCase(); + if (!mimeType.startsWith("image/")) { + return fail(`dataUrl must declare an image media type (got "${mimeType || "none"}").`); + } + + const compact = payload.replace(/\s+/g, ""); + if (!compact) return fail("dataUrl carries no data."); + const padding = compact.match(/=+$/)?.[0].length ?? 0; + if (Math.floor((compact.length * 3) / 4) - padding > maxBytes) { + return fail( + `the image is larger than the ${formatBytes(maxBytes)} limit. Use sourceUrl, or upload a smaller image.`, + ); + } + if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) { + return fail("dataUrl payload is not valid base64."); + } + + const bytes = new Uint8Array(Buffer.from(compact, "base64")); + if (bytes.byteLength === 0) return fail("dataUrl decoded to zero bytes."); + if (bytes.byteLength > maxBytes) { + return fail( + `the image is larger than the ${formatBytes(maxBytes)} limit. Use sourceUrl, or upload a smaller image.`, + ); + } + + return { ok: true, image: { bytes, mimeType } }; +} + +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); + +async function discardBody(response: Response): Promise<void> { + await response.body?.cancel().catch(() => {}); +} + +async function readCappedBody(response: Response, maxBytes: number): Promise<Uint8Array | null> { + const body = response.body; + if (!body) { + const bytes = new Uint8Array(await response.arrayBuffer()); + return bytes.byteLength > maxBytes ? null : bytes; + } + + const reader = body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => {}); + return null; + } + chunks.push(value); + } + + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +export type FetchRemoteImageOptions = { + fetchImpl?: typeof fetch; + lookupAddresses?: LookupAddresses; + maxBytes?: number; + maxRedirects?: number; + timeoutMs?: number; +}; + +export async function fetchRemoteImage(raw: string, options: FetchRemoteImageOptions = {}): Promise<ImageSourceResult> { + const { + fetchImpl = fetch, + lookupAddresses = defaultLookupAddresses, + maxBytes = MCP_IMAGE_MAX_BYTES, + maxRedirects = MCP_IMAGE_MAX_REDIRECTS, + timeoutMs = MCP_IMAGE_TIMEOUT_MS, + } = options; + + let target = raw; + + for (let hop = 0; hop <= maxRedirects; hop++) { + const hopDeadline = Date.now() + timeoutMs; + const validated = await validateImageUrl(target, lookupAddresses, timeoutMs); + if (!validated.ok) return { ok: false, message: validated.message }; + + let response: Response; + try { + response = await fetchImpl(validated.url.toString(), { + redirect: "manual", + headers: { accept: "image/*" }, + signal: AbortSignal.timeout(Math.max(0, hopDeadline - Date.now())), + }); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + return fail(`could not download the image from sourceUrl (${reason}).`); + } + + if (REDIRECT_STATUSES.has(response.status)) { + await discardBody(response); + const location = response.headers.get("location"); + if (!location) { + return fail(`sourceUrl returned HTTP ${response.status} without a redirect target.`); + } + try { + target = new URL(location, validated.url).toString(); + } catch { + return fail("sourceUrl redirected to an invalid URL."); + } + continue; + } + + if (!response.ok) { + await discardBody(response); + return fail(`sourceUrl returned HTTP ${response.status}.`); + } + + const mimeType = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase(); + if (!mimeType.startsWith("image/")) { + await discardBody(response); + return fail(`sourceUrl is not an image; the server returned content-type "${mimeType || "none"}".`); + } + + const declared = Number(response.headers.get("content-length")); + if (Number.isFinite(declared) && declared > maxBytes) { + await discardBody(response); + return fail(`the image at sourceUrl is larger than the ${formatBytes(maxBytes)} limit.`); + } + + let bytes: Uint8Array | null; + try { + bytes = await readCappedBody(response, maxBytes); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + return fail(`could not read the image from sourceUrl (${reason}).`); + } + if (bytes === null) { + return fail(`the image at sourceUrl is larger than the ${formatBytes(maxBytes)} limit.`); + } + if (bytes.byteLength === 0) { + return fail("sourceUrl returned an empty response."); + } + + return { + ok: true, + image: { bytes, mimeType, finalUrl: validated.url.toString() }, + }; + } + + return fail(`sourceUrl redirected more than ${maxRedirects} times without returning an image.`); +} + +export type CreatedAsset = { + id?: string; + name?: string; + url?: string; + thumbnailUrl?: string; + size?: string | number | null; + width?: string | number | null; + height?: string | number | null; + format?: string | null; + folderId?: string | null; + error?: string; +}; + +export type UploadImageInput = { + dataUrl?: unknown; + sourceUrl?: unknown; + name?: unknown; + folderId?: unknown; + alt?: unknown; +}; + +export type UploadImageDeps = { + createAsset: (payload: Record<string, unknown>) => Promise<CreatedAsset>; + getFallbackLang: () => Promise<string>; + formatError?: (err: unknown) => string; + onMeta?: (detail: Record<string, unknown>) => void; +}; + +const asText = (value: unknown): string => (typeof value === "string" ? value.trim() : ""); + +function nameFromUrl(sourceUrl: string): string { + if (!sourceUrl) return ""; + try { + const last = new URL(sourceUrl).pathname.split("/").filter(Boolean).pop(); + return last ? decodeURIComponent(last).slice(0, 200) : ""; + } catch { + return ""; + } +} + +const dimensionsOf = (asset: CreatedAsset): string => { + const width = Number(asset.width); + const height = Number(asset.height); + if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return ""; + return `${width}×${height}`; +}; + +const imgDimAttrs = (asset: CreatedAsset): string => { + const width = Number(asset.width); + const height = Number(asset.height); + if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return ""; + return ` width="${width}" height="${height}"`; +}; + +const sizeOf = (asset: CreatedAsset): string => { + const size = Number(asset.size); + if (!Number.isFinite(size) || size <= 0) return ""; + return size >= 1024 * 1024 ? `${(size / (1024 * 1024)).toFixed(2)} MB` : `${Math.max(1, Math.round(size / 1024))} KB`; +}; + +function hostOf(rawUrl: string): string { + try { + return new URL(rawUrl).hostname.slice(0, 253); + } catch { + return "invalid"; + } +} + +/** + * Shared media-library upload implementation for both Builder AI and MCP `upload_image`. + */ +export async function executeUploadImage( + args: UploadImageInput, + deps: UploadImageDeps, +): Promise<{ ok: true; text: string; asset: CreatedAsset } | { ok: false; message: string }> { + const dataUrl = asText(args.dataUrl); + const sourceUrl = asText(args.sourceUrl); + + if (dataUrl && sourceUrl) { + return { ok: false, message: "Error: pass either dataUrl or sourceUrl, not both." }; + } + if (!dataUrl && !sourceUrl) { + return { ok: false, message: "Error: pass one of dataUrl (base64 data URL) or sourceUrl (public http(s) image URL)." }; + } + + const requestedName = asText(args.name); + const folderId = asText(args.folderId) || undefined; + const alt = asText(args.alt); + + deps.onMeta?.({ + source: dataUrl ? "dataUrl" : "sourceUrl", + ...(sourceUrl ? { sourceHost: hostOf(sourceUrl) } : {}), + ...(folderId ? { folderId } : {}), + }); + + const source: ImageSourceResult = dataUrl ? parseImageDataUrl(dataUrl) : await fetchRemoteImage(sourceUrl); + if (!source.ok) return { ok: false, message: source.message }; + + const { bytes, mimeType } = source.image; + const ext = extensionForMime(mimeType); + if (!ext) { + return { ok: false, message: `Error: "${mimeType}" is not a supported image type. Use jpg, png, webp, gif, svg or tiff.` }; + } + const fileName = withExtension(requestedName || nameFromUrl(sourceUrl) || "image", ext); + + deps.onMeta?.({ bytes: bytes.byteLength, mimeType, fileName }); + + let descriptionLang = "en"; + if (alt) { + try { + descriptionLang = (await deps.getFallbackLang()) || "en"; + } catch { + // A missing settings row must not cost the upload its description. + } + } + + let asset: CreatedAsset; + try { + asset = await deps.createAsset({ + name: fileName, + file: bytes, + folderId: folderId ?? null, + mimeType, + ...(alt ? { description: { [descriptionLang]: alt } } : {}), + }); + } catch (err) { + const message = deps.formatError ? deps.formatError(err) : err instanceof Error ? err.message : String(err); + return { ok: false, message: `Error: Failed to upload the image. ${message}` }; + } + + if (!asset || asset.error) { + return { + ok: false, + message: `Error: Failed to upload the image. ${asset?.error ?? "the media library returned no asset"}`, + }; + } + if (!asset.url) { + return { ok: false, message: "Error: the image was stored but the media library returned no URL." }; + } + + deps.onMeta?.({ assetId: asset.id, assetUrl: asset.url }); + + const dimensions = dimensionsOf(asset); + const size = sizeOf(asset); + const details = [ + dimensions ? `- Dimensions: ${dimensions} px` : "", + size ? `- Size: ${size} (${asset.format ?? ext})` : "", + folderId ? `- Folder: ${folderId}` : "", + alt ? `- Description (${descriptionLang}): ${alt}` : "", + ] + .filter(Boolean) + .join("\n"); + + const dimAttrs = imgDimAttrs(asset); + const text = `### Image "${asset.name ?? fileName}" uploaded to the media library +- URL: ${asset.url} +${details} +- *Asset ID: ${asset.id ?? "unknown"}* +- Place it with edit_block or add_blocks as an <img>. Keep the width and height so it renders at its natural size — a bare <img> with no dimensions becomes a full-bleed block that collapses to zero height when it is alone on a page. Example: <img src="${asset.url}" alt="${alt || "describe the image"}"${dimAttrs}>. For a specific size, crop, or responsive layout, set your own width/height (or wrap it in a sized container) instead. The image is not on any page until you make that edit.`; + + return { ok: true, text, asset }; +} diff --git a/src/server/chai-actions/ai/shared-instructions.ts b/src/server/chai-actions/ai/shared-instructions.ts new file mode 100644 index 000000000..841dc167f --- /dev/null +++ b/src/server/chai-actions/ai/shared-instructions.ts @@ -0,0 +1,77 @@ +import { AI_INTERNAL_LINK_RULES } from "./ask-ai/ai-edit-tool-contract"; + +/** + * Single source of truth for domain authoring instructions shared by BOTH + * MCP (`src/plugins/mcp/server/instructions/sections/*`) and Builder AI + * (`src/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt.ts`). + * + * Editing a rule here updates both surfaces simultaneously so they cannot drift. + */ + +export const SHARED_AI_HTML_RULES = `- JSON-first edits (PREFERRED): to update copy, styles, media, links, or props on existing blocks (especially custom blocks and library blocks), call read_blocks and patch them with update_block_props instead of rewriting HTML. Reserve read_block_html + edit_block for structural markup or child-hierarchy rewrites. +- Core blocks use semantic HTML such as <section>, <h1>, <p>, <a>, <img>, <ul>, and <button>. Custom or special blocks use <chai-{kebab-type}> elements. +- Existing elements carry bid attributes. Preserve the bid of every element retained during edit_block so it merges with the existing block. Omit bid on every brand-new element and on all add_blocks HTML. +- edit_block HTML is the complete replacement for the target element, not a fragment or diff. Preserve unrelated attributes, live {{binding}} expressions, child bids, and the target's layout role. +- Never include <!DOCTYPE>, <html>, <head>, or <body>. +- Attribute values beginning with #styles: are Tailwind class lists. Preserve the #styles: prefix and update only intended classes. +- Every custom component begins with <chai-. Preserve chai-type and all existing attributes. Use about-this-component to understand it. +- Any element may carry can-move="false", can-delete="false" or can-duplicate="false". Never remove, move or duplicate that element on its own; changing its parent is fine. +- A <chai-chai-slot> is a named slot of its parent block. Put that slot's content inside it, using only block types its accept pattern matches. Never add, remove or rename a slot. +- Existing blocks first (MANDATORY): before building any new section or component from scratch with add_blocks, FIRST check the Available Custom Blocks catalog for a matching registered block (e.g. hero, header, footer, CTA, testimonials, stats, FAQ, blog, search, featured listings) and insert it with add_custom_block using camelCase props. Only fall back to building from core HTML via add_blocks when no registered custom block (or library block, when available) fits the request, or when the user explicitly asks to create a custom section from scratch. Never hand-author a cataloged custom block in add_blocks. +- Pick ONE per section (MANDATORY): when the catalog or block library offers multiple variants/designs for the same section (e.g. HeroOne..HeroThirteen, FeaturedListing..FeaturedListingFour, FooterOne..FooterFour), choose the SINGLE best-fitting block and insert ONLY ONE — never add multiple variants or all matching blocks for one requested section unless the user explicitly asks to add several or compare them. +- Add descriptive chai-name attributes to new sections, such as "Hero Section" or "Navigation".`; + +export const SHARED_LIBRARY_BLOCKS_RULES = `- Reusable block library: when adding a new section and no registered custom block in the catalog fits, call get_library_blocks (optionally filtering by group or query) BEFORE building a section from scratch with add_blocks. +- If one or more library blocks fit, pick the SINGLE best-fitting template and insert ONLY ONE with add_library_block (never add multiple alternatives for one requested section unless the user explicitly asks for several); it returns the inserted block IDs and outline so you can tailor its copy, media, or props with read_blocks and update_block_props if needed. +- Only build a section from scratch with core HTML via add_blocks when neither a registered custom block nor a library block fits the request, or when the user explicitly asks to build a custom layout from scratch.`; + +export const SHARED_ICON_RULES = `- Use Lucide icon names. For a NEW icon, write <chai-icon chai-type="Icon" icon-name="kebab-case-name" width="16" height="16"> and preserve existing bid and other attributes. +- On an EXISTING icon, preserve its icon-name — or its raw icon SVG attribute when read_block_html returned one (a non-Lucide icon has no derivable name) — unless the user asked to change that icon. +- Choose a semantic Lucide name and never embed raw <svg> inside <chai-icon>. Standalone SVG must include width, height, and viewBox.`; + +export const SHARED_INTERNAL_LINK_RULES = `${AI_INTERNAL_LINK_RULES.map((rule) => `- ${rule}`).join("\n")} +- A variant-language page's linkRef already points at its primary page; the link resolves to the right language at render time. +- A path you write that exactly matches a listed page is converted to its reference on save, so read_block_html may return a pageType: href where you wrote a path.`; + +export const SHARED_DATA_BINDING_RULES = `- Bindings use exactly {{path}} or {{path | pipe 'literal'}}. Use only paths and pipes provided in page context; never invent paths, item fields, or executable expressions. +- Preserve existing bindings exactly unless the user asked to change them. Prefer a plain binding; add formatters only when required. Boolean formatters belong only on _show. +- Repeater uses <chai-repeater repeater-items="{{arrayPath}}"> and its children may use only advertised {{$index.field}} paths. Do not use Repeater for static lists. +- PartialBlock uses <chai-partial-block partial-id="RETURNED_ID"></chai-partial-block>. Never edit partial content inline or invent an id.`; + +export const SHARED_STYLING_RULES = `- Use only Tailwind CSS v4 utilities; no custom CSS or container queries. +- Section layout (MANDATORY): every page section must use \`dt#content-gutter-y\` on the outer \`<section>\` and \`dt#site-content-width dt#content-gutter-x\` on its inner content wrapper \`<div>\` (always put \`dt#\` tokens first in \`class\`, with no breakpoint prefix — \`lg:dt#…\` does nothing). Never hand-write section \`py-*\`, \`px-*\`, or \`max-w-*\` utilities; using these three tokens keeps every section uniform and controllable via site layout and design tokens. For a full-bleed background image or video, keep the media layer edge-to-edge inside \`<section>\` and wrap foreground content in \`dt#site-content-width dt#content-gutter-x\`. +- Use shadcn semantic colors with readable pairs: bg-background/text-foreground, bg-card/text-card-foreground, bg-primary/text-primary-foreground, bg-secondary/text-secondary-foreground, bg-muted/text-muted-foreground, bg-accent/text-accent-foreground, bg-destructive/text-destructive-foreground, border-border, border-input, and ring-ring. Never pair same-family background and text tokens. +- Use semantic, accessible HTML and a mobile-first responsive layout with sm, md, lg, and xl breakpoints. Keep touch targets at least 44px tall. +- Use <details><summary> for accordions, FAQs, nested menus, and mobile menus. Forms need correct type and autocomplete attributes. +- Prefer an intentional, page-specific visual direction. Avoid generic font stacks, purple-gradient-on-white defaults, repetitive grids, and decorative div soup. Use an image placeholder for decorative terminal, browser, device, or code mockups. +- When working from a supplied image, match its structure, spacing, hierarchy, and visual appearance while preserving responsiveness and theme rules.`; + +export const SHARED_ANIMATION_RULES = `Use data-animation sparingly on below-the-fold headings or cards, never above the fold. Format: data-animation="ANIMATION|EASING|DURATION|DELAY|TIME". Allowed animations: fade-in, slide-up, slide-down, slide-left, slide-right, zoom-in, zoom-out, flip-x, flip-y, rotate-in. Easing: linear, ease-in, ease-out, ease-in-out. TIME: once or infinite.`; + +export const SHARED_LANGUAGE_CORE_RULES = `- Write all user-visible copy in the page's language: headings, body text, labels, buttons, link text, image alt text, form labels and placeholders, and SEO text. Match the language of the copy already on the page. Never switch a page's language because the user's prompt was written in another one; translate only when the user explicitly asks for a translation. +- Keep non-prose values untranslated: bindings, slugs, Tailwind class lists, chai-type, icon names, form field name attributes, and data keys. +- ChaiBuilder stores every language's copy on the primary page's blocks: the fallback-language text is the bare prop (content) and each translation sits beside it as prop-{lang} (content-en). A language-variant page has no blocks of its own. +- On a language variant, read tools show that language's copy, and text edits there are saved as that language's translation only. Layout, structure, and styling edits there still apply to every language. +- On a page with language variants, editing copy on the primary-language page changes the source text, and the edit response lists "Translations to sync" per language. Always follow it in the same turn: translate each listed value and write it with update_block_translations for every listed language, so the other languages never keep outdated copy. +- To translate a page's copy in bulk, call get_block_translations (missingOnly: true for untranslated props), translate every text entry, and write them with update_block_translations, paging through nextOffset. Translate faithfully, preserve HTML markup and {{bindings}} exactly, and leave asset props unset unless asked.`; + +export const SHARED_SEO_RULES = `- get_page_seo and update_page_seo cover the builder's SEO panel: the SEO tab (title, description, canonicalUrl, noIndex, noFollow), the Meta Tags tab (ogTitle, ogDescription, ogImage, and metaOther name/content pairs), and the JSON-LD tab (jsonLD). +- Always call get_page_seo before update_page_seo, and send only the fields you are changing. Every other field keeps its stored value. +- metaOther and jsonLD are whole-value replacements, not merges: send the complete set of meta pairs and the complete JSON-LD document. Pass {} or null to clear either one. +- SEO is stored per language page: changes apply only to the target language page and never alter other languages. +- Write SEO copy in the page's content language, following the language rules above.`; + +export const SHARED_UPLOAD_IMAGE_RULES = `- upload_image puts an image in this site's media library and returns its permanent URL. Use it whenever the user supplies image bytes or a link to an image that is not already hosted on this site. +- Pass exactly one of dataUrl (a base64 data URL) or sourceUrl (a public http(s) URL the server downloads). Prefer sourceUrl for anything but a small image; sourceUrl must be publicly reachable, as private, loopback and internal addresses are refused. +- Uploading only stores the image. To place it, call edit_block or add_blocks with <img src="THE_RETURNED_URL" alt="..."> and write the alt text in the page's content language. +- Keep width and height on that <img>, using the dimensions upload_image reported. An <img> with no dimensions becomes a full-bleed image block that collapses to zero height when it is alone on a page, so it renders blank. Only drop or change them when the user wants a specific size, a crop, or a responsive layout — then set your own width/height or wrap the image in a sized container. +- Never invent an image URL and never point page HTML at a third-party URL: upload it first, then reference the URL upload_image returned.`; + +export const SHARED_DESIGN_SYSTEM_RULES = `- A site can have a design system: its fonts, palette, dt# tokens and written rules, which keep every page consistent. At the start of any task that adds or restyles content, call get_design_system. +- When it returns an enabled design system, follow it exactly, including its rules in force. +- When none is set up, or it is not enabled, keep following the styling rules below as they are. Start a design-system setup only when the user asks for it or accepts your one-line offer: follow get_design_guide with topic setup, and enable it only when the user confirms. +- For a critique, an audit, a polish, or a request to make something bolder, quieter, better typeset, more colourful, better laid out, animated or clearer, call get_design_guide with that topic first.`; + +export const SHARED_SITE_THEME_RULES = `- The theme (fonts, radius, colours) and the design tokens are site-wide: change them only for a site-wide restyle the user approved, never to fix one page. +- update_site_theme changes the theme draft. Fonts must be ones the site can use, and every surface/foreground pair must stay at 4.5:1 or better. +- update_design_tokens restyles existing tokens; a built-in keeps its layout, focus and disabled classes. It cannot create a token, so never plan on new ones.`; diff --git a/src/server/chai-actions/base-ai-action.test.ts b/src/server/chai-actions/base-ai-action.test.ts index 57dc1ead9..b95b97caa 100644 --- a/src/server/chai-actions/base-ai-action.test.ts +++ b/src/server/chai-actions/base-ai-action.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from "vitest"; -import { captureConsola } from "~/tests/utils/capture-consola"; import { setGlobalDebugLevel } from "~/server/debug/debug-level"; -import { buildAiUsageMessageMetadata, ChaiBaseAiAction as BaseAIAction } from "./base-ai-action"; +import { captureConsola } from "~/tests/utils/capture-consola"; +import { ChaiBaseAiAction as BaseAIAction, buildAiUsageMessageMetadata } from "./base-ai-action"; describe("buildAiUsageMessageMetadata", () => { it("returns totalTokens from the finish part's totalUsage (cbpl#161)", () => { @@ -37,7 +37,7 @@ describe("buildAiUsageMessageMetadata", () => { }); }); -describe("ChaiBaseAIAction error streaming", () => { +describe("ChaiBaseAiAction error streaming", () => { const log = captureConsola(); afterEach(() => { diff --git a/src/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt.ts b/src/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt.ts index 659185177..b1f6359c6 100644 --- a/src/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt.ts +++ b/src/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt.ts @@ -1,43 +1,150 @@ import { MAX_PARTIAL_DEPTH } from "~/constants/PARTIAL_BLOCKS"; -import { AI_INTERNAL_LINK_RULES } from "~/server/chai-actions/ai/ask-ai/ai-edit-tool-contract"; +import { + SHARED_AI_HTML_RULES, + SHARED_ANIMATION_RULES, + SHARED_DATA_BINDING_RULES, + SHARED_DESIGN_SYSTEM_RULES, + SHARED_ICON_RULES, + SHARED_INTERNAL_LINK_RULES, + SHARED_LANGUAGE_CORE_RULES, + SHARED_LIBRARY_BLOCKS_RULES, + SHARED_SEO_RULES, + SHARED_STYLING_RULES, + SHARED_UPLOAD_IMAGE_RULES, +} from "~/server/chai-actions/ai/shared-instructions"; const ANIMATION_RULES = ` # ANIMATION RULES -- Add \`data-animation\` attribute to elements when appropriate to add entry animations on scroll. -- **Do not overuse animations.** Only animate important elements like hero images, feature cards & section heading etc. -- **No animation above the fold.** Do NOT add \`data-animation\` to any element in the first/hero section visible on load — above-the-fold content must render immediately without entry animations. -- The format MUST exactly be: \`data-animation="ANIMATION|EASING|DURATION|DELAY|TIME"\` - - **ANIMATION**: fade-in, slide-up, slide-down, slide-left, slide-right, zoom-in, zoom-out, flip-x, flip-y, rotate-in - - **EASING**: linear, ease-in, ease-out, ease-in-out - - **DURATION**: in milliseconds (e.g., 500, 700, 1000) - - **DELAY**: in milliseconds (e.g., 0, 200, 300) so that the animation starts after a delay and not immediately - - **TIME**: once (plays once) or infinite (repeats every time it enters the viewport) +- ${SHARED_ANIMATION_RULES} - Example: \`<div data-animation="slide-up|ease-in-out|500|300|once" class="...">\` `; -const IMAGE_RULES = ` - +const PLACEHOLDER_IMAGE_RULES = ` # IMAGE RULES -- **Use placeholder images only** — never hotlink to any other external image service (Picsum, Unsplash source, etc). placehold.co is the ONLY allowed image domain. +- **Use placeholder images only** — never hotlink to any other external image service (Picsum, Unsplash source, etc). placehold.co is the ONLY allowed image domain (unless you upload an image via \`upload_image\` or fetch one via a registered image-search tool). - Format: \`https://placehold.co/{width}x{height}/{bgHex}/{textHex}?text={Label}\` - {Label}: a short 2-3 word description of what belongs there, e.g. \`Hero+Banner\`, \`Team+Photo\`, \`Product+Shot\` (spaces become \`+\`). - - {bgHex}/{textHex}: any hue you like (pick one that suits the page — doesn't have to be blue), but both colors must be pale/light and close to each other in tone, so the label sits subtly rather than screaming for attention. Examples of the right relationship: \`c8dbfa\`/\`b0cbf7\` (pale blue), \`f2ffd6\`/\`e1f7b0\` (pale yellow-green), \`fce7f3\`/\`f9c9de\` (pale pink). Never a dark or saturated color for either value. - -- Suggested sizes: - * Hero: 1200x600 - * Cards: 400x300 - * Team: 300x300 - -- **Alt text is mandatory and must be descriptive and meaningful** — describe what the image *would* show in context, not just "image" or "placeholder". - - ✅ Good: \`alt="A modern open-plan office with large windows and natural light"\` - - ❌ Bad: \`alt="Image"\`, \`alt="Placeholder"\`, \`alt="Photo"\`, \`alt=""\` + - {bgHex}/{textHex}: pale/light and close to each other in tone (e.g. \`c8dbfa\`/\`b0cbf7\`, \`f2ffd6\`/\`e1f7b0\`, \`fce7f3\`/\`f9c9de\`). Never a dark or saturated color for either value. +- Suggested sizes: Hero 1200x600, Cards 400x300, Team 300x300. +- **Alt text is mandatory and must be descriptive and meaningful** — describe what the image shows in context, not "image" or "placeholder". - Always include explicit \`width\` and \`height\` HTML attributes on every \`<img>\` tag matching the image dimensions. - Example: \`<img src="https://placehold.co/1200x600/c8dbfa/b0cbf7?text=Hero+Banner" alt="A sweeping aerial view of a modern city skyline at sunset" width="1200" height="600">\` -- **Above-the-fold images must NOT be lazy loaded.** For any image in the first/hero section visible on load, use \`loading="eager"\` (or omit \`loading\`) — never \`loading="lazy"\`. Only images below the fold may use \`loading="lazy"\`. +- **Above-the-fold images must NOT be lazy loaded.** Use \`loading="eager"\` (or omit \`loading\`) above the fold; only below-the-fold images may use \`loading="lazy"\`. `; +const TOOL_SUMMARY_LINES: Array<{ name: string; line: string }> = [ + { + name: "read_blocks", + line: "- **read_blocks** — fetch the JSON of one or more existing blocks by bid (optionally with includeDescendants: true). PREFERRED before update_block_props for inspecting and editing copy, styles, media, links, and custom-block or library-block props.", + }, + { + name: "update_block_props", + line: "- **update_block_props** — patch JSON props on one or more existing blocks by bid without rewriting HTML. PREFERRED over edit_block for copy, styles, images, links, and custom-block or library-block updates.", + }, + { + name: "read_block_html", + line: "- **read_block_html** — fetch the full current HTML of one or more existing blocks by bid. Use only when restructuring HTML with edit_block; prefer read_blocks + update_block_props for prop/copy/style edits.", + }, + { + name: "get_page_blocks", + line: "- **get_page_blocks** — inspect the current page's draft blocks as raw JSON when needed (prefer the outline + read_blocks for normal edits).", + }, + { + name: "edit_block", + line: "- **edit_block** — replace ONE existing block (by bid) with new HTML when restructuring markup or child hierarchy. For copy, style, media, link, or custom-block prop updates, prefer read_blocks + update_block_props.", + }, + { + name: "add_blocks", + line: "- **add_blocks** — insert new HTML into the page. parentId is the bid of the container (omit for page root); position is the child index (-1 or omit to append).", + }, + { + name: "remove_blocks", + line: "- **remove_blocks** — delete blocks by bid.", + }, + { + name: "add_custom_block", + line: '- **add_custom_block** — add a registered custom block (anything listed in "Available Custom Blocks") with typed props. Prefer this over add_blocks whenever a cataloged custom block fits; do NOT hand-author HTML for those block types.', + }, + { + name: "get_library_blocks", + line: "- **get_library_blocks** — browse reusable pre-built blocks from the site's block library (filter by group or query). Call before building a section from scratch when no registered custom block fits.", + }, + { + name: "add_library_block", + line: "- **add_library_block** — insert a reusable block from the site's block library by blockId (from get_library_blocks). Returns inserted block IDs and outline so you can refine its copy if needed.", + }, + { + name: "bind_prop", + line: "- **bind_prop** — set a data binding on a prop of an existing block.", + }, + { + name: "get_partial_blocks", + line: "- **get_partial_blocks** — list available partial blocks (global reusable sections like header/footer). Call before placing <chai-partial-block> elements.", + }, + { + name: "get_pages_list", + line: "- **get_pages_list** — list the site's pages with the linkRef to use as the href when linking to one. Call before linking to another page of the site.", + }, + { + name: "get_block_translations", + line: "- **get_block_translations** — read per-language translatable props (source vs stored translation) on this page.", + }, + { + name: "update_block_translations", + line: "- **update_block_translations** — write translated prop-{lang} values onto this page's blocks without altering the fallback language or layout.", + }, + { + name: "get_page_seo", + line: "- **get_page_seo** — read this page's draft SEO, Open Graph, meta tags, and JSON-LD.", + }, + { + name: "update_page_seo", + line: "- **update_page_seo** — update this page's draft SEO fields (call get_page_seo first).", + }, + { + name: "upload_image", + line: "- **upload_image** — upload a base64 dataUrl or public http(s) sourceUrl into this site's media library and return its permanent URL + dimensions.", + }, + { + name: "get_design_system", + line: "- **get_design_system** — read the site's design system rules, theme values, design tokens, and this page's brief.", + }, + { + name: "save_design_system", + line: "- **save_design_system** — save or update the site's design system, site context, or this page's brief.", + }, + { + name: "check_page_design", + line: "- **check_page_design** — run deterministic design checks on this page's blocks (or specific blockIds).", + }, + { + name: "get_design_guide", + line: "- **get_design_guide** — read a design playbook (setup, craft-floor, critique, audit, polish, typography, color, layout, motion, copy, bolder, quieter).", + }, +]; + +const DEFAULT_ACTIVE_TOOLS = new Set([ + "read_blocks", + "update_block_props", + "read_block_html", + "get_page_blocks", + "edit_block", + "add_blocks", + "remove_blocks", + "add_custom_block", + "bind_prop", + "get_partial_blocks", + "get_pages_list", +]); + +const buildAvailableToolsText = (activeTools?: ReadonlySet<string>): string => { + const allowed = activeTools ?? DEFAULT_ACTIVE_TOOLS; + return TOOL_SUMMARY_LINES.filter((entry) => allowed.has(entry.name)) + .map((entry) => entry.line) + .join("\n"); +}; + const EDIT_PAGE_TOOLS_SYSTEM_PROMPT = - `You are the AI page editor for Chai Builder. You edit the user's page exclusively through the tools provided. You never output raw HTML in your chat text — HTML only ever appears inside tool call arguments. + `You are the AI page editor for Chai Builder. You edit the user's open page exclusively through the tools provided. You never output raw HTML in your chat text — HTML only ever appears inside tool call arguments. # 1. HOW YOU WORK (TOOL WORKFLOW — ALWAYS OBEY) @@ -45,22 +152,16 @@ You see a compact PAGE OUTLINE of the current page (below). Each line is one blo \`{bid} | {type} | {name} | {short text}\`. Indentation shows nesting. Available tools: -- **read_block_html** — fetch the full current HTML of one or more existing blocks by bid. YOU MUST call this before editing a block with edit_block. Never guess a block's markup from the outline. -- **edit_block** — replace ONE existing block (by bid) with new HTML. The html must be the full replacement for that element (its entire tag), not a partial diff. -- **add_blocks** — insert new HTML into the page. parentId is the bid of the container (omit for page root); position is the child index (-1 or omit to append). -- **remove_blocks** — delete blocks by bid. -- **add_custom_block** — add a registered custom block (anything listed in "Available Custom Blocks") with typed props. Use this — NOT HTML — for those block types. -- **bind_prop** — set a data binding on a prop of an existing block. -- **get_partial_blocks** — list available partial blocks (global reusable sections like header/footer). Call before placing <chai-partial-block> elements. -- **get_pages_list** — list the site's pages with the linkRef to use as the href when linking to one. Call before linking to another page of the site. +{{AVAILABLE_TOOLS_LIST}} Workflow rules: 1. Before each tool call, write ONE short plain-language sentence telling the user what you are about to do (e.g. "I'll brighten up the hero section with a bolder headline."). Friendly, non-technical — never mention bids, tags, HTML, tools, or code. -2. To modify an existing section: read_block_html first (batch multiple bids into one call), then edit_block. -3. Work one section at a time — one edit_block or add_blocks call per section. Never rewrite the whole page in a single call when the user asked for a targeted change. -3a. Plan first for multi-section work. When building a new page or a request that spans several sections, your FIRST message must be a brief numbered plan listing the sections you will build — one short line each (e.g. "Here's the plan: 1) Hero 2) Features 3) Testimonials 4) Pricing 5) Call to action"). Then build them one at a time in that order. This lets the user see the full scope up front and track progress while each section streams in. Skip the plan for a single targeted edit or a question. -3b. Build the ENTIRE plan in one continuous run. Add every planned section back-to-back until the page is complete. Do NOT pause partway to ask "should I continue?" or "want me to add the rest?" — only stop once every section in your plan exists, or a tool error blocks you. Yielding early with a question leaves the user with a half-built page. -3c. Compose each section's images and avatars INLINE in that section's single add_blocks call — never build a section and then follow up with separate edit_block calls to swap in each image or avatar one at a time, that wastes the turn budget and can truncate the build before later sections are added. +2. To modify existing blocks (copy, styles, images, links, or custom/library block props): call read_blocks first (batch bids, or pass includeDescendants: true for a section), then patch them with update_block_props in one call — no HTML round-trip needed. Only use read_block_html + edit_block when restructuring HTML tags or child hierarchy. +3. Work one section at a time — one update_block_props, edit_block, add_custom_block, add_library_block, or add_blocks call per section. Never rewrite the whole page in a single call when the user asked for a targeted change. +3a. Reuse ONE existing block per requested section BEFORE building from scratch. Whenever adding a new section (e.g. hero, header, footer, CTA, testimonials, stats, FAQ, blog, search, featured listings), FIRST check "Available Custom Blocks" and pick the SINGLE best-fitting block with add_custom_block; if none fits and get_library_blocks is available, check the block library and pick ONE matching template with add_library_block. When multiple variants exist for the same section (e.g. HeroOne..HeroThirteen, FeaturedListing..FeaturedListingFour), insert ONLY ONE — never add multiple variants for one requested section unless the user explicitly asks for several. Only build a section from core HTML via add_blocks when neither fits or when the user explicitly asks to build a custom section from scratch. +3b. Plan first for multi-section work. When building a new page or a request that spans several sections, your FIRST message must be a brief numbered plan listing the sections you will build — one short line each (e.g. "Here's the plan: 1) Hero 2) Features 3) Testimonials 4) Pricing 5) Call to action"). Then build them one at a time in that order. Skip the plan for a single targeted edit or a question. +3c. Build the ENTIRE plan in one continuous run. Add every planned section back-to-back until the page is complete. Do NOT pause partway to ask "should I continue?" — only stop once every section in your plan exists, or a tool error blocks you. +3d. Compose each section's images and avatars INLINE in that section's single add_blocks call — never build a section and then follow up with separate edit_block calls to swap in each image or avatar one at a time. 4. Prefer editing the smallest block that fully contains the change. If the user asks to change a headline, edit the heading's nearest sensible parent, not the entire page section — but always replace a complete element. 5. In every edit_block/add_blocks call, fill the arguments in this exact order: task first, then blockId/parentId/position, then html LAST. 6. \`task\` is a short user-facing progress label (e.g. "Redesigning hero section"). Plain language, no technical terms. @@ -78,43 +179,13 @@ The chat is read by non-technical users. Keep your visible text as short as poss - Do NOT explain your reasoning, list the steps you took, or enumerate the design choices unless the user explicitly asks. - If the user asks a question, answer in one or two plain sentences. -# 2. EDIT SEMANTICS -- edit_block html MUST be a full valid replacement of the target element, keeping its role in the layout. -- Preserve existing \`bid\` attributes on elements you keep within an edited block; do NOT invent bids for new elements — new elements simply have no bid. -- Never add a bid attribute in add_blocks html. -- Preserve all attributes you don't intentionally change (especially chai-type, data bindings, #styles: values). - -# 3. HTML GENERATION RULES (MANDATORY) - -You are an expert HTML/CSS developer specializing in Tailwind CSS and shadcn/ui patterns. -You produce clean, semantic, accessible, production-ready HTML. -Generate **pure HTML**, with no markdown, no comments, no extra text. - -### General Guidelines -1. Use **only Tailwind CSS v4 utility classes**, no custom CSS. -2. Use **shadcn/ui design system** semantic tokens for all colors. -3. Use **semantic HTML** with proper accessibility. -4. Always produce **responsive, mobile-first** layout. -5. **Do NOT include** <!DOCTYPE>, <html>, <head>, or <body>. -6. Keep UI varied — don't repeat the same layout patterns. -7. Use \`<details><summary>\` for accordion, FAQ, and mobile menu interactions. -8. Do NOT use Tailwind container queries. -9. If UI is generated from a user-provided image, ensure full responsiveness. -10. **If the user has attached an image, the HTML MUST be generated based strictly on the layout, spacing, hierarchy, and visual appearance of that image.** - - Match structure as closely as possible - - Maintain the Tailwind + shadcn theme rules - - The HTML output should reflect the exact design of the provided image - -### 🚨 CRITICAL: Avoid HTML "Div Soup" for Decorative UI Elements -**NEVER generate complex HTML markup for decorative UI elements that should be images:** -- ❌ DO NOT create HTML mockups of: code snippets, terminal windows, browser frames, device mockups, window chrome, syntax-highlighted code blocks -- ✅ INSTEAD: Use placeholder images for these decorative elements -- **Reasoning**: Complex nested div structures for visual decoration create "div soup" that bloats markup unnecessarily -- **When to use images**: If the element is purely decorative/visual and not interactive content (e.g., showing a code example as part of a design, not actual executable code) -- **Examples**: - * For a "code snippet showcase" → Use an image: \`<img src="https://placehold.co/800x400/e2e8f0/e2e8f0" alt="Code editor showing React component example" width="800" height="400">\` - * For a "browser window mockup" → Use an image: \`<img src="https://placehold.co/1000x600/e2e8f0/e2e8f0" alt="Browser window displaying dashboard interface" width="1000" height="600">\` - * For actual interactive content → Use semantic HTML +# 2. CHAIBUILDER AI-HTML & EDIT SEMANTICS (MANDATORY) + +${SHARED_AI_HTML_RULES} + +# 3. STYLING, DESIGN & HTML RULES (MANDATORY) + +${SHARED_STYLING_RULES} ### 🚨 Design Tokens (MANDATORY) You MUST use design tokens whenever appropriate. Design tokens are predefined groupings of Tailwind classes identified by the \`dt#\` prefix. @@ -125,90 +196,17 @@ You MUST use design tokens whenever appropriate. Design tokens are predefined gr **Available Design Tokens**: {{DESIGN_TOKENS_LIST}} -# 3.1 DESIGN EXCELLENCE & CREATIVITY (CRITICAL) - -Create distinctive, production-grade interfaces that avoid generic "AI slop" aesthetics. Every UI you generate should be visually striking, memorable, and intentionally designed. - -### Design Thinking Process -Before generating HTML, commit to a BOLD aesthetic direction: -- **Purpose**: Consider what problem this interface solves and who uses it -- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember? - -**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. - -### Design Excellence Guidelines - -**Typography & Font Selection**: -- Choose fonts that are beautiful, unique, and interesting -- AVOID generic fonts: Arial, Inter, Roboto, system fonts -- Use distinctive font combinations that elevate the design -- Pair a distinctive display font with a refined body font -- Use weight variations (font-light, font-bold) creatively -- **Do NOT apply \`font-serif\` (or any default font-family utility like \`font-sans\`/\`font-mono\`) unless the user explicitly asks for that style.** Rely on the theme's default typography by default. - -**Color & Visual Hierarchy**: -- Commit to a cohesive aesthetic with dominant colors and sharp accents -- Avoid timid, evenly-distributed palettes -- Use shadcn tokens creatively (not just bg-background everywhere) -- Consider bold color blocking, dramatic contrasts, or refined monochrome -- AVOID: purple gradients on white backgrounds, predictable color schemes - -**Spatial Composition**: -- Create unexpected layouts with asymmetry, overlap, diagonal flow -- Use grid-breaking elements and generous negative space OR controlled density -- Avoid predictable grid patterns - be creative with positioning -- Consider: absolute positioning, creative flexbox/grid layouts, overlapping elements - -**Backgrounds & Visual Details**: -- Create atmosphere and depth rather than defaulting to solid colors -- Consider: gradient meshes, subtle textures, geometric patterns -- Use layered transparencies, dramatic shadows, decorative borders -- Add visual interest with background patterns or accent elements - -**NEVER Use Generic AI Aesthetics**: -- Overused font families (Inter, Roboto, Arial, system fonts) -- Cliched color schemes (purple gradients on white) -- Predictable layouts and component patterns -- Cookie-cutter designs lacking context-specific character -- NEVER converge on common choices (Space Grotesk, etc.) across generations - -**Implementation Complexity**: -- Match complexity to the aesthetic vision -- Maximalist designs: elaborate code with extensive effects -- Minimalist designs: restraint, precision, careful spacing and typography -- Elegance comes from executing the vision well - -**Variation Mandate**: -- Every design should be different -- Vary between light and dark themes -- Change fonts, layouts, color schemes between generations -- Interpret user requests creatively with unexpected choices - - -# 4. ATTRIBUTE & CUSTOM COMPONENT RULES - -### chai-name -- Add \`chai-name\` attribute to tags -- Use descriptive section names (e.g., "Hero Section", "Navigation"). - -## Custom Web components(CRITICAL) -- Html can have custom web components. All web components starts with <chai- prefix. -- Use "about-this-component" attribute to understand what the component does. -- Check for can-move and can-delete attribute to check if the component can be moved or deleted. -- If an attribute value starts with #styles: treat it like class attribute with tailwind classes. - Use the attribute key to understand what the attribute does and apply classes. Maintain the #styles: at start followed by tailwind classes. -- Do not change the chai-type attribute. Do not remove any attributes. +### Typography & Hover Guidelines +- **Do NOT apply \`font-serif\` (or default font-family utilities like \`font-sans\`/\`font-mono\`) unless explicitly requested.** Rely on the theme's default typography. +- Primary buttons: hover:bg-primary/90; Cards: hover:bg-accent hover:text-accent-foreground; Links: text-muted-foreground hover:text-foreground; Nav links: text-foreground/80 hover:text-foreground. +{{DESIGN_SYSTEM_SECTION}} + +# 4. DATA BINDING, CUSTOM BLOCKS, LINKS & ICONS ## Data Binding (CRITICAL) -- Block prop values may contain non-executable bindings: {{path.to.data | pipe 'literal argument'}} -- When you see {{...}} in an existing element's attribute value, it is a live data binding — NEVER remove or replace it with a static value. Preserve it exactly. -- You MAY use binding expressions when setting props on custom blocks, but ONLY using paths listed in the "Available Data Binding Paths" section below. -- Repeater blocks use a special prop: repeater-items="{{collectionName}}" where collectionName is the array to iterate. -- Inside a Repeater, child block props can reference each item's fields via {{$index.fieldName}}. -- Binding syntax must use exactly two curly braces: {{path}} — not {path} or \${{path}}. +${SHARED_DATA_BINDING_RULES} - Pipes may be chained. Arguments must be primitive literals; never use JavaScript, operators, method calls, or path-valued arguments. -- Prefer plain {{path}} bindings. Add a pipe only when it performs formatting or fallback behavior explicitly needed by the request. NEVER append the default pipe routinely; use it only when the user explicitly requests a fallback value. -- Only use pipes listed below. Boolean-returning pipes are reserved for the _show conditional visibility property and must not be used in regular block properties. Examples: {{listing.price | currency 'USD'}}, {{listing.title | trim | uppercase}}. For _show: {{listing.price | gt 0}}. +- NEVER append the default pipe routinely; use it only when the user explicitly requests a fallback value. - (global) paths are site-wide and available on every page. (page) paths are only available on this specific page type. **Available Data Binding Paths**: @@ -221,113 +219,68 @@ Before generating HTML, commit to a BOLD aesthetic direction: {{PAGE_TYPE_CONTEXT}} ## Available Custom Blocks -The following custom block types are registered and available. To ADD one of these, USE THE add_custom_block TOOL with camelCase props — do NOT generate <chai-*> HTML for them. When one already exists in the page you may edit its props via edit_block (keeping every attribute intact) or bind_prop. +Check this catalog FIRST before building any new section with add_blocks. When a registered custom block fits the request (e.g. hero, footer, CTA, testimonials, stats, FAQ, blog, featured listings), pick the SINGLE best-fitting block and insert ONLY ONE via the add_custom_block tool with camelCase props — numbered/named variants in a group (e.g. HeroOne..HeroThirteen, FeaturedListing..FeaturedListingFour) are mutually exclusive design alternatives, so NEVER add multiple variants for one requested section unless the user explicitly asks for several. Never generate <chai-*> HTML for them, and do not recreate a matching custom block out of core HTML unless the user explicitly asks to build one from scratch. When one already exists in the page, edit its props via read_blocks + update_block_props (or bind_prop). -{{CUSTOM_BLOCK_CATALOG}} +{{CUSTOM_BLOCK_CATALOG}}{{LIBRARY_BLOCKS_SECTION}} ## Special Blocks These may appear as web components INSIDE the html argument of add_blocks/edit_block: ### Repeater — <chai-repeater> -Used to render a list by iterating over an array data binding. -- Required prop: \`repeater-items="{{arrayPath}}"\` where \`arrayPath\` is an array-type binding path. -- Only bind to paths listed in the "Arrays" section of "Available Data Binding Paths". -- Child blocks inside a Repeater reference the current item's fields using \`{{$index.fieldName}}\` — use only the item fields listed for that array; never invent a field name. -- Example: \`<chai-repeater repeater-items="{{page.products}}"><h3>{{$index.name}}</h3></chai-repeater>\` -- Do NOT use a Repeater for static lists — only when iterating over bound data. - -### PartialBlock — <chai-partial-block> -Partial blocks are global reusable blocks (e.g. header, footer, navigation) shared across pages. -- Reference them by their ID: \`<chai-partial-block partial-id="THE_PARTIAL_ID"></chai-partial-block>\` -- Never modify a partial block's content inline — only reference it. Their content is edited on the partial's own page. -- When asked to build a full page layout, call the \`get_partial_blocks\` tool to discover available partial IDs before placing them. -- Only use IDs returned by \`get_partial_blocks\` — never invent one, and NEVER reference the page currently being edited (a partial can't contain itself). -- Partials nest at most ${MAX_PARTIAL_DEPTH} levels below a page. The tool already filters its list to what is allowed here; if it returns none, explain the limit to the user instead of placing a partial. - -## Links -${AI_INTERNAL_LINK_RULES.map((rule) => `- ${rule}`).join("\n")} -- Call \`get_pages_list\` once before writing the first link to another page; never invent a page id. +- Required prop: \`repeater-items="{{arrayPath}}"\` using only paths listed in "Arrays" above. +- Child blocks reference item fields using \`{{$index.fieldName}}\`.{{PARTIAL_BLOCK_SECTION}}{{LINKS_SECTION}} ## Icons -- Icons use the **Lucide** icon set (https://lucide.dev/icons). -- Always include \`chai-type="Icon"\` on icon elements and preserve any existing attributes (e.g. \`bid\`). -- Express each icon as \`<chai-icon chai-type="Icon" icon-name="kebab-case-name" width="16" height="16">\` - e.g. \`<chai-icon chai-type="Icon" icon-name="search" width="16" height="16">\`, \`<chai-icon chai-type="Icon" icon-name="arrow-right" width="24" height="24">\`. -- Pick semantically appropriate icon names from Lucide; do not embed raw \`<svg>\` markup inside \`<chai-icon>\`. - -### SVG -- Always include width/height attributes. -- Ensure correct \`viewBox\`. - - -# 5. SHADCN/THEME COLOR RULES (STRICT) - -Use ONLY these semantic tokens: -- bg-background + text-foreground -- bg-card + text-card-foreground -- bg-primary + text-primary-foreground -- bg-secondary + text-secondary-foreground -- bg-muted + text-muted-foreground -- bg-accent + text-accent-foreground -- bg-destructive + text-destructive-foreground -- border-border, border-input -- ring-ring +${SHARED_ICON_RULES} -### Contrast Rules -- Always maintain clear readable contrast. -- Never pair same-family bg/text tokens (e.g., bg-primary + text-primary). +# 5. LANGUAGE, SEO, ANIMATION & IMAGES -### Hover Rules -- Primary buttons: hover:bg-primary/90 -- Cards: hover:bg-accent hover:text-accent-foreground -- Links: text-muted-foreground hover:text-foreground -- Nav links: text-foreground/80 hover:text-foreground +## Language +${SHARED_LANGUAGE_CORE_RULES} +{{SEO_SECTION}}{{ANIMATION_RULES}}{{IMAGE_RULES}} - -# 6. RESPONSIVENESS RULES - -- Mobile-first approach. -- Breakpoints: sm, md, lg, xl. -- Smooth scaling between sizes. -- At md breakpoint: - * Reduce grid columns (lg:4 → md:2 → sm:1) - * Adjust padding, spacing, and layouts - * Ensure nav/mobile menus behave correctly - * Ensure cards remain aligned - - -# 7. SPECIFIC UI PATTERNS - -### Forms & Fields -- Always include proper \`type\` and \`autocomplete\` attributes for form fields (e.g., \`type=\"email\" autocomplete=\"email\"\`, \`type=\"text\" autocomplete=\"given-name\"\`, \`type=\"tel\" autocomplete=\"tel\"\`). - -### Mobile Menu (<details><summary>) -- Use 'summary' containing an SVG hamburger icon. -- Mobile menu container sample: - absolute right-1 mt-2 min-w-64 bg-card border border-border rounded-lg shadow-lg z-50 p-4 -- Menu item sample: - block py-2 px-4 hover:bg-accent rounded-md transition-colors -- Touch targets must be at least 44px tall. - -### Accordions / Nested Menus -- Always use <details> and <summary>. - - -# 8. COMMON RULES - -{{ANIMATION_RULES}} -{{IMAGE_RULES}} - -# 9. CURRENT PAGE OUTLINE +# 6. CURRENT PAGE OUTLINE Each line: bid | type | name | short text. Indentation = nesting. This reflects the page state at the start of this request; your applied tool calls update the real page immediately. {{PAGE_OUTLINE}} `.trim(); -export const getEditPageToolsSystemPrompt = (options: { animation?: boolean } = {}): string => { +export const getEditPageToolsSystemPrompt = ( + options: { animation?: boolean; activeTools?: ReadonlySet<string> } = {}, +): string => { + const active = options.activeTools; + const effective = active ?? DEFAULT_ACTIVE_TOOLS; + const hasAny = (...names: string[]) => (active ? names.some((n) => active.has(n)) : false); + const hasEffective = (name: string) => effective.has(name); + + const partialBlockSection = hasEffective("get_partial_blocks") + ? `\n\n### PartialBlock — <chai-partial-block>\n- Reference by ID returned from \`get_partial_blocks\`: \`<chai-partial-block partial-id="THE_PARTIAL_ID"></chai-partial-block>\`.\n- Partials nest at most ${MAX_PARTIAL_DEPTH} levels below a page. The tool already filters its list to what is allowed here; if it returns none, explain the limit to the user instead of placing a partial.` + : ""; + const linksSection = hasEffective("get_pages_list") + ? `\n\n## Links\n${SHARED_INTERNAL_LINK_RULES}\n- Call \`get_pages_list\` once before writing the first link to another page; never invent a page id.` + : ""; + + const libraryBlocksSection = hasAny("get_library_blocks", "add_library_block") + ? `\n\n## Block Library\n${SHARED_LIBRARY_BLOCKS_RULES}` + : ""; + + const seoSection = hasAny("get_page_seo", "update_page_seo") ? `\n\n## SEO\n${SHARED_SEO_RULES}` : ""; + const designSystemSection = hasAny("get_design_system") + ? `\n\n## Design System\n${SHARED_DESIGN_SYSTEM_RULES}` + : ""; + const uploadImageSection = hasAny("upload_image") + ? `\n\n# MEDIA UPLOAD RULES\n${SHARED_UPLOAD_IMAGE_RULES}\n` + : ""; + let prompt = EDIT_PAGE_TOOLS_SYSTEM_PROMPT; - prompt = prompt.replace("{{ANIMATION_RULES}}", options?.animation ? ANIMATION_RULES : ""); - prompt = prompt.replace("{{IMAGE_RULES}}", IMAGE_RULES); + prompt = prompt.replace("{{AVAILABLE_TOOLS_LIST}}", () => buildAvailableToolsText(active)); + prompt = prompt.replace("{{LIBRARY_BLOCKS_SECTION}}", () => libraryBlocksSection); + prompt = prompt.replace("{{PARTIAL_BLOCK_SECTION}}", () => partialBlockSection); + prompt = prompt.replace("{{LINKS_SECTION}}", () => linksSection); + prompt = prompt.replace("{{DESIGN_SYSTEM_SECTION}}", () => designSystemSection); + prompt = prompt.replace("{{SEO_SECTION}}", () => seoSection); + prompt = prompt.replace("{{ANIMATION_RULES}}", () => (options.animation ? ANIMATION_RULES : "")); + prompt = prompt.replace("{{IMAGE_RULES}}", () => `${uploadImageSection}${PLACEHOLDER_IMAGE_RULES}`); return prompt; }; diff --git a/src/server/chai-actions/pages/get-website-pages.ts b/src/server/chai-actions/pages/get-website-pages.ts index 246d1fff1..6ef4fef3b 100644 --- a/src/server/chai-actions/pages/get-website-pages.ts +++ b/src/server/chai-actions/pages/get-website-pages.ts @@ -1,8 +1,9 @@ import { and, eq, inArray, isNull } from "drizzle-orm"; -import { isEmpty } from "lodash-es"; +import { compact, isEmpty, uniq } from "lodash-es"; import { z } from "zod"; import { db, safeQuery, schema } from "~/server/chai-actions/db"; import { apiError } from "~/server/chai-actions/lib"; +import { getConfigUpstreamPageSource, isFeatureEnabled } from "~/server/defaults/config-registry"; import { ChaiBaseAction } from "../base-action"; export type GetWebsitePagesActionData = { @@ -32,8 +33,20 @@ type GetWebsitePagesActionResponse = Array<{ /** The page this one renders while `useUpstream` is on (upstream pages). */ upstream: string | null; useUpstream: boolean; + canDuplicate?: boolean; }>; +async function readCanDuplicate(ids: string[], appId: string): Promise<Record<string, boolean> | null> { + const source = getConfigUpstreamPageSource(); + if (!isFeatureEnabled("upstreamPages") || !source?.canDuplicate || ids.length === 0) return null; + try { + return await source.canDuplicate({ ids, appId }); + } catch (error) { + console.error("Failed to read upstream canDuplicate:", error); + return null; + } +} + export class GetWebsitePagesAction extends ChaiBaseAction<GetWebsitePagesActionData, GetWebsitePagesActionResponse> { protected getValidationSchema() { return z.object({ @@ -108,6 +121,8 @@ export class GetWebsitePagesAction extends ChaiBaseAction<GetWebsitePagesActionD // Create a set of pageIds that are templates for O(1) lookup const templatePageIds = new Set((templates || []).map((t) => t.pageId)); + const duplicable = await readCanDuplicate(uniq(compact(pages.map((page) => page.upstream))), appId); + // Map the pages with template information return pages.map((page) => ({ ...page, @@ -119,6 +134,7 @@ export class GetWebsitePagesAction extends ChaiBaseAction<GetWebsitePagesActionD links: page.links, partialBlocks: page.partialBlocks, metadata: (page.metadata as Record<string, unknown> | null) ?? null, + ...(page.upstream && duplicable ? { canDuplicate: duplicable[page.upstream] !== false } : {}), })); } } diff --git a/src/server/chai-actions/pages/upstream-pages.ts b/src/server/chai-actions/pages/upstream-pages.ts index 45f6989db..6ea345186 100644 --- a/src/server/chai-actions/pages/upstream-pages.ts +++ b/src/server/chai-actions/pages/upstream-pages.ts @@ -87,6 +87,15 @@ export class CloneUpstreamPageAction extends ChaiBaseAction<{ id: string }, { ta // The upstream is reached only through the linked page's own stored pointer. const { upstream: upstreamId, lastSaved } = await readUpstreamPointer(id, appId, true); + let duplicable: Record<string, boolean> | undefined; + try { + duplicable = await source.canDuplicate?.({ ids: [upstreamId], appId }); + } catch (error) { + throw new ActionError("Failed to read upstream page", "UPSTREAM_LOOKUP_FAILED", 500, error); + } + if (duplicable?.[upstreamId] === false) { + throw new ActionError("This page can't be duplicated", "UPSTREAM_PAGE_LOCKED", 403); + } const content = await source.getContent(upstreamId, { appId }).catch((error: unknown) => { throw new ActionError("Failed to read upstream page", "UPSTREAM_LOOKUP_FAILED", 500, error); }); diff --git a/src/server/chai-actions/website/theme-patch.ts b/src/server/chai-actions/website/theme-patch.ts index 5c4b89e40..b775fe623 100644 --- a/src/server/chai-actions/website/theme-patch.ts +++ b/src/server/chai-actions/website/theme-patch.ts @@ -16,6 +16,14 @@ export const THEME_HEX_RE = /^#[0-9a-fA-F]{6}$/; const hex = z.string().regex(THEME_HEX_RE, "must be a #RRGGBB hex colour"); const fontFamily = z.string().trim().regex(THEME_FONT_FAMILY_RE, "is not a font family name"); +const colorPair = z.tuple([hex, hex]); +// Explicit optional properties instead of z.partialRecord so AI SDK's zodSchema() +// emits usable per-key JSON Schema properties rather than `additionalProperties: false` +// with no properties (which forces strict models to send only `{}`). +const themeColorsPatchShape = Object.fromEntries( + CHAI_THEME_COLOR_KEYS.map((key) => [key, colorPair.optional()]), +) as Record<(typeof CHAI_THEME_COLOR_KEYS)[number], z.ZodOptional<typeof colorPair>>; + export const chaiThemePatchShape = { fontFamily: z .strictObject({ @@ -30,7 +38,7 @@ export const chaiThemePatchShape = { .optional() .describe("Base radius in px or rem, e.g. 8px; rounded-lg uses it, rounded-md and rounded-sm step down."), colors: z - .partialRecord(z.enum(CHAI_THEME_COLOR_KEYS), z.tuple([hex, hex])) + .strictObject(themeColorsPatchShape) .optional() .describe( "Colours to change, keyed by theme role (background, foreground, primary, primary-foreground, muted, muted-foreground, card, border…), each a [light, dark] pair of #RRGGBB values.", diff --git a/src/server/chai-builder/public/get-site-domains.ts b/src/server/chai-builder/public/get-site-domains.ts index aefe1c7e6..f19b8005c 100644 --- a/src/server/chai-builder/public/get-site-domains.ts +++ b/src/server/chai-builder/public/get-site-domains.ts @@ -18,7 +18,15 @@ async function fetchSiteDomains(appId: string): Promise<SiteDomains> { if (error || !data?.subdomain) { console.error("Error fetching site domains", error); - throw new Error("SITE_DOMAINS_NOT_FOUND"); + const detail = + error instanceof Error + ? error.message + : error + ? String(error) + : !resolver + ? "no site domain resolver registered" + : "no subdomain found for site"; + throw new Error(`SITE_DOMAINS_NOT_FOUND (${detail})`, error ? { cause: error } : undefined); } return data; diff --git a/src/types/blocks.ts b/src/types/blocks.ts index d75adc4fe..44658640e 100644 --- a/src/types/blocks.ts +++ b/src/types/blocks.ts @@ -86,6 +86,11 @@ export interface ChaiBlockConfig { showInLibrary?: boolean; /** Image URL shown as the block's card in the Library tab. Used with `showInLibrary`. */ preview?: string; + /** + * Arbitrary host-defined metadata stored on the block config. Chai never reads + * it; host code (such as `canShowBlock`) can inspect it. + */ + metadata?: Record<string, unknown>; dataProviderMode?: "live" | "mock"; dataProviderDependencies?: string[]; diff --git a/src/types/chaibuilder-config.ts b/src/types/chaibuilder-config.ts index ef731d181..2c9b8b288 100644 --- a/src/types/chaibuilder-config.ts +++ b/src/types/chaibuilder-config.ts @@ -243,6 +243,11 @@ export type ChaiUpstreamPageSource = { id: string, args: { appId: string; live?: boolean }, ): Promise<{ blocks: ChaiBlock[]; seo: Record<string, unknown> } | null>; + /** + * Whether site `appId` may duplicate each upstream page in `ids`, keyed by id. + * A missing id, or no method, means it may. + */ + canDuplicate?(args: { ids: string[]; appId: string }): Promise<Record<string, boolean>>; }; /** diff --git a/src/types/chaibuilder-editor-props.ts b/src/types/chaibuilder-editor-props.ts index 50a09c5da..df842583b 100644 --- a/src/types/chaibuilder-editor-props.ts +++ b/src/types/chaibuilder-editor-props.ts @@ -16,8 +16,19 @@ export type ChaiLibraryBlock<T = Record<string, any>> = { description?: string; /** Overrides `libraryGroupMaxDepth` for this block. See `ChaiBlockConfig.maxDepth`. */ maxDepth?: number; + /** Arbitrary host-defined metadata. Chai stores it and passes it to `canShowBlock`. */ + metadata?: Record<string, unknown>; } & T; +export type ChaiCanShowBlockContext = { + pageType?: string; +}; + +export type ChaiCanShowBlock = ( + block: { type?: string; id?: string; metadata?: Record<string, unknown> }, + ctx: ChaiCanShowBlockContext, +) => boolean; + export type ChaiLibrary<T = Record<string, any>> = { id: string; name: string; @@ -159,6 +170,11 @@ export interface ChaiBuilderEditorProps { */ pageId?: string; + /** + * Page type of the open page; a slugless type marks a partial/global block + */ + pageType?: string; + /** * Page external data */ @@ -427,6 +443,12 @@ export interface ChaiBuilderEditorProps { }; }; + /** + * Host-supplied predicate deciding whether a block should appear in the Add Block panels + * and search results. Omitted means every block is shown (subject to `pageTypes`). + */ + canShowBlock?: ChaiCanShowBlock; + /** * Screen to small message component */ diff --git a/src/types/common.ts b/src/types/common.ts index 17c73d017..35c6287ae 100644 --- a/src/types/common.ts +++ b/src/types/common.ts @@ -96,6 +96,7 @@ export type ChaiWebsiteBuilderProps = { | "labels" | "libraryGroupMaxDepth" | "panelWidth" + | "canShowBlock" >; export type ChaiPageProps<T = Record<string, any>> = { diff --git a/src/utils/blocks-tree-ops.ts b/src/utils/blocks-tree-ops.ts index dd0a85f00..c92e6fb73 100644 --- a/src/utils/blocks-tree-ops.ts +++ b/src/utils/blocks-tree-ops.ts @@ -15,6 +15,21 @@ export { insertBlocksAtPosition } from "~/builder/hooks/history/insert-block-at- const fitsMaxDepth = (parentId: string, allBlocks: ChaiBlock[], maxDepth: number) => maxDepth < 0 || getBlockDepth(parentId, allBlocks) + 1 <= maxDepth; +const canPlaceInto = (parent: ChaiBlock, childType: string, allBlocks: ChaiBlock[], depthLimit: number) => + canAcceptInto(parent, childType, allBlocks) && + canBeNestedInside(parent._type, childType) && + // A slot takes whatever its owner's accept rule allows at any depth: the owner made room for it. + (fitsMaxDepth(parent._id, allBlocks, depthLimit) || parent._type === "ChaiSlot"); + +// Whether a block of `childType` may take `blockId`'s place under the same parent. +export const canReplaceWith = (blockId: string, childType: string, allBlocks: ChaiBlock[], maxDepth?: number) => { + const target = find(allBlocks, { _id: blockId }); + if (!target) return false; + if (!target._parent) return true; + const parent = find(allBlocks, { _id: target._parent }); + return !!parent && canPlaceInto(parent, childType, allBlocks, maxDepth ?? getBlockMaxDepth(childType)); +}; + /** * Resolve the nearest valid parent and insertion position for a new block. * Callers that accept an explicit parent must validate that id exists first; @@ -45,12 +60,7 @@ export const getParentAndPosition = ( const candidateParent = allBlocks.find((block) => block._id === currentTargetId); if (!candidateParent) break; - if ( - canAcceptInto(candidateParent, childType, allBlocks) && - canBeNestedInside(candidateParent._type, childType) && - // A slot takes whatever its owner's accept rule allows at any depth: the owner made room for it. - (fitsMaxDepth(candidateParent._id, allBlocks, depthLimit) || candidateParent._type === "ChaiSlot") - ) { + if (canPlaceInto(candidateParent, childType, allBlocks, depthLimit)) { parentBlockId = candidateParent._id; break; } @@ -198,3 +208,24 @@ export const removeNestedBlocks = (blocks: ChaiBlock[], blockIds: Array<string>) if (!isEmpty(_blockIds)) return removeNestedBlocks(_blocks, _blockIds); return _blocks; }; + +/** Collect the given root block IDs and every descendant ID inside them. */ +export function collectSubtreeIds(blocks: ChaiBlock[], roots: string[]): Set<string> { + const children = new Map<string, string[]>(); + for (const block of blocks) { + if (!block._parent) continue; + const list = children.get(block._parent); + if (list) list.push(block._id); + else children.set(block._parent, [block._id]); + } + const ids = new Set<string>(); + const stack = [...roots]; + while (stack.length) { + const id = stack.pop() as string; + if (ids.has(id)) continue; + ids.add(id); + const next = children.get(id); + if (next) stack.push(...next); + } + return ids; +} diff --git a/src/utils/design-checks/evaluate-write-checks.ts b/src/utils/design-checks/evaluate-write-checks.ts new file mode 100644 index 000000000..f1dd0e93e --- /dev/null +++ b/src/utils/design-checks/evaluate-write-checks.ts @@ -0,0 +1,89 @@ +import { isEqual } from "lodash-es"; +import type { ChaiBlock } from "~/types/common"; +import type { ChaiDesignChecksMode } from "~/types/design-system"; +import { filterFindingsToBlocks, formatDesignFindings, runDesignChecks } from "./run-design-checks"; +import type { ChaiDesignCheckContext, ChaiDesignFinding } from "./types"; + +const LISTED_ON_WRITE = 5; +const LISTED_ON_REJECT = 8; + +const findingKey = (finding: ChaiDesignFinding) => + [finding.rule, finding.scope, finding.blockId ?? "", (finding.blockIds ?? []).join(","), finding.message].join("|"); + +const indent = (text: string) => + text + .split("\n") + .map((line) => ` ${line}`) + .join("\n"); + +/** + * Ids of blocks that are new in `after`, differ from their version in `before`, or were + * removed. A removal counts: deleting the h2 between an h1 and an h3 leaves every surviving + * block unchanged but still breaks the heading order. + * @internal + */ +export function changedBlockIds(before: ChaiBlock[], after: ChaiBlock[]): Set<string> { + const previous = new Map(before.map((block) => [block._id, block])); + const changed = new Set<string>(); + for (const block of after) { + const old = previous.get(block._id); + if (!old || !isEqual(old, block)) changed.add(block._id); + previous.delete(block._id); + } + for (const id of previous.keys()) changed.add(id); + return changed; +} + +export type BlockWriteDesignCheckResult = + | { status: "skipped"; note: "" } + | { status: "rejected"; reject: string; errors: number; warnings: number } + | { status: "clean"; note: string; errors: 0; warnings: 0 } + | { status: "findings"; note: string; errors: number; warnings: number }; + +/** + * Pure write-time design check shared by MCP (`runDesignHook`) and Builder AI (`useAiPageChat`). + * Judges only the blocks the edit changed plus findings newly introduced by the edit. + */ +export function evaluateDesignCheckDiff( + before: ChaiBlock[], + after: ChaiBlock[], + ctx: ChaiDesignCheckContext, + mode: ChaiDesignChecksMode, +): BlockWriteDesignCheckResult { + if (mode === "off") return { status: "skipped", note: "" }; + + const changed = changedBlockIds(before, after); + if (changed.size === 0) return { status: "skipped", note: "" }; + + const afterFindings = runDesignChecks(after, ctx); + const onChanged = new Set(filterFindingsToBlocks(afterFindings, changed)); + const existing = new Set(runDesignChecks(before, ctx).map(findingKey)); + const findings = afterFindings.filter((finding) => onChanged.has(finding) || !existing.has(findingKey(finding))); + const errors = findings.filter((finding) => finding.severity === "error"); + const warnings = findings.length - errors.length; + + if (mode === "strict" && errors.length > 0) { + return { + status: "rejected", + reject: `Error: Design check failed, so nothing was saved. Fix these and send the edit again:\n${formatDesignFindings(errors, LISTED_ON_REJECT)}`, + errors: errors.length, + warnings, + }; + } + + if (findings.length === 0) { + return { + status: "clean", + note: "\n- Design check: no findings on the changed blocks (evidence, not proof: run check_page_design before asking to publish).", + errors: 0, + warnings: 0, + }; + } + + return { + status: "findings", + note: `\n- Design check: ${errors.length} error(s), ${warnings} warning(s) on the changed blocks; fix the errors before moving on:\n${indent(formatDesignFindings(findings, LISTED_ON_WRITE))}`, + errors: errors.length, + warnings, + }; +} diff --git a/src/utils/design-checks/index.ts b/src/utils/design-checks/index.ts index 9c0355466..7dfe3f0e4 100644 --- a/src/utils/design-checks/index.ts +++ b/src/utils/design-checks/index.ts @@ -1,4 +1,9 @@ export { filterFindingsToBlocks, formatDesignFindings, runDesignChecks } from "./run-design-checks"; +export { + changedBlockIds, + evaluateDesignCheckDiff, + type BlockWriteDesignCheckResult, +} from "./evaluate-write-checks"; export { CONTRAST_BODY, CONTRAST_LARGE, hexContrastRatio, parseHexColor } from "./contrast"; export { parseBannedWords } from "./rules/content"; export { describeContrastIssue, themeContrastIssues, type ThemeContrastIssue } from "./rules/color"; diff --git a/src/utils/design-checks/rules/structure.ts b/src/utils/design-checks/rules/structure.ts index cdac2ed40..f0d394381 100644 --- a/src/utils/design-checks/rules/structure.ts +++ b/src/utils/design-checks/rules/structure.ts @@ -119,7 +119,58 @@ export const identicalEntranceAnimationRule: ChaiDesignRule = { }, }; -export const STRUCTURE_RULES = [nestedCardsRule, repeatedSectionLayoutRule, identicalEntranceAnimationRule]; +const SECTION_LAYOUT_TOKENS = ["dt#site-content-width", "dt#content-gutter-x", "dt#content-gutter-y"] as const; + +const collectSubtreeTokens = (graph: DesignGraph, root: DesignNode): Set<string> => { + const tokens = new Set<string>(); + const stack: DesignNode[] = [root]; + while (stack.length > 0) { + const node = stack.pop()!; + for (const set of node.styleSets) { + for (const token of set.tokens) tokens.add(token); + } + for (const child of graph.children(node)) stack.push(child); + } + return tokens; +}; + +/** + * Every top-level page `<section>` must handle `dt#site-content-width`, `dt#content-gutter-x`, + * and `dt#content-gutter-y` (typically `dt#content-gutter-y` on `<section>` and + * `dt#site-content-width dt#content-gutter-x` on its inner content wrapper `<div>`) so all + * sections stay uniform and controllable via site layout and design tokens. + */ +export const sectionLayoutTokensRule: ChaiDesignRule = { + id: "section-layout-tokens", + run: (graph, ctx) => { + if (ctx.isPartial) return []; + const required = SECTION_LAYOUT_TOKENS.filter((token) => !ctx.designTokens?.[token]?.archived); + if (required.length === 0) return []; + + return graph.roots.flatMap((root) => { + if ((root.type !== "Box" && root.type !== "EmptyBox") || root.tag !== "section") return []; + const present = collectSubtreeTokens(graph, root); + const missing = required.filter((token) => !present.has(token)); + if (missing.length === 0) return []; + return [ + blockFinding( + "section-layout-tokens", + "warn", + root, + `Page section is missing layout design token(s): ${missing.join(", ")}.`, + "Put dt#content-gutter-y on the outer <section> and dt#site-content-width dt#content-gutter-x on its inner content wrapper <div> (never hand-write section py-/px-/max-w- or prefix dt# tokens with breakpoints).", + ), + ]; + }); + }, +}; + +export const STRUCTURE_RULES = [ + sectionLayoutTokensRule, + nestedCardsRule, + repeatedSectionLayoutRule, + identicalEntranceAnimationRule, +]; // Exported for the interaction rules, which share the notion of a painted surface. export const paintsSurface = (utilities: string[]) => diff --git a/src/utils/design-checks/run-design-checks.test.ts b/src/utils/design-checks/run-design-checks.test.ts index 43afad989..f02270610 100644 --- a/src/utils/design-checks/run-design-checks.test.ts +++ b/src/utils/design-checks/run-design-checks.test.ts @@ -15,15 +15,16 @@ describe("runDesignChecks", () => { it("returns nothing for an empty page and a clean, themed section", () => { expect(check([])).toEqual([]); const clean = [ - b("s", "Box", { tag: "section", styles: S("bg-background py-24") }), + b("s", "Box", { tag: "section", styles: S("dt#content-gutter-y bg-background") }), + b("inner", "Box", { tag: "div", styles: S("dt#site-content-width dt#content-gutter-x") }, "s"), b( "h", "Heading", { tag: "h1", content: "Bread, slowly", styles: S("font-heading text-5xl text-foreground") }, - "s", + "inner", ), - b("p", "Paragraph", { content: "Baked overnight.", styles: S("max-w-prose text-muted-foreground") }, "s"), - b("a", "Button", { content: "See the menu", styles: S("dt#btn dt#btn-primary") }, "s"), + b("p", "Paragraph", { content: "Baked overnight.", styles: S("max-w-prose text-muted-foreground") }, "inner"), + b("a", "Button", { content: "See the menu", styles: S("dt#btn dt#btn-primary") }, "inner"), ]; expect(check(clean)).toEqual([]); }); @@ -400,6 +401,45 @@ describe("runDesignChecks", () => { }); }); + describe("section-layout-tokens", () => { + it("warns when a top-level page section omits site-content-width or content-gutter tokens", () => { + const findings = check([ + b("s1", "Box", { tag: "section", styles: S("bg-background py-20") }), + b("inner1", "Box", { tag: "div", styles: S("mx-auto max-w-6xl px-6") }, "s1"), + ]); + expect(only(findings, "section-layout-tokens")).toMatchObject([ + { + severity: "warn", + blockId: "s1", + message: expect.stringContaining("dt#site-content-width, dt#content-gutter-x, dt#content-gutter-y"), + }, + ]); + }); + + it("passes when outer section uses dt#content-gutter-y and inner wrapper uses dt#site-content-width dt#content-gutter-x", () => { + const findings = check([ + b("s1", "Box", { tag: "section", styles: S("dt#content-gutter-y bg-background") }), + b("inner1", "Box", { tag: "div", styles: S("dt#site-content-width dt#content-gutter-x") }, "s1"), + ]); + expect(only(findings, "section-layout-tokens")).toEqual([]); + }); + + it("skips partials and archived layout tokens", () => { + const bareSection = [b("s1", "Box", { tag: "section", styles: S("bg-background py-8") })]; + expect(only(check(bareSection, { isPartial: true }), "section-layout-tokens")).toEqual([]); + + const archivedFindings = check( + [b("s1", "Box", { tag: "section", styles: S("dt#site-content-width dt#content-gutter-x") })], + { + designTokens: { + "dt#content-gutter-y": { name: "Content-Gutter-Y", value: "py-8", archived: true }, + }, + }, + ); + expect(only(archivedFindings, "section-layout-tokens")).toEqual([]); + }); + }); + describe("ordering, filtering and formatting", () => { const blocks = [ b("s", "Box", { styles: S("bg-blue-500") }), diff --git a/src/utils/import-html/restore-block-prop-types.ts b/src/utils/import-html/restore-block-prop-types.ts index 69550cb9c..8c0eb0141 100644 --- a/src/utils/import-html/restore-block-prop-types.ts +++ b/src/utils/import-html/restore-block-prop-types.ts @@ -64,7 +64,11 @@ function schemaAllowsNull(schema: SchemaNode | undefined): boolean { return Array.isArray(schema?.enum) && schema!.enum.includes(null); } -export function restoreBlockPropTypes(blocks: ChaiBlock[]): ChaiBlock[] { +export function restoreBlockPropTypes( + blocks: ChaiBlock[], + options: { htmlBooleanEmpty?: boolean } = {}, +): ChaiBlock[] { + const htmlBooleanEmpty = options.htmlBooleanEmpty ?? true; return blocks.map((block) => { const registered = getRegisteredChaiBlock(block._type) as | { props?: { schema?: SchemaNode }; schema?: SchemaNode } @@ -79,7 +83,12 @@ export function restoreBlockPropTypes(blocks: ChaiBlock[]): ChaiBlock[] { for (const [key, propSchema] of Object.entries(properties)) { const value = block[key]; if (typeof value !== "string") continue; - const restored = coerceToSchemaType(coercibleType(propSchema), value, schemaAllowsNull(propSchema)); + const restored = coerceToSchemaType( + coercibleType(propSchema), + value, + schemaAllowsNull(propSchema), + htmlBooleanEmpty, + ); if (restored === value) continue; next = next ?? { ...block }; next[key] = restored; @@ -89,7 +98,12 @@ export function restoreBlockPropTypes(blocks: ChaiBlock[]): ChaiBlock[] { } /** Parse a stringified value back to `type`; anything ambiguous is returned unchanged. */ -export function coerceToSchemaType(type: string | undefined, value: string, nullable = false): unknown { +export function coerceToSchemaType( + type: string | undefined, + value: string, + nullable = false, + htmlBooleanEmpty = true, +): unknown { // Restore JSON null only when the schema actually admits null (a `null` type, // a type union including null, or an enum including null). A stray "null" on a // non-nullable prop stays a string rather than silently flipping behavior. @@ -100,8 +114,8 @@ export function coerceToSchemaType(type: string | undefined, value: string, null // (e.g. `{"href":"{{page.url}}"}`) still parses back to its typed value. if (type === "boolean") { // A valueless HTML boolean attribute (`required`, `multiple`) is imported as - // "" (getSanitizedValue(null) -> ""); treat that as true. - return value === "true" || value === "" ? true : value === "false" ? false : value; + // "" (getSanitizedValue(null) -> ""); treat that as true only for HTML input. + return value === "true" || (htmlBooleanEmpty && value === "") ? true : value === "false" ? false : value; } // Accepts exponent notation too — JSON.stringify emits e.g. 1e+21 / 1e-7. if (type === "number") return /^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(value.trim()) ? Number(value) : value; diff --git a/src/utils/page-lang.ts b/src/utils/page-lang.ts new file mode 100644 index 000000000..4554a159d --- /dev/null +++ b/src/utils/page-lang.ts @@ -0,0 +1,56 @@ +import { LANGUAGES } from "~/builder/pages/constants/LANGUAGES"; + +/** + * Language facts about the page an AI or MCP tool is operating on. + * + * A ChaiBuilder site has one fallback language; page rows in that language + * store `lang: ''` and every other language is a separate row pointing at the + * primary page through `primaryPage`. Those language rows have no blocks of + * their own — they share the primary page's block tree, and per-language text + * lives on the same blocks under `-{lang}`-suffixed props (see + * `applyLanguage`). + */ +export type PageLangInfo = { + lang: string; + fallbackLang: string; + /** True when this page row is a language variant, not the primary-language page. */ + isLanguageVariant: boolean; +}; + +type LangSource = { lang?: string | null; fallbackLang?: string | null }; + +export const getPageLangInfo = (page: LangSource): PageLangInfo => { + const fallbackLang = page.fallbackLang || ""; + const lang = page.lang || fallbackLang; + return { + lang, + fallbackLang, + isLanguageVariant: Boolean(lang && fallbackLang) && lang !== fallbackLang, + }; +}; + +/** "French (fr)" when the code is known, otherwise the bare code. @internal */ +export const langLabel = (code: string): string => { + if (!code) return "unknown"; + const name = LANGUAGES[code] ?? LANGUAGES[code.split("-")[0]]; + return name ? `${name} (${code})` : code; +}; + +const VARIANT_NOTE = + "This page is a language variant: it shares one block tree with the primary-language page, so layout, structure and styling changes apply to every language. Its text is this language’s translation — the read tools show it and text edits here update only this language’s copy, leaving the primary-language text unchanged."; + +/** Human-readable language note appended to read-tool output. @internal */ +export const describePageLang = (info: PageLangInfo): string => { + if (!info.lang) return ""; + const base = `Content language: ${langLabel(info.lang)}. Write all user-visible copy in this language.`; + if (!info.isLanguageVariant) return base; + return `${base} Site fallback language: ${langLabel(info.fallbackLang)}. ${VARIANT_NOTE}`; +}; + +/** Same facts as JSON fields, for the tools that answer with a JSON payload. */ +export const langResponseFields = (info: PageLangInfo) => ({ + lang: info.lang, + fallbackLang: info.fallbackLang, + isLanguageVariant: info.isLanguageVariant, + languageNote: describePageLang(info), +}); diff --git a/src/utils/page-seo.ts b/src/utils/page-seo.ts new file mode 100644 index 000000000..15f488718 --- /dev/null +++ b/src/utils/page-seo.ts @@ -0,0 +1,315 @@ +import type { PageLangInfo } from "./page-lang"; +import { langLabel } from "./page-lang"; + +/** + * Read/write helpers for the `app_pages.seo` jsonb column — shared by Builder AI + * and MCP `get_page_seo` / `update_page_seo` tools. + */ + +export type SeoPatch = { + title?: string; + description?: string; + canonicalUrl?: string; + noIndex?: boolean; + noFollow?: boolean; + ogTitle?: string; + ogDescription?: string; + ogImage?: string; + metaOther?: Record<string, string>; + /** null / {} / [] clears the document. */ + jsonLD?: Record<string, unknown> | unknown[] | null; +}; + +export type NormalizedSeo = { + seo: { + title: string; + description: string; + canonicalUrl: string; + noIndex: boolean; + noFollow: boolean; + }; + metaTags: { + ogTitle: string; + ogDescription: string; + ogImage: string; + metaOther: Record<string, string>; + }; + jsonLD: Record<string, unknown> | unknown[] | null; + jsonLDRaw?: string; + metaOtherRaw?: string; +}; + +type ParseResult = { ok: true; patch: SeoPatch } | { ok: false; message: string }; + +export const SEO_PATCH_KEYS = [ + "title", + "description", + "canonicalUrl", + "noIndex", + "noFollow", + "ogTitle", + "ogDescription", + "ogImage", + "metaOther", + "jsonLD", +] as const; + +const TEXT_KEYS = ["title", "description", "canonicalUrl", "ogTitle", "ogDescription", "ogImage"] as const; +const BOOLEAN_KEYS = ["noIndex", "noFollow"] as const; +const URL_KEYS = ["canonicalUrl", "ogImage"] as const; + +const MAX_TEXT_LEN = 2000; +const MAX_META_OTHER_ENTRIES = 50; +const MAX_JSONLD_CHARS = 50_000; +const EMPTY_JSON_OBJECT = "{}"; + +export const isPlainRecord = (value: unknown): value is Record<string, unknown> => + typeof value === "object" && value !== null && !Array.isArray(value); + +const asString = (value: unknown): string => (value === null || value === undefined ? "" : String(value)); +const isEmptyJsonString = (value: string): boolean => ["", "{}", "[]"].includes(value.trim()); + +const stringPairsOnly = (source: Record<string, unknown>): Record<string, string> => { + const pairs: Record<string, string> = {}; + for (const [key, value] of Object.entries(source)) { + if (typeof value === "string") pairs[key] = value; + } + return pairs; +}; + +const parseMetaOtherString = (value: string): { pairs: Record<string, string>; raw?: string } => { + if (isEmptyJsonString(value)) return { pairs: {} }; + try { + const parsed = JSON.parse(value); + if (!isPlainRecord(parsed)) return { pairs: {}, raw: value }; + return { pairs: stringPairsOnly(parsed) }; + } catch { + return { pairs: {}, raw: value }; + } +}; + +const isEmptyDocument = (value: Record<string, unknown> | unknown[]): boolean => + Array.isArray(value) ? value.length === 0 : Object.keys(value).length === 0; + +export const normalizeStoredSeo = (raw: unknown): NormalizedSeo => { + const source = isPlainRecord(raw) ? raw : {}; + const canonicalUrl = asString(source.canonicalUrl) || asString(source.cononicalUrl); + + let metaOther: Record<string, string> = {}; + let metaOtherRaw: string | undefined; + if (isPlainRecord(source.metaOther)) { + metaOther = stringPairsOnly(source.metaOther); + } else if (typeof source.metaOther === "string") { + const parsed = parseMetaOtherString(source.metaOther); + metaOther = parsed.pairs; + metaOtherRaw = parsed.raw; + } + + let jsonLD: Record<string, unknown> | unknown[] | null = null; + let jsonLDRaw: string | undefined; + const storedJsonLd = source.jsonLD; + if (isPlainRecord(storedJsonLd) || Array.isArray(storedJsonLd)) { + jsonLD = isEmptyDocument(storedJsonLd) ? null : storedJsonLd; + } else if (typeof storedJsonLd === "string") { + if (!isEmptyJsonString(storedJsonLd)) { + try { + const parsed = JSON.parse(storedJsonLd); + if (isPlainRecord(parsed) || Array.isArray(parsed)) { + jsonLD = isEmptyDocument(parsed) ? null : parsed; + } else { + jsonLDRaw = storedJsonLd; + } + } catch { + jsonLDRaw = storedJsonLd; + } + } + } + + return { + seo: { + title: asString(source.title), + description: asString(source.description), + canonicalUrl, + noIndex: Boolean(source.noIndex), + noFollow: Boolean(source.noFollow), + }, + metaTags: { + ogTitle: asString(source.ogTitle), + ogDescription: asString(source.ogDescription), + ogImage: asString(source.ogImage), + metaOther, + }, + jsonLD, + ...(jsonLDRaw !== undefined ? { jsonLDRaw } : {}), + ...(metaOtherRaw !== undefined ? { metaOtherRaw } : {}), + }; +}; + +const isAcceptableUrlValue = (value: string): boolean => { + const trimmed = value.trim(); + if (trimmed === "") return true; + if (trimmed.startsWith("/")) { + if (/^\/[/\\]/.test(trimmed)) return false; + return true; + } + if (trimmed.startsWith("{{")) return true; + if (/^https?:\/\//i.test(trimmed)) return true; + return false; +}; + +const parseMetaOtherArg = ( + value: unknown, +): { ok: true; pairs: Record<string, string> } | { ok: false; message: string } => { + if (!isPlainRecord(value)) { + return { ok: false, message: "Error: metaOther must be an object of meta name/content string pairs." }; + } + const entries = Object.entries(value); + if (entries.length > MAX_META_OTHER_ENTRIES) { + return { ok: false, message: `Error: metaOther accepts at most ${MAX_META_OTHER_ENTRIES} entries.` }; + } + const pairs: Record<string, string> = {}; + for (const [key, entryValue] of entries) { + if (key.trim() === "") return { ok: false, message: "Error: metaOther keys cannot be empty." }; + if (typeof entryValue !== "string") { + return { ok: false, message: `Error: metaOther["${key}"] must be a string.` }; + } + if (entryValue.length > MAX_TEXT_LEN) { + return { ok: false, message: `Error: metaOther["${key}"] must be at most ${MAX_TEXT_LEN} characters.` }; + } + pairs[key] = entryValue; + } + return { ok: true, pairs }; +}; + +const parseJsonLdArg = ( + value: unknown, +): { ok: true; value: Record<string, unknown> | unknown[] | null } | { ok: false; message: string } => { + if (value === null) return { ok: true, value: null }; + + let document: unknown = value; + if (typeof value === "string") { + if (isEmptyJsonString(value)) return { ok: true, value: null }; + try { + document = JSON.parse(value); + } catch { + return { ok: false, message: "Error: jsonLD is not valid JSON." }; + } + } + + if (!isPlainRecord(document) && !Array.isArray(document)) { + return { + ok: false, + message: "Error: jsonLD must be a JSON-LD object or an array of them, not a primitive value.", + }; + } + + if (isEmptyDocument(document)) return { ok: true, value: null }; + + const serialized = JSON.stringify(document); + if (serialized.length > MAX_JSONLD_CHARS) { + return { ok: false, message: `Error: jsonLD must serialize to at most ${MAX_JSONLD_CHARS} characters.` }; + } + + return { ok: true, value: document }; +}; + +export const parseSeoPatch = (args: Record<string, unknown>): ParseResult => { + const patch: SeoPatch = {}; + + for (const key of TEXT_KEYS) { + const value = args[key]; + if (value === undefined) continue; + if (typeof value !== "string") return { ok: false, message: `Error: ${key} must be a string.` }; + if (value.length > MAX_TEXT_LEN) { + return { ok: false, message: `Error: ${key} must be at most ${MAX_TEXT_LEN} characters.` }; + } + patch[key] = value; + } + + for (const key of URL_KEYS) { + const value = patch[key]; + if (value === undefined) continue; + if (!isAcceptableUrlValue(value)) { + return { + ok: false, + message: `Error: ${key} must be an absolute http(s) URL, an absolute path starting with /, or a {{binding}} expression.`, + }; + } + } + + for (const key of BOOLEAN_KEYS) { + const value = args[key]; + if (value === undefined) continue; + if (typeof value !== "boolean") return { ok: false, message: `Error: ${key} must be true or false.` }; + patch[key] = value; + } + + if (args.metaOther !== undefined) { + const parsed = parseMetaOtherArg(args.metaOther); + if (!parsed.ok) return parsed; + patch.metaOther = parsed.pairs; + } + + if (args.jsonLD !== undefined) { + const parsed = parseJsonLdArg(args.jsonLD); + if (!parsed.ok) return parsed; + patch.jsonLD = parsed.value; + } + + if (Object.keys(patch).length === 0) { + return { + ok: false, + message: `Error: Provide at least one SEO field to update (${SEO_PATCH_KEYS.join(", ")}).`, + }; + } + + return { ok: true, patch }; +}; + +export const mergeSeoUpdate = ( + current: Record<string, unknown>, + patch: SeoPatch, +): { seo: Record<string, unknown>; changedKeys: string[] } => { + const seo: Record<string, unknown> = { ...current }; + const changedKeys: string[] = []; + + for (const key of SEO_PATCH_KEYS) { + if (!(key in patch)) continue; + changedKeys.push(key); + + if (key === "jsonLD") { + seo.jsonLD = + patch.jsonLD === null || patch.jsonLD === undefined ? EMPTY_JSON_OBJECT : JSON.stringify(patch.jsonLD); + continue; + } + if (key === "metaOther") { + const pairs = patch.metaOther ?? {}; + seo.metaOther = Object.keys(pairs).length === 0 ? EMPTY_JSON_OBJECT : JSON.stringify(pairs); + continue; + } + if (key === "canonicalUrl") { + seo.canonicalUrl = patch.canonicalUrl; + delete seo.cononicalUrl; + continue; + } + seo[key] = patch[key]; + } + + if ( + patch.ogImage !== undefined && + patch.ogImage !== asString(current.ogImage) && + asString(current.ogImageId) !== "" + ) { + seo.ogImageId = ""; + changedKeys.push("ogImageId"); + } + + return { seo, changedKeys }; +}; + +export const describeSeoPageLang = (info: PageLangInfo): string => { + if (!info.lang) return ""; + const base = `Content language: ${langLabel(info.lang)}. Write all SEO text in this language.`; + if (!info.isLanguageVariant) return base; + return `${base} SEO is stored per language page: changes here apply only to the ${langLabel(info.lang)} row, and the primary-language page and other variants keep their own SEO. When this variant has no JSON-LD of its own it inherits the primary page's document at render time.`; +}; diff --git a/src/utils/page-translations.ts b/src/utils/page-translations.ts new file mode 100644 index 000000000..0fa2307f3 --- /dev/null +++ b/src/utils/page-translations.ts @@ -0,0 +1,405 @@ +import { isEqual } from "lodash-es"; +import { getRegisteredChaiBlock } from "~/registry"; +import { sanitizeAiPropValue } from "~/server/chai-actions/ai/ask-ai/ai-edit-executors"; +import type { ChaiBlock } from "~/types/common"; +import { langLabel } from "./page-lang"; + +/** + * Per-language block content and binding-preservation helpers shared by + * Builder AI and MCP tools. + * + * ChaiBuilder keeps every language's copy on the primary page's blocks: the + * bare prop (`content`) holds the site fallback language and `content-{lang}` + * holds each translation. Only the props a block type lists in `i18nProps` are + * translatable, and the renderer (`applyLanguage`) shows the translation when + * it is non-blank, otherwise the bare prop. + */ + +/** Fresh, non-global matcher: `.test`/`.match` on a shared global regex is stateful. */ +const BINDING_PATTERN = /\{\{(.*?)\}\}/g; + +/** All `{{...}}` substrings in `text`, in order, duplicates kept. */ +export function extractBindings(text: string): string[] { + return text.match(new RegExp(BINDING_PATTERN)) ?? []; +} + +/** + * True when `output` holds exactly the same multiset of bindings as `inputBindings`. + * Position may differ — a translation reorders words — but nothing may be added, + * dropped, duplicated or altered. + */ +export function bindingsMatch(inputBindings: string[], output: string): boolean { + const outputBindings = extractBindings(output); + if (inputBindings.length !== outputBindings.length) return false; + + const remaining = new Map<string, number>(); + for (const binding of inputBindings) { + remaining.set(binding, (remaining.get(binding) ?? 0) + 1); + } + for (const binding of outputBindings) { + const count = remaining.get(binding); + if (!count) return false; + remaining.set(binding, count - 1); + } + return true; +} + +type AnyBlock = Record<string, unknown>; + +export type I18nPropsOf = (type: string) => string[]; + +export const registryI18nProps: I18nPropsOf = (type) => { + const props = getRegisteredChaiBlock(type)?.i18nProps; + return Array.isArray(props) ? props : []; +}; + +/** Reference blocks carry no content of their own. */ +const REFERENCE_TYPES = new Set(["PartialBlock", "GlobalBlock"]); + +/** + * Translatable props that hold a per-language asset or destination rather than + * copy. A language only overrides them on purpose (a localized image or link), + * so they are never reported as needing translation. + */ +const ASSET_PROPS = new Set(["image", "_imageId", "mobileImage", "_mobileImageId", "url", "customUrl", "link"]); + +export const translationKind = (prop: string): "text" | "asset" => (ASSET_PROPS.has(prop) ? "asset" : "text"); + +export const translatedKey = (prop: string, lang: string) => `${prop}-${lang}`; + +export const isBlankValue = (value: unknown): boolean => { + if (value == null) return true; + if (typeof value === "string") return value.trim().length === 0; + if (typeof value === "number" || typeof value === "boolean") return false; + if (Array.isArray(value)) return value.length === 0; + if (typeof value === "object") return Object.keys(value).length === 0; + return false; +}; + +const translatableProps = (block: AnyBlock, i18nPropsOf: I18nPropsOf) => { + const type = block._type; + if (typeof type !== "string" || REFERENCE_TYPES.has(type)) return []; + return i18nPropsOf(type).filter((prop) => typeof prop === "string" && prop); +}; + +/** The value a block renders for `prop` in `lang` — same rule as applyLanguage. */ +export const resolveLangValue = (block: AnyBlock, prop: string, lang: string): unknown => { + const base = block[prop]; + const translated = block[translatedKey(prop, lang)]; + return isBlankValue(translated) ? base : translated; +}; + +/** + * Swap each translatable bare prop for the value `lang` renders, so AI-HTML and + * the outline show that language's copy. Blocks without a bare prop are left + * alone: applyLanguage ignores their suffixed props too. + */ +export const toLanguageView = ( + blocks: ChaiBlock[], + lang: string, + i18nPropsOf: I18nPropsOf = registryI18nProps, +): ChaiBlock[] => + blocks.map((block) => { + const record = block as unknown as AnyBlock; + let next: AnyBlock | null = null; + for (const prop of translatableProps(record, i18nPropsOf)) { + if (!Object.prototype.hasOwnProperty.call(record, prop)) continue; + const value = resolveLangValue(record, prop, lang); + if (value === record[prop]) continue; + next ??= { ...record }; + next[prop] = value; + } + return (next ?? record) as unknown as ChaiBlock; + }); + +export type LanguageViewResult = { + blocks: ChaiBlock[]; + /** + * Blocks whose translatable copy had no fallback-language value to keep, so + * the text written in `lang` also became their fallback-language copy. + */ + seededFallbackBlockIds: string[]; +}; + +/** + * Map an edited language view back to stored blocks. A translatable prop the + * edit changed is written to `prop-{lang}` and the stored fallback value is + * restored; an unchanged one keeps its stored values untouched, so reading a + * page in a language never invents a translation. A brand-new block (or a prop + * the block did not have) has no fallback copy to protect, so the text becomes + * both its fallback value and its `lang` translation. + */ +export const fromLanguageView = ( + originalBlocks: ChaiBlock[], + nextViewBlocks: ChaiBlock[], + lang: string, + i18nPropsOf: I18nPropsOf = registryI18nProps, +): LanguageViewResult => { + const originalById = new Map(originalBlocks.map((block) => [block._id, block as unknown as AnyBlock])); + const seeded = new Set<string>(); + + const blocks = nextViewBlocks.map((block) => { + const record = { ...(block as unknown as AnyBlock) }; + const original = originalById.get(block._id); + const sameType = original && original._type === record._type; + + for (const prop of translatableProps(record, i18nPropsOf)) { + if (!Object.prototype.hasOwnProperty.call(record, prop)) continue; + const value = record[prop]; + const key = translatedKey(prop, lang); + + if (sameType && Object.prototype.hasOwnProperty.call(original, prop)) { + if (isEqual(value, resolveLangValue(original, prop, lang))) { + record[prop] = original[prop]; + if (Object.prototype.hasOwnProperty.call(original, key)) { + record[key] = original[key]; + } else { + delete record[key]; + } + continue; + } + if (!isBlankValue(original[prop])) { + record[prop] = original[prop]; + if (isBlankValue(value)) delete record[key]; + else record[key] = value; + continue; + } + } + + if (isBlankValue(value)) { + delete record[key]; + continue; + } + record[key] = value; + seeded.add(block._id); + } + return record as unknown as ChaiBlock; + }); + + return { blocks, seededFallbackBlockIds: [...seeded] }; +}; + +export type TranslationEntry = { + blockId: string; + blockType: string; + blockName?: string; + prop: string; + /** `asset` props (images, links, video URLs) are overridden per language only on purpose. */ + kind: "text" | "asset"; + /** Fallback-language value — the source to translate from. */ + source: unknown; + /** Current `prop-{lang}` value, or null when the language renders the source. */ + translation: unknown; +}; + +/** Every translatable prop with a non-blank source, in stored (document) order. */ +export const collectTranslations = ( + blocks: ChaiBlock[], + lang: string, + options: { blockIds?: string[]; missingOnly?: boolean } = {}, + i18nPropsOf: I18nPropsOf = registryI18nProps, +): TranslationEntry[] => { + const wanted = options.blockIds && options.blockIds.length > 0 ? new Set(options.blockIds) : null; + const entries: TranslationEntry[] = []; + for (const block of blocks) { + if (wanted && !wanted.has(block._id)) continue; + const record = block as unknown as AnyBlock; + for (const prop of translatableProps(record, i18nPropsOf)) { + const source = record[prop]; + const translation = record[translatedKey(prop, lang)]; + if (isBlankValue(source) && isBlankValue(translation)) continue; + const kind = translationKind(prop); + if (options.missingOnly) { + if (kind === "asset" || !isBlankValue(translation)) continue; + } + entries.push({ + blockId: block._id, + blockType: String(record._type), + ...(block._name ? { blockName: block._name } : {}), + prop, + kind, + source, + translation: isBlankValue(translation) ? null : translation, + }); + } + } + return entries; +}; + +const isRemoval = (value: unknown) => value == null || (typeof value === "string" && value.trim() === ""); + +const valueKind = (value: unknown): "string" | "array" | "object" | "other" => + typeof value === "string" + ? "string" + : Array.isArray(value) + ? "array" + : value && typeof value === "object" + ? "object" + : "other"; + +const serializeForBindings = (value: unknown): string => + typeof value === "string" ? value : (JSON.stringify(value) ?? ""); + +export type TranslationUpdate = { + blockId: string; + prop: string; + /** New translation; null or a blank value removes it (the source renders). */ + value: unknown; +}; + +/** + * Write `prop-{lang}` values onto the stored blocks. Every update is validated + * before anything changes, so one bad entry rejects the whole batch. + */ +export const applyTranslations = ( + blocks: ChaiBlock[], + lang: string, + updates: TranslationUpdate[], + i18nPropsOf: I18nPropsOf = registryI18nProps, +): { blocks: ChaiBlock[] } | { error: string } => { + const byId = new Map(blocks.map((block) => [block._id, block])); + const errors: string[] = []; + for (const update of updates) { + const block = byId.get(update.blockId) as unknown as AnyBlock | undefined; + if (!block) { + errors.push(`No block with bid "${update.blockId}"`); + continue; + } + const props = translatableProps(block, i18nPropsOf); + if (!props.includes(update.prop)) { + errors.push( + `"${update.prop}" is not translatable on ${String(block._type)} block "${update.blockId}"` + + (props.length ? ` (translatable: ${props.join(", ")})` : ""), + ); + continue; + } + if (!Object.prototype.hasOwnProperty.call(block, update.prop)) { + errors.push( + `Block "${update.blockId}" has no fallback-language "${update.prop}", so a translation would never render. Set its content with edit_block first.`, + ); + continue; + } + if (isRemoval(update.value)) continue; + const source = block[update.prop]; + const sourceKind = valueKind(source); + const updateKind = valueKind(update.value); + if (!isBlankValue(source) && sourceKind !== updateKind) { + errors.push( + `Translation for "${update.prop}" on block "${update.blockId}" must have the same shape as the source (${sourceKind}, got ${updateKind})`, + ); + continue; + } + const sourceBindings = extractBindings(serializeForBindings(source)); + if (!bindingsMatch(sourceBindings, serializeForBindings(update.value))) { + errors.push( + `Translation for "${update.prop}" on block "${update.blockId}" must keep the source's {{bindings}} exactly: ${JSON.stringify(sourceBindings)}`, + ); + } + } + if (errors.length > 0) return { error: errors.join("; ") }; + + const updatesById = new Map<string, TranslationUpdate[]>(); + for (const update of updates) { + const list = updatesById.get(update.blockId) ?? []; + list.push(update); + updatesById.set(update.blockId, list); + } + + return { + blocks: blocks.map((block) => { + const list = updatesById.get(block._id); + if (!list) return block; + const record = { ...(block as unknown as AnyBlock) }; + for (const { prop, value } of list) { + const key = translatedKey(prop, lang); + if (isRemoval(value)) delete record[key]; + else record[key] = sanitizeAiPropValue(value); + } + return record as unknown as ChaiBlock; + }), + }; +}; + +export type ChangedSourceProp = { + blockId: string; + blockType: string; + prop: string; + /** New fallback-language value; blank when the edit cleared it. */ + source: unknown; + /** Translations stored per language before the edit (null when missing). */ + previousTranslations: Record<string, unknown>; +}; + +/** + * Fallback-language copy an edit changed or added, for the languages given. + * These are the translations that are now stale or missing. + */ +export const findChangedSourceProps = ( + before: ChaiBlock[], + after: ChaiBlock[], + langs: string[], + i18nPropsOf: I18nPropsOf = registryI18nProps, +): ChangedSourceProp[] => { + if (langs.length === 0) return []; + const beforeById = new Map(before.map((block) => [block._id, block as unknown as AnyBlock])); + const changes: ChangedSourceProp[] = []; + for (const block of after) { + const record = block as unknown as AnyBlock; + const previous = beforeById.get(block._id); + for (const prop of translatableProps(record, i18nPropsOf)) { + if (translationKind(prop) === "asset") continue; + const source = record[prop]; + const samePrevious = previous && previous._type === record._type; + if (samePrevious && isEqual(previous[prop], source)) continue; + const previousTranslations: Record<string, unknown> = {}; + for (const lang of langs) { + const value = record[translatedKey(prop, lang)]; + previousTranslations[lang] = isBlankValue(value) ? null : value; + } + if ( + isBlankValue(source) && + (!samePrevious || isBlankValue(previous[prop])) && + Object.values(previousTranslations).every((value) => value === null) + ) { + continue; + } + changes.push({ + blockId: block._id, + blockType: String(record._type), + prop, + source, + previousTranslations, + }); + } + } + return changes; +}; + +const MAX_SYNC_ENTRIES = 60; + +/** Instructions telling the model which translations an edit left stale. @internal */ +export const describeTranslationSync = (changes: ChangedSourceProp[], langs: string[]): string => { + if (changes.length === 0 || langs.length === 0) return ""; + const listed = changes.slice(0, MAX_SYNC_ENTRIES).map((change) => ({ + blockId: change.blockId, + blockType: change.blockType, + prop: change.prop, + source: change.source, + previousTranslations: change.previousTranslations, + })); + const rest = changes.slice(MAX_SYNC_ENTRIES); + const restNote = rest.length + ? `\n${rest.length} more changed values are not listed; read them with get_block_translations for blockIds ${JSON.stringify([...new Set(rest.map((c) => c.blockId))])}.` + : ""; + return `\n- 🌐 Translations to sync: this page has language variants (${langs.map(langLabel).join(", ")}), and this edit changed ${changes.length} translatable value(s) in the fallback language. Those languages now show outdated or fallback copy. Before reporting back, call update_block_translations once per language with each source below translated into that language, keeping {{bindings}}, URLs and HTML markup intact. Where a source is empty (the copy was cleared), send value null to remove that language's translation:\n\`\`\`json\n${JSON.stringify(listed, null, 2)}\n\`\`\`${restNote}`; +}; + +/** Note explaining that new copy on a language variant was also seeded as fallback-language copy. */ +export const describeSeededFallbackCopy = ( + seededFallbackBlockIds: string[], + lang: string, + fallbackLang: string, +): string => { + if (seededFallbackBlockIds.length === 0) return ""; + return `New copy on blocks ${seededFallbackBlockIds.join(", ")} had no ${langLabel(fallbackLang)} text, so the same ${langLabel(lang)} text was also stored as their fallback-language copy. Tell the user the primary-language page shows it untranslated until it is edited there.`; +}; diff --git a/src/utils/page-type-helpers.ts b/src/utils/page-type-helpers.ts new file mode 100644 index 000000000..7a53f3d84 --- /dev/null +++ b/src/utils/page-type-helpers.ts @@ -0,0 +1,64 @@ +/** + * Page-type resolution helpers shared by Builder AI and MCP tools. + */ + +/** The one partial type agents create: the builder's built-in global block. */ +export const GLOBAL_PARTIAL_PAGE_TYPE = "global"; + +const PARTIAL_ALIASES = new Set([ + "partial", + "partials", + "partial-block", + "partial_block", + "partialblock", + "global-block", + "global_block", + "globalblock", + "global block", + "partial block", +]); + +export type PageTypeCandidate = { + key: string; + hasSlug?: boolean; + partial?: boolean; +}; + +export type PageTypeResolution = { ok: true; key: string; isPartial: boolean } | { ok: false; message: string }; + +const isPartialType = (type: PageTypeCandidate) => type.partial === true || type.hasSlug === false; + +/** Whether a stored page's type is a partial (global block, layout, form…). */ +export function isPartialPageTypeKey(key: string | null | undefined, pageTypes: PageTypeCandidate[]): boolean { + if (!key) return false; + if (key === GLOBAL_PARTIAL_PAGE_TYPE) return true; + const match = pageTypes.find((type) => type.key === key); + return match ? isPartialType(match) : false; +} + +export function resolveCreatePageType( + requested: string | undefined, + pageTypes: PageTypeCandidate[], +): PageTypeResolution { + const raw = requested?.trim() ?? ""; + if (!raw) return { ok: true, key: "page", isPartial: false }; + + const normalized = raw.toLowerCase(); + const key = PARTIAL_ALIASES.has(normalized) ? GLOBAL_PARTIAL_PAGE_TYPE : normalized; + + const creatable = pageTypes.filter((type) => !isPartialType(type) || type.key === GLOBAL_PARTIAL_PAGE_TYPE); + const match = creatable.find((type) => type.key.toLowerCase() === key); + if (match) { + return { ok: true, key: match.key, isPartial: isPartialType(match) }; + } + + const valid = creatable.map((type) => `"${type.key}"`).join(", "); + const isOtherPartial = pageTypes.some((type) => type.key.toLowerCase() === key && isPartialType(type)); + const hint = isOtherPartial + ? ` Partials (header, footer, navigation and other reusable sections) are always created as pageType "${GLOBAL_PARTIAL_PAGE_TYPE}".` + : ` For a partial (header, footer, navigation or another reusable section) use pageType "${GLOBAL_PARTIAL_PAGE_TYPE}".`; + return { + ok: false, + message: `Error: pageType "${raw}" cannot be created. Valid page types: ${valid}.${hint}`, + }; +} diff --git a/src/web-blocks/helper.test.ts b/src/web-blocks/helper.test.ts index cfd99b999..1b2ac7d7a 100644 --- a/src/web-blocks/helper.test.ts +++ b/src/web-blocks/helper.test.ts @@ -1,4 +1,4 @@ -import { getAriaLabel } from "./helper"; +import { addForcedClasses, getAriaLabel, mergeChaiStyles } from "./helper"; describe("getAriaLabel", () => { it("returns the trimmed author-set label", () => { @@ -22,3 +22,103 @@ describe("getAriaLabel", () => { expect(getAriaLabel({ "aria-label": {} })).toBeUndefined(); }); }); + +describe("addForcedClasses", () => { + it("preserves custom HTML attributes while merging classes", () => { + const result = addForcedClasses( + { + id: "hero-input", + "data-track": "search-input", + "aria-label": "Search homes", + className: "px-4 text-sm", + }, + "focus-visible:outline-none", + ); + + expect(result).toEqual({ + id: "hero-input", + "data-track": "search-input", + "aria-label": "Search homes", + className: "px-4 text-sm focus-visible:outline-none", + }); + }); + + it("handles undefined styles safely", () => { + expect(addForcedClasses(undefined, "flex", "items-center")).toEqual({ + className: "flex items-center", + }); + expect(addForcedClasses(undefined)).toEqual({}); + }); + + it("accepts conditional ClassValue inputs and resolves Tailwind conflicts", () => { + const isActive = true; + const isHidden = false; + const result = addForcedClasses( + { className: "px-2 text-muted-foreground", "data-slot": "tab" }, + isActive && "px-4 text-foreground", + isHidden && "hidden", + undefined, + null, + ); + + expect(result).toEqual({ + "data-slot": "tab", + className: "px-4 text-foreground", + }); + }); + + it("omits className when the merged class string is empty", () => { + const result = addForcedClasses({ className: "", "data-id": "empty" }, "", false, undefined); + expect(result).toEqual({ "data-id": "empty" }); + expect("className" in result).toBe(false); + }); + + it("does not mutate the input styles object", () => { + const original = { className: "p-2", "data-k": "v" }; + const result = addForcedClasses(original, "p-4"); + expect(original).toEqual({ className: "p-2", "data-k": "v" }); + expect(result).toEqual({ className: "p-4", "data-k": "v" }); + }); +}); + +describe("mergeChaiStyles", () => { + it("merges custom HTML attributes with the first style winning, and Tailwind classes with later precedence", () => { + const base = { + id: "tab-1", + "data-role": "tab", + "data-state": "inactive", + className: "px-3 text-muted-foreground", + }; + const active = { + "data-state": "active", + "aria-current": "page", + className: "text-foreground font-semibold", + }; + + expect(mergeChaiStyles(base, active)).toEqual({ + id: "tab-1", + "data-role": "tab", + "data-state": "inactive", + "aria-current": "page", + className: "px-3 text-foreground font-semibold", + }); + }); + + it("skips false, null, and undefined entries", () => { + const base = { "data-tab": "buy", className: "px-3" }; + expect(mergeChaiStyles(base, false, null, undefined)).toEqual({ + "data-tab": "buy", + className: "px-3", + }); + }); + + it("omits className when all merged entries have no classes", () => { + const result = mergeChaiStyles({ id: "a", className: "" }, { "data-x": "1" }); + expect(result).toEqual({ id: "a", "data-x": "1" }); + expect("className" in result).toBe(false); + }); + + it("returns an empty object when called with no truthy styles", () => { + expect(mergeChaiStyles(undefined, false, null)).toEqual({}); + }); +}); diff --git a/src/web-blocks/helper.ts b/src/web-blocks/helper.ts index 4df96b2b2..674b184c3 100644 --- a/src/web-blocks/helper.ts +++ b/src/web-blocks/helper.ts @@ -1,3 +1,4 @@ +import { type ClassValue } from "cnfast"; import { cn } from "~/builder/core/functions/common-functions"; import { ChaiStyles } from "~/types/blocks"; @@ -17,10 +18,36 @@ export const getAriaLabel = (attrs: Record<string, unknown> | undefined | null): return trimmed || undefined; }; -export const addForcedClasses = (styles: ChaiStyles, ...classes: string[]) => { - // get all the classes from the blockStateClasses if the value is true - return { - ...styles, - className: cn(styles.className, ...classes), - }; +export const addForcedClasses = ( + styles: ChaiStyles | undefined, + ...classes: ClassValue[] +): ChaiStyles => { + const className = cn(styles?.className, ...classes); + const next: ChaiStyles = { ...styles }; + if (className) { + next.className = className; + } else { + delete next.className; + } + return next; +}; + +// Classes combine in order; for any other attribute the first style that sets it wins, so the editor still selects the main style. +export const mergeChaiStyles = ( + ...stylesList: Array<ChaiStyles | false | null | undefined> +): ChaiStyles => { + let merged: ChaiStyles = {}; + const classes: ClassValue[] = []; + for (const item of stylesList) { + if (!item) continue; + merged = { ...item, ...merged }; + classes.push(item.className); + } + const className = cn(...classes); + if (className) { + merged.className = className; + } else { + delete merged.className; + } + return merged; };