Beautiful Open-Source Form Builder
fix(mcp): render one final draft preview
Julien Nahumac203326fb58
diff --git a/api/app/Mcp/Apps/FormDraftPreviewApp.php b/api/app/Mcp/Apps/FormDraftPreviewApp.phpindex 348f5539c..80d39f0f4 100644--- a/api/app/Mcp/Apps/FormDraftPreviewApp.php+++ b/api/app/Mcp/Apps/FormDraftPreviewApp.php@@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Ui\Csp;#[Name('form_draft_preview')]#[Description('Interactive preview of a temporary guest OpnForm draft with an optional editor handoff.')]-#[Uri('ui://opnform/form-draft-preview-v5')]+#[Uri('ui://opnform/form-draft-preview-v6')]class FormDraftPreviewApp extends AppResource{public function shouldRegister(McpAvailability $availability): booldiff --git a/api/app/Mcp/Servers/OpnFormServer.php b/api/app/Mcp/Servers/OpnFormServer.phpindex 4afc42bd9..977e58e52 100644--- a/api/app/Mcp/Servers/OpnFormServer.php+++ b/api/app/Mcp/Servers/OpnFormServer.php@@ -33,7 +33,7 @@ use Laravel\Mcp\Server\Attributes\Version;#[Name('OpnForm')]#[Version('1.0.0')]-#[Instructions('Default every request to create a new form to the guest draft workflow unless the user explicitly asks to save it in their connected OpnForm account or a workspace. A natural request such as "create a contact form" needs no login or preview wording: validate, then create_form_draft, which renders the interactive preview. Every patch_form_draft renders the updated preview too. Follow the catalog authoring guidelines: human labels, useful placeholders, appropriate fields/layout, a contextual submit label, and a useful completion message. Correct relevant quality_warnings while preserving intentional choices. For a long answer, use type text with multi_lines true; textarea is not a valid field type. If validation fails, correct and revalidate the definition before creating a draft. Never ask the user to connect when guest draft tools can satisfy the request. OAuth is required only for connected-account operations. Enabling or selecting the plugin is not OAuth authentication. Use preview_form_draft only to re-render an existing draft. After each guest create or patch, briefly summarize the result and ask whether the user wants another change or wants to save the form to their OpnForm account. Never call a temporary guest draft saved. Once an account-owned form is saved as an unpublished draft, say so and ask whether the user wants it published; asking is not confirmation, so publish only after an explicit affirmative response. If an account-scoped tool challenges, ask the user to authenticate the OpnForm MCP server in the host; do not repeatedly retry from the guest workflow. In local Codex, start a new conversation after OAuth so the MCP client loads the stored credential. If guest draft tools are unexpectedly missing, do not substitute an authenticated tool unless the user requested account persistence; ask the user to start a new conversation with OpnForm selected before the first message. Use OpnForm MCP tools directly. Never invoke Codex or ChatGPT recursively, run `codex exec`, use shell or raw HTTP, inspect repositories or caches, or switch connectors. Read the schema and field catalog again before changing presentation, fields, layout, or media, then validate before saving. Focused presentation creates one step per block automatically: use full-width blocks, no page breaks or standalone media blocks, and attach optional media through the block image property. Use only durable public HTTPS asset URLs, never localhost or temporary tunnel URLs.')]+#[Instructions('Treat a natural request to create a form as a guest workflow unless the user explicitly asks for account persistence. No login or preview wording is required. Read the form schema and field catalog, follow their authoring guidance, validate, then create or patch the draft. Create and patch are data-only: after either succeeds, call preview_form_draft exactly once so the turn contains one final interactive preview. Use sanitized HTML, never Markdown, in nf-text content. Every input name is a respondent-facing label in sentence case with spaces; technical identifiers belong only in id and may be omitted. Correct relevant quality_warnings before persistence. OAuth is only for saving or managing account forms, workspaces, or submissions. After a guest preview, briefly ask whether to modify or save. After an account form is saved as an unpublished draft, ask whether to publish and require explicit confirmation. Keep replies concise, use OpnForm MCP tools directly, preserve draft handles privately, and do not bypass validation, revisions, permissions, confirmations, plan rules, or rate limits.')]class OpnFormServer extends Server{public int $maxPaginationLength = 100;diff --git a/api/app/Mcp/Tools/CreateFormDraftTool.php b/api/app/Mcp/Tools/CreateFormDraftTool.phpindex 778f9bb1d..be6bddcbd 100644--- a/api/app/Mcp/Tools/CreateFormDraftTool.php+++ b/api/app/Mcp/Tools/CreateFormDraftTool.php@@ -2,7 +2,6 @@namespace App\Mcp\Tools;-use App\Mcp\Apps\FormDraftPreviewApp;use App\Mcp\Support\McpOutputSchema;use App\Service\Forms\AgentFormDraftRateLimiter;use App\Service\Forms\AgentFormDraftService;@@ -12,7 +11,6 @@ use Laravel\Mcp\Response;use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Attributes\Name;-use Laravel\Mcp\Server\Attributes\RendersApp;use Laravel\Mcp\Server\Attributes\Title;use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;@@ -20,8 +18,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[Name('create_form_draft')]#[Title('Create a Guest Form Draft')]-#[Description('Use this as the default creation tool when the user asks to create or build a new form without explicitly asking to save it in an OpnForm account or workspace. A natural request such as "create a contact form" is sufficient; the user does not need to mention guest mode, login, a draft, or a preview. It works immediately without login and returns a temporary unpublished seven-day draft with its interactive preview; never request authentication or use create_form_in_account for this guest-first workflow.')]-#[RendersApp(resource: FormDraftPreviewApp::class)]+#[Description('Default tool for creating a new form unless the user explicitly asks to save it in an OpnForm account or workspace. Creates a temporary unpublished seven-day guest draft without login. This tool is data-only and never renders a widget. On success, call preview_form_draft exactly once with the returned draft_handle so the user sees one final interactive preview. Do not retry after success. Validation errors are safe to correct and retry; draft creation itself is not idempotent.')]#[IsReadOnly(false)]#[IsDestructive(false)]#[IsOpenWorld(false)]@@ -46,13 +43,6 @@ class CreateFormDraftTool extends GuestDraftMcpToolreturn Response::structured(['draft_handle' => $created['token'],'draft' => $drafts->serialize($created['draft']),- 'preview_url' => $drafts->previewUrl($created['draft']),- 'next_steps' => [- 'Pass draft_handle unchanged to guest draft tools. Do not display this internal handle to the user.',- 'Use patch_form_draft with expected_version for changes.',- 'The interactive preview is included in this result; present it before any text summary.',- 'After the preview, ask whether the user wants another change or wants to save the form to their OpnForm account.',- ],]);}@@ -74,8 +64,6 @@ class CreateFormDraftTool extends GuestDraftMcpTool->max(43)->required(),'draft' => McpOutputSchema::draft($schema)->required(),- 'preview_url' => $schema->string()->format('uri')->required(),- 'next_steps' => $schema->array()->items($schema->string())->required(),];}}diff --git a/api/app/Mcp/Tools/PatchFormDraftTool.php b/api/app/Mcp/Tools/PatchFormDraftTool.phpindex cebb7cd52..3197f2bb9 100644--- a/api/app/Mcp/Tools/PatchFormDraftTool.php+++ b/api/app/Mcp/Tools/PatchFormDraftTool.php@@ -2,7 +2,6 @@namespace App\Mcp\Tools;-use App\Mcp\Apps\FormDraftPreviewApp;use App\Mcp\Support\McpOutputSchema;use App\Models\Forms\Form;use App\Service\Forms\AgentFormFieldCatalog;@@ -13,14 +12,12 @@ use Laravel\Mcp\Response;use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Attributes\Name;-use Laravel\Mcp\Server\Attributes\RendersApp;use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[Name('patch_form_draft')]-#[Description('Use this when the user asks to change the current guest form draft. Apply validated semantic operations and return the updated interactive preview automatically. Requires expected_version, so concurrent agent or editor changes cannot be silently overwritten. Supported ops: set_form_values, add_block, update_block, remove_block, move_block. Before changing presentation_style, fields, layout, or media, read opnform://reference/form-fields/v1. Style values are strict: border_radius is none, small, or full; width is centered or full; size is sm, md, or lg; theme is default, simple, notion, minimal, or transparent. Classic mode uses nf-page-break for explicit pagination; focused mode derives one step per block and must not use page breaks.')]-#[RendersApp(resource: FormDraftPreviewApp::class)]+#[Description('Apply semantic operations to the current guest draft. This tool is data-only and never renders a widget. Requires the latest expected_version and rejects conflicts without overwriting newer work. On success, call preview_form_draft exactly once with the returned draft_handle so the user sees one updated preview. Do not retry after success. Correct validation errors and retry with the same current version; after a version conflict, fetch the draft before retrying. Supported ops: set_form_values, add_block, update_block, remove_block, move_block.')]#[IsReadOnly(false)]#[IsDestructive]#[IsOpenWorld(false)]@@ -45,8 +42,6 @@ class PatchFormDraftTool extends GuestDraftMcpToolreturn Response::structured(['draft_handle' => $validated['draft_handle'],'draft' => $drafts->serialize($draft),- 'preview_url' => $drafts->previewUrl($draft),- 'next_step' => 'Present the refreshed interactive preview, briefly summarize the change, then ask whether the user wants another change or wants to save the form to their OpnForm account.',]);}@@ -84,6 +79,7 @@ class PatchFormDraftTool extends GuestDraftMcpTool'block' => $schema->object(['name' => $schema->string()->required(),'type' => $schema->string()->enum(AgentFormFieldCatalog::types())->required(),+ 'content' => $schema->string()->description('For nf-text blocks: sanitized HTML, never Markdown.'),'placeholder' => $schema->string()->nullable(),'help' => $schema->string()->nullable(),'required' => $schema->boolean(),@@ -92,6 +88,7 @@ class PatchFormDraftTool extends GuestDraftMcpTool'patch' => $schema->object(['name' => $schema->string(),'type' => $schema->string()->enum(AgentFormFieldCatalog::types()),+ 'content' => $schema->string()->description('For nf-text blocks: sanitized HTML, never Markdown.'),'placeholder' => $schema->string()->nullable(),'help' => $schema->string()->nullable(),'required' => $schema->boolean(),@@ -112,8 +109,6 @@ class PatchFormDraftTool extends GuestDraftMcpToolreturn ['draft_handle' => $schema->string()->min(43)->max(43)->required(),'draft' => McpOutputSchema::draft($schema)->required(),- 'preview_url' => $schema->string()->format('uri')->required(),- 'next_step' => $schema->string()->required(),];}}diff --git a/api/app/Mcp/Tools/PreviewFormDraftTool.php b/api/app/Mcp/Tools/PreviewFormDraftTool.phpindex c3f55c403..4b156592b 100644--- a/api/app/Mcp/Tools/PreviewFormDraftTool.php+++ b/api/app/Mcp/Tools/PreviewFormDraftTool.php@@ -17,7 +17,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[Name('preview_form_draft')]-#[Description('Use this when an existing guest draft preview needs to be shown or re-rendered without changing the draft. Create_form_draft and patch_form_draft already render their previews automatically. The returned browser preview is valid for one hour. This read-only tool does not create an editor link. Call open_form_draft_in_editor only when the user chooses to continue editing in OpnForm.')]+#[Description('Render the final interactive preview for an existing guest draft without changing it. Call exactly once after a successful create_form_draft or patch_form_draft, and use it again only when the user explicitly asks to refresh an existing preview. The signed preview remains valid until the seven-day draft expires. This tool is read-only, safe to retry after an error, and does not create an editor link.')]#[RendersApp(resource: FormDraftPreviewApp::class)]#[IsReadOnly]#[IsDestructive(false)]diff --git a/api/app/Mcp/Tools/ValidateFormDefinitionTool.php b/api/app/Mcp/Tools/ValidateFormDefinitionTool.phpindex 4eafbe185..8b340c685 100644--- a/api/app/Mcp/Tools/ValidateFormDefinitionTool.php+++ b/api/app/Mcp/Tools/ValidateFormDefinitionTool.php@@ -16,7 +16,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[Name('validate_form_definition')]-#[Description('Normalize and validate an OpnForm agent form definition without storing it. Returns the canonical definition with defaults, stable block IDs, sanitized content, normalized aliases, and non-blocking authoring-quality warnings.')]+#[Description('Normalize and validate an OpnForm agent form definition without storing it. Returns the canonical definition with defaults, stable block IDs, sanitized content, normalized aliases, and authoring-quality warnings. Resolve every warning with blocking=true before create or save; correct other relevant warnings unless they conflict with an intentional user choice.')]#[IsReadOnly]#[IsDestructive(false)]#[IsIdempotent]@@ -62,6 +62,7 @@ class ValidateFormDefinitionTool extends GuestMcpTool'code' => $schema->string()->required(),'message' => $schema->string()->required(),'path' => $schema->string()->required(),+ 'blocking' => $schema->boolean()->required(),]))->required(),];diff --git a/api/app/Providers/RouteServiceProvider.php b/api/app/Providers/RouteServiceProvider.phpindex 46e25f624..2fe61722d 100644--- a/api/app/Providers/RouteServiceProvider.php+++ b/api/app/Providers/RouteServiceProvider.php@@ -2,6 +2,7 @@namespace App\Providers;+use App\Models\Forms\AgentFormDraft;use Illuminate\Cache\RateLimiting\Limit;use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;use Illuminate\Http\Request;@@ -122,6 +123,21 @@ class RouteServiceProvider extends ServiceProviderreturn Limit::perHour(20)->by('mcp-oauth-registration:'.$request->ip());});+ RateLimiter::for('agent-draft-preview', function (Request $request) {+ $routeDraft = $request->route('draft');+ $draftId = (string) ($routeDraft instanceof AgentFormDraft ? $routeDraft->getKey() : $routeDraft);+ $identifier = ctype_digit($draftId)+ ? 'draft:'.$draftId+ : 'invalid:'.$request->ip();++ return [+ Limit::perMinute(max(1, config('opnform.mcp.rate_limit.draft_preview_requests_per_minute', 240)))+ ->by('agent-draft-preview:'.$identifier),+ Limit::perMinute(max(1, config('opnform.mcp.rate_limit.draft_proxy_pool_per_minute', 6000)))+ ->by('agent-draft-preview:proxy:'.$request->ip()),+ ];+ });+RateLimiter::for('agent-draft-handoff', function (Request $request) {$token = (string) $request->input('handoff_token');$identifier = strlen($token) === 43diff --git a/api/app/Service/Forms/AgentFormAuthoringGuide.php b/api/app/Service/Forms/AgentFormAuthoringGuide.phpindex ee98daf9e..ac3232b46 100644--- a/api/app/Service/Forms/AgentFormAuthoringGuide.php+++ b/api/app/Service/Forms/AgentFormAuthoringGuide.php@@ -10,8 +10,8 @@ class AgentFormAuthoringGuide'Keep short forms short. Ask only for information that serves the stated purpose and do not duplicate questions.',],'copy' => [- 'Unless the form is intentionally trivial, begin with a concise nf-text heading and one supporting sentence that explains the form purpose.',- 'Use human-facing labels in sentence case. Use short noun labels for identity fields and direct, unbiased questions for surveys; never expose raw identifiers or snake_case.',+ 'Unless the form is intentionally trivial, begin with a concise nf-text heading and one supporting sentence that explains the form purpose. Its content is sanitized HTML, never Markdown: use <h1>Contact us</h1><p>How can we help?</p>, not # Contact us.',+ 'Use the name property only for respondent-facing labels in sentence case with natural spaces, such as Full name and Email address. Technical identifiers belong in id, which may be omitted; never expose full_name, contact_email, kebab-case, database keys, or variable names.','Use placeholders only for a useful example or expected format. Never use a placeholder instead of a visible label or merely repeat the label.','Use help text only for constraints, unfamiliar information, formatting guidance, or why the information is requested.',],@@ -39,7 +39,7 @@ class AgentFormAuthoringGuidereturn ['objective' => 'Create a polished respondent-facing form, not merely the smallest valid schema.','rules' => self::RULES,- 'validation' => 'Treat quality warnings from validate_form_definition as non-blocking editorial guidance. Correct relevant warnings before creating or saving, while preserving intentional user choices.',+ 'validation' => 'Resolve every quality warning marked blocking before creating or saving. Correct other relevant warnings while preserving intentional user choices.',];}diff --git a/api/app/Service/Forms/AgentFormDefinition.php b/api/app/Service/Forms/AgentFormDefinition.phpindex c1ceadef5..5b7c3f9b7 100644--- a/api/app/Service/Forms/AgentFormDefinition.php+++ b/api/app/Service/Forms/AgentFormDefinition.php@@ -352,9 +352,20 @@ class AgentFormDefinition'required' => ['name', 'type'],'additionalProperties' => true,'properties' => [- 'id' => ['type' => 'string'],- 'name' => ['type' => 'string', 'minLength' => 1],+ 'id' => [+ 'type' => 'string',+ 'description' => 'Stable technical block identifier. Omit it for new blocks so the server generates one. Never reuse it as visible label copy.',+ ],+ 'name' => [+ 'type' => 'string',+ 'minLength' => 1,+ 'description' => 'Respondent-facing label in sentence case with natural spaces, such as Full name or Email address. Never use snake_case, kebab-case, database keys, or variable names.',+ ],'type' => ['type' => 'string', 'enum' => FieldCatalog::types()],+ 'content' => [+ 'type' => 'string',+ 'description' => 'For nf-text blocks only: sanitized HTML fragment, never Markdown. Example: <h1>Contact us</h1><p>How can we help?</p>.',+ ],'help' => ['type' => ['string', 'null']],'hidden' => ['type' => 'boolean', 'default' => false],'required' => ['type' => 'boolean', 'default' => false],diff --git a/api/app/Service/Forms/AgentFormDraftService.php b/api/app/Service/Forms/AgentFormDraftService.phpindex 403649b6c..0152cc84c 100644--- a/api/app/Service/Forms/AgentFormDraftService.php+++ b/api/app/Service/Forms/AgentFormDraftService.php@@ -18,6 +18,7 @@ class AgentFormDraftServicepublic function __construct(private readonly AgentFormDefinition $formDefinition,+ private readonly AgentFormQualityAnalyzer $qualityAnalyzer,private readonly AgentFormDraftPatcher $patcher,private readonly FormCreationService $formCreation,) {@@ -30,6 +31,7 @@ class AgentFormDraftService{$definition['visibility'] = 'draft';$definition = $this->formDefinition->normalizeAndValidate($definition);+ $this->qualityAnalyzer->assertReadyForAgentPersistence($definition);$token = $this->generateToken();$draft = AgentFormDraft::query()->create([@@ -63,6 +65,7 @@ class AgentFormDraftService$definition = $this->patcher->apply($draft->definition, $operations);$definition['visibility'] = 'draft';$definition = $this->formDefinition->normalizeAndValidate($definition);+ $this->qualityAnalyzer->assertReadyForAgentPersistence($definition);$draft->forceFill(['definition' => $definition,diff --git a/api/app/Service/Forms/AgentFormFieldCatalog.php b/api/app/Service/Forms/AgentFormFieldCatalog.phpindex 79833653d..0e10633a3 100644--- a/api/app/Service/Forms/AgentFormFieldCatalog.php+++ b/api/app/Service/Forms/AgentFormFieldCatalog.php@@ -54,8 +54,8 @@ class AgentFormFieldCatalog'layout_types' => self::LAYOUT_TYPES,'aliases' => self::ALIASES,'common_properties' => [- 'id' => 'Stable UUID. It is generated when omitted.',- 'name' => 'Required user-facing block label.',+ 'id' => 'Stable technical identifier. Omit it when creating a block so the server generates one. Never place this value in the visible label.',+ 'name' => 'Required respondent-facing label in sentence case, using natural words and spaces, for example Full name or Email address. Never use snake_case, kebab-case, database keys, or variable names.','type' => 'One canonical type or alias from this catalog.','help' => 'Optional sanitized HTML help text.','hidden' => 'Boolean, defaults to false.',@@ -76,7 +76,9 @@ class AgentFormFieldCatalog'barcode' => ['decoders'],'matrix' => ['rows', 'columns'],'payment' => ['amount', 'currency', 'stripe_account_id'],- 'nf-text' => ['content'],+ 'nf-text' => [+ 'content' => 'Sanitized HTML fragment, never Markdown. Use elements such as <h1>, <h2>, <p>, <strong>, <em>, <a>, <ul>, <ol>, and <li>. Example: <h1>Contact us</h1><p>Send us a message and we will get back to you.</p>.',+ ],'nf-page-break' => ['next_btn_text', 'previous_btn_text'],'nf-image' => ['image_block'],'nf-video' => ['video_block'],diff --git a/api/app/Service/Forms/AgentFormQualityAnalyzer.php b/api/app/Service/Forms/AgentFormQualityAnalyzer.phpindex abf0981be..a0099fd80 100644--- a/api/app/Service/Forms/AgentFormQualityAnalyzer.php+++ b/api/app/Service/Forms/AgentFormQualityAnalyzer.php@@ -3,11 +3,17 @@namespace App\Service\Forms;use Illuminate\Support\Str;+use Illuminate\Validation\ValidationException;class AgentFormQualityAnalyzer{private const MAX_WARNINGS = 50;+ private const BLOCKING_CODES = [+ 'machine_like_label',+ 'markdown_text_content',+ ];+private const RAW_LABELS = ['name','email',@@ -45,6 +51,20 @@ class AgentFormQualityAnalyzer);}+ foreach ($properties as $index => $property) {+ if (($property['type'] ?? null) !== 'nf-text') {+ continue;+ }++ if ($this->looksLikeMarkdown((string) ($property['content'] ?? ''))) {+ $warnings[] = $this->warning(+ 'markdown_text_content',+ 'Replace Markdown with sanitized HTML in nf-text content, for example <h1>Contact us</h1><p>How can we help?</p>.',+ "properties.{$index}.content",+ );+ }+ }+foreach ($inputProperties as $index => $property) {$path = "properties.{$index}";$label = Str::squish(strip_tags((string) ($property['name'] ?? '')));@@ -108,6 +128,23 @@ class AgentFormQualityAnalyzerreturn array_slice($warnings, 0, self::MAX_WARNINGS);}+ public function assertReadyForAgentPersistence(array $definition): void+ {+ $blockingWarnings = collect($this->analyze($definition))+ ->where('blocking', true)+ ->values();++ if ($blockingWarnings->isEmpty()) {+ return;+ }++ throw ValidationException::withMessages([+ 'definition' => $blockingWarnings+ ->map(fn (array $warning): string => "{$warning['path']}: {$warning['message']}")+ ->all(),+ ]);+ }+private function hasVisibleIntroduction(array $properties): bool{foreach ($properties as $property) {@@ -132,6 +169,15 @@ class AgentFormQualityAnalyzerreturn $label === Str::lower($label) && in_array($label, self::RAW_LABELS, true);}+ private function looksLikeMarkdown(string $content): bool+ {+ return preg_match('/(^|\n)\s{0,3}#{1,6}\s+\S/m', $content) === 1+ || preg_match('/\*\*[^*\n]+\*\*/', $content) === 1+ || preg_match('/__[^_\n]+__/', $content) === 1+ || preg_match('/(^|\n)\s*```/m', $content) === 1+ || preg_match('/(?<!!)\[[^\]\n]+\]\([^)\n]+\)/', $content) === 1;+ }+private function wouldBenefitFromPlaceholder(array $property): bool{if (in_array($property['type'] ?? null, ['email', 'phone_number', 'url'], true)) {@@ -177,6 +223,11 @@ class AgentFormQualityAnalyzerprivate function warning(string $code, string $message, string $path): array{- return compact('code', 'message', 'path');+ return [+ 'code' => $code,+ 'message' => $message,+ 'path' => $path,+ 'blocking' => in_array($code, self::BLOCKING_CODES, true),+ ];}}diff --git a/api/app/Service/Forms/McpFormManagementService.php b/api/app/Service/Forms/McpFormManagementService.phpindex 170728dee..6cd5cc2f0 100644--- a/api/app/Service/Forms/McpFormManagementService.php+++ b/api/app/Service/Forms/McpFormManagementService.php@@ -15,6 +15,7 @@ class McpFormManagementService{public function __construct(private readonly AgentFormDefinition $definitions,+ private readonly AgentFormQualityAnalyzer $qualityAnalyzer,private readonly FormCreationService $formCreation,private readonly FormUpdateService $formUpdate,) {@@ -125,6 +126,7 @@ class McpFormManagementService$this->assertWritable($workspace, $user);$definition = $this->definitions->normalizeAndValidate($definition, $workspace);+ $this->qualityAnalyzer->assertReadyForAgentPersistence($definition);$definition['visibility'] = 'draft';$created = $this->formCreation->create($definition, $user, $workspace);diff --git a/api/config/opnform.php b/api/config/opnform.phpindex 29d5fb62f..a91a748c4 100644--- a/api/config/opnform.php+++ b/api/config/opnform.php@@ -25,6 +25,7 @@ return ['per_hour' => (int) env('MCP_RATE_LIMIT_PER_HOUR', 3000),'draft_creates_per_minute' => (int) env('MCP_DRAFT_CREATES_PER_MINUTE', 20),'draft_creates_per_hour' => (int) env('MCP_DRAFT_CREATES_PER_HOUR', 200),+ 'draft_preview_requests_per_minute' => (int) env('MCP_DRAFT_PREVIEW_REQUESTS_PER_MINUTE', 240),'draft_handoffs_per_minute' => (int) env('MCP_DRAFT_HANDOFFS_PER_MINUTE', 120),'draft_editor_requests_per_minute' => (int) env('MCP_DRAFT_EDITOR_REQUESTS_PER_MINUTE', 240),'draft_proxy_pool_per_minute' => (int) env('MCP_DRAFT_PROXY_POOL_PER_MINUTE', 6000),diff --git a/api/resources/views/mcp/form-draft-preview-app.blade.php b/api/resources/views/mcp/form-draft-preview-app.blade.phpindex b542f8a78..5675fd976 100644--- a/api/resources/views/mcp/form-draft-preview-app.blade.php+++ b/api/resources/views/mcp/form-draft-preview-app.blade.php@@ -213,7 +213,7 @@await app.openLink({ url: payload.editor_url });} catch (error) {- actionStatus.textContent = 'Could not open OpnForm. Please try again.';+ actionStatus.textContent = 'Could not open the OpnForm editor. Please try again.';actionStatus.hidden = false;} finally {openButton.textContent = initialOpenButtonText;@@ -242,7 +242,7 @@<button id="zoom-reset" class="zoom-value" type="button" title="Reset zoom">85%</button><button id="zoom-in" class="zoom-button" type="button" title="Zoom in" aria-label="Zoom in">+</button></div>- <button id="open-editor" class="open-button" type="button" disabled>Open in OpnForm</button>+ <button id="open-editor" class="open-button" type="button" aria-label="Continue editing this draft in OpnForm" disabled>Edit in OpnForm</button></div></header><p id="action-status" class="action-status" role="status" aria-live="polite" hidden></p>diff --git a/api/routes/api.php b/api/routes/api.phpindex e3b268e33..48f6a30b0 100644--- a/api/routes/api.php+++ b/api/routes/api.php@@ -58,7 +58,8 @@ if (config('app.self_hosted')) {Route::middleware('mcp.enabled')->group(function () {Route::prefix('agent-drafts')->name('agent-drafts.')->middleware('mcp.guest-drafts')->group(function () {Route::get('/preview/{draft}', [AgentFormDraftController::class, 'preview'])- ->middleware(['signed', 'throttle:60,1'])+ ->withoutMiddleware('throttle:100,1')+ ->middleware(['signed', 'throttle:agent-draft-preview'])->name('preview');Route::post('/handoff/consume', [AgentFormDraftController::class, 'consume'])->withoutMiddleware('throttle:100,1')diff --git a/api/tests/Feature/Mcp/AgentDraftEditorTest.php b/api/tests/Feature/Mcp/AgentDraftEditorTest.phpindex 8ec5c8613..1aa65a10b 100644--- a/api/tests/Feature/Mcp/AgentDraftEditorTest.php+++ b/api/tests/Feature/Mcp/AgentDraftEditorTest.php@@ -43,7 +43,7 @@ it('renders a read-only MCP App preview and creates an editor link only on demanOpnFormServer::resource(\App\Mcp\Apps\FormDraftPreviewApp::class)->assertOk()- ->assertSee('Open in OpnForm')+ ->assertSee('Edit in OpnForm')->assertSee("app.callServerTool('open_form_draft_in_editor'")->assertSee('currentPreviewUrl !== nextPreviewUrl')->assertDontSee('window.openai')@@ -73,7 +73,7 @@ it('publishes standard and ChatGPT-compatible CSP metadata with the full fronten->content()->toResource($previewApp);- expect($previewApp->uri())->toBe('ui://opnform/form-draft-preview-v5')+ expect($previewApp->uri())->toBe('ui://opnform/form-draft-preview-v6')->and($previewApp->resolvedAppMeta()['csp']['resourceDomains'])->toBe(['http://127.0.0.1:33676'])->and($previewApp->resolvedAppMeta()['csp']['frameDomains'])@@ -114,6 +114,22 @@ it('serves preview data only through a valid signed URL without exposing capabil$this->getJson(route('agent-drafts.preview', $draft))->assertForbidden();});+it('rate limits preview requests per draft instead of the shared frontend proxy', function () {+ $this->withMiddleware(ThrottleRequests::class);+ config()->set('opnform.mcp.rate_limit.draft_preview_requests_per_minute', 2);+ config()->set('opnform.mcp.rate_limit.draft_proxy_pool_per_minute', 1000);++ $firstDraft = app(AgentFormDraftService::class)->create(editorDraftDefinition())['draft'];+ $secondDraft = app(AgentFormDraftService::class)->create(editorDraftDefinition())['draft'];+ $firstUrl = URL::temporarySignedRoute('agent-drafts.preview', now()->addMinute(), ['draft' => $firstDraft->id]);+ $secondUrl = URL::temporarySignedRoute('agent-drafts.preview', now()->addMinute(), ['draft' => $secondDraft->id]);++ $this->getJson($firstUrl)->assertOk();+ $this->getJson($firstUrl)->assertOk();+ $this->getJson($firstUrl)->assertTooManyRequests();+ $this->getJson($secondUrl)->assertOk();+});+it('keeps each generated browser preview link valid until the draft expires', function () {$this->freezeTime();$draft = app(AgentFormDraftService::class)->create(editorDraftDefinition())['draft'];diff --git a/api/tests/Feature/Mcp/AgentPluginPackageTest.php b/api/tests/Feature/Mcp/AgentPluginPackageTest.phpindex 141dffa63..e588f0b55 100644--- a/api/tests/Feature/Mcp/AgentPluginPackageTest.php+++ b/api/tests/Feature/Mcp/AgentPluginPackageTest.php@@ -14,6 +14,16 @@ function readOpnformPluginJson(string $path): array);}+function readOpnformSkillBundle(): string+{+ $skillRoot = opnformPluginPath('skills/opnform');+ $references = collect(glob($skillRoot.'/references/*.md'))+ ->map(fn (string $path): string => file_get_contents($path))+ ->implode("\n");++ return file_get_contents($skillRoot.'/SKILL.md')."\n".$references;+}+it('ships portable manifests that conform to the Agent Plugins 1.0 schemas', function () {$plugin = readOpnformPluginJson('plugin.json');$mcp = readOpnformPluginJson('mcp.json');@@ -124,11 +134,12 @@ it('keeps every native manifest path relative to and inside the plugin package',it('ships a discoverable OpnForm skill with the complete safety workflow', function () {$skillPath = opnformPluginPath('skills/opnform/SKILL.md');$skill = file_get_contents($skillPath);+ $bundle = readOpnformSkillBundle();expect($skillPath)->toBeFile()->and($skill)->toStartWith("---\n")->and($skill)->toMatch('/\A---\nname: opnform\ndescription: .+\n---\n/s')- ->and($skill)->toContain(+ ->and($bundle)->toContain('opnform://schemas/agent-form-definition/v1','validate_form_definition','draft_handle',@@ -145,37 +156,31 @@ it('ships a discoverable OpnForm skill with the complete safety workflow', funct'expected_version','revision',)- ->and($skill)->toContain(- 'Authenticated tools remain discoverable before the account is connected',- 'Do not report that account tools are unavailable',- 'Never launch another Codex or ChatGPT agent',- 'run `codex exec`',- 'OpnForm is not attached to the current conversation',+ ->and($bundle)->toContain(+ 'Do not use shell, raw HTTP, another connector, or a recursive agent as a fallback','Distinguish missing tools from missing authentication','Enabling or selecting the plugin is not OAuth authentication',- 'Settings → MCP servers → OpnForm → Authenticate',- 'start a new conversation with OpnForm selected before the first message',- 'may not hot-reload OAuth credentials',- 'do not loop or claim the connection succeeded',- '`textarea` is not a valid OpnForm field type',- 'never continue to draft creation after validation fails',- "field reference's `authoring_guidelines`",- '`quality_warnings` as non-blocking editorial guidance',- 'Use human-facing labels in sentence case',- 'Add placeholders only when they provide a useful example or expected format',- 'pair at most two related short fields on a row',- 'not a generic “Submit”',+ 'start a new conversation with OpnForm selected',+ 'Do not loop on an OAuth challenge or claim that connection succeeded without a successful account-scoped result',+ '`textarea` is not a valid type',+ 'do not create or patch after a validation failure',+ '`quality_warnings`',+ '`name` is always visible respondent-facing copy',+ 'Add placeholders only for useful examples or expected formats',+ 'Use a contextual action',)->and($skill)->toContain('confirm_publish: true', 'confirm_trash: true')->and($skill)->not->toContain('`confirm: true`')->and($skill)->not->toContain('draft_token', 'capability secret')->and($skill)->toContain('Submission access is read-only')- ->and($skill)->toContain(- 'do not turn a recoverable enum or field error into a generic “server error”',+ ->and($bundle)->toContain(+ 'describe a recoverable field error as a generic server error','`border_radius` is `none`, `small`, or `full`',- 'Never invent aliases such as `medium` or `large`',)- ->and(substr_count($skill, "\n"))->toBeLessThan(500);+ ->and(str_word_count($skill))->toBeLessThan(900)+ ->and(opnformPluginPath('skills/opnform/references/form-authoring.md'))->toBeFile()+ ->and(opnformPluginPath('skills/opnform/references/account-and-submissions.md'))->toBeFile()+ ->and(opnformPluginPath('skills/opnform/references/connection-and-recovery.md'))->toBeFile();});it('declares the hosted OpnForm MCP dependency in native skill metadata', function () {@@ -222,13 +227,15 @@ it('does not expose plugin package files from the monorepo root', function () {});it('teaches agents how to change presentation and media without repository inspection', function () {- $skill = file_get_contents(opnformPluginPath('skills/opnform/SKILL.md'));+ $bundle = readOpnformSkillBundle();- expect($skill)- ->toContain('Re-read the field reference before changing presentation style, fields, layout, or media')- ->toContain('every visible block becomes one step automatically')- ->toContain('add an `image` object to that input or `nf-text` block')- ->toContain('Never persist localhost, private addresses, temporary tunnel domains');+ expect($bundle)+ ->toContain('opnform://schemas/agent-form-definition/v1')+ ->toContain('opnform://reference/form-fields/v1')+ ->toContain('before generating or materially changing fields, layout, presentation, or media')+ ->toContain('In focused mode, every visible block is already one step')+ ->toContain('attach an `image` object directly to that input or `nf-text` block')+ ->toContain('Never persist localhost, private addresses, temporary tunnels');});it('renders a guest preview automatically after creation and every draft change', function () {@@ -236,16 +243,19 @@ it('renders a guest preview automatically after creation and every draft change'$server = file_get_contents(app_path('Mcp/Servers/OpnFormServer.php'));$createTool = file_get_contents(app_path('Mcp/Tools/CreateFormDraftTool.php'));$patchTool = file_get_contents(app_path('Mcp/Tools/PatchFormDraftTool.php'));+ $previewTool = file_get_contents(app_path('Mcp/Tools/PreviewFormDraftTool.php'));expect($skill)- ->toContain('renders the interactive MCP preview automatically')- ->toContain('renders the refreshed interactive preview automatically')+ ->toContain('Call `preview_form_draft` exactly once with that handle')+ ->toContain('then call `preview_form_draft` exactly once')->and($server)- ->toContain('needs no login or preview wording')- ->toContain('Every patch_form_draft renders the updated preview too')+ ->toContain('Create and patch are data-only')+ ->toContain('call preview_form_draft exactly once')->and($createTool)- ->toContain('RendersApp(resource: FormDraftPreviewApp::class)')+ ->not->toContain('RendersApp')->and($patchTool)+ ->not->toContain('RendersApp')+ ->and($previewTool)->toContain('RendersApp(resource: FormDraftPreviewApp::class)');});@@ -257,15 +267,15 @@ it('guides the agent from guest preview to account save and explicit publicationexpect($skill)->toContain('whether the user wants another change or wants to save the form')- ->toContain('saved as a draft and ask whether the user wants to publish it')+ ->toContain('saved as an unpublished draft')->toContain('Asking is not confirmation')->and($server)- ->toContain('Never call a temporary guest draft saved')- ->toContain('publish only after an explicit affirmative response')+ ->toContain('ask whether to modify or save')+ ->toContain('require explicit confirmation')->and($createTool)- ->toContain('wants another change or wants to save the form')+ ->toContain('data-only')->and($patchTool)- ->toContain('wants another change or wants to save the form');+ ->toContain('data-only');});it('renders a flattened and hardened form preview frame', function () {diff --git a/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php b/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.phpindex bc52c54d3..8300d8135 100644--- a/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php+++ b/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php@@ -105,7 +105,7 @@ it('advertises guest and account tools with explicit per-tool auth policies', fu->not->toHaveKey('create_form')->and($tools['create_form_draft']['title'])->toBe('Create a Guest Form Draft')->and($tools['create_form_draft']['description'])- ->toContain('default creation tool', 'works immediately without login', 'never request authentication')+ ->toContain('Default tool', 'without login', 'call preview_form_draft exactly once')->and($tools['create_form_draft']['securitySchemes'])->toBe([['type' => 'noauth'],])@@ -168,7 +168,7 @@ it('hides guest draft capabilities but keeps validation and OAuth tools on self-expect($resourceUris)->toContain('opnform://schemas/agent-form-definition/v1', 'opnform://reference/form-fields/v1')- ->not->toContain('ui://opnform/form-draft-preview-v5');+ ->not->toContain('ui://opnform/form-draft-preview-v6');$this->postJson('/mcp', ['jsonrpc' => '2.0',@@ -217,6 +217,25 @@ it('creates an unpublished form automatically when the account has one workspace->and($form->edit_url)->toBeString()->not->toBeEmpty();});+it('rejects machine-like labels before saving an account form', function () {+ $user = User::factory()->create();+ managedWorkspace($user);++ OpnFormServer::actingAs($user, 'oauth')->tool(CreateFormTool::class, [+ 'definition' => managedFormDefinition([+ 'properties' => [+ ['name' => 'full_name', 'type' => 'text'],+ ['name' => 'contact_email', 'type' => 'email'],+ ],+ ]),+ ])->assertHasErrors([+ 'properties.0.name: Replace the raw label [full_name] with clear respondent-facing copy in sentence case.',+ 'properties.1.name: Replace the raw label [contact_email] with clear respondent-facing copy in sentence case.',+ ]);++ $this->assertDatabaseCount('forms', 0);+});+it('requires workspace selection only when multiple workspaces are available', function () {$user = User::factory()->create();$selected = managedWorkspace($user);diff --git a/api/tests/Feature/Mcp/GuestDraftToolsTest.php b/api/tests/Feature/Mcp/GuestDraftToolsTest.phpindex c23559340..dab169679 100644--- a/api/tests/Feature/Mcp/GuestDraftToolsTest.php+++ b/api/tests/Feature/Mcp/GuestDraftToolsTest.php@@ -32,11 +32,11 @@ it('publishes a neutral draft handle contract and accurate preview annotations',$open = app(OpenFormDraftInEditorTool::class)->toArray();expect($create['outputSchema']['properties'])->toHaveKey('draft_handle')- ->and($create['outputSchema']['properties'])->toHaveKey('preview_url')+ ->and($create['outputSchema']['properties'])->not->toHaveKey('preview_url')->and($create['outputSchema']['properties'])->not->toHaveKey('draft_token')- ->and($create['_meta']['ui']['resourceUri'])->toBe('ui://opnform/form-draft-preview-v5')- ->and(app(PatchFormDraftTool::class)->toArray()['_meta']['ui']['resourceUri'])- ->toBe('ui://opnform/form-draft-preview-v5')+ ->and($create['_meta'])->not->toHaveKey('ui')+ ->and(app(PatchFormDraftTool::class)->toArray()['_meta'])->not->toHaveKey('ui')+ ->and($preview['_meta']['ui']['resourceUri'])->toBe('ui://opnform/form-draft-preview-v6')->and($preview['inputSchema']['properties'])->toHaveKey('draft_handle')->and($preview['outputSchema']['properties'])->not->toHaveKeys(['editor_url',@@ -54,10 +54,9 @@ it('creates a seven-day server-side guest draft and returns an opaque handle', f'definition' => guestDraftDefinition(['visibility' => 'public']),])->assertOk()->assertSee('draft_handle')- ->assertSee('preview_url')+ ->assertDontSee('preview_url')->assertDontSee('capability secret')- ->assertSee('Customer intake')- ->assertSee('expected_version');+ ->assertSee('Customer intake');$draft = AgentFormDraft::query()->sole();@@ -115,7 +114,7 @@ it('patches form values and blocks with optimistic versioning', function () {$response->assertOk()->assertSee('Qualified lead')->assertSee('Full legal name')- ->assertSee('preview_url')+ ->assertDontSee('preview_url')->assertSee('version');$updated = $created['draft']->refresh();@@ -244,6 +243,39 @@ it('rejects duplicate block ids', function () {])->assertHasErrors(['unique id']);});+it('rejects machine-like labels before persisting a guest draft', function () {+ OpnFormServer::tool(CreateFormDraftTool::class, [+ 'definition' => guestDraftDefinition([+ 'properties' => [+ ['id' => 'full-name', 'name' => 'full_name', 'type' => 'text'],+ ['id' => 'contact-email', 'name' => 'contact_email', 'type' => 'email'],+ ],+ ]),+ ])->assertHasErrors([+ 'properties.0.name: Replace the raw label [full_name] with clear respondent-facing copy in sentence case.',+ 'properties.1.name: Replace the raw label [contact_email] with clear respondent-facing copy in sentence case.',+ ]);++ $this->assertDatabaseCount('agent_form_drafts', 0);+});++it('rejects markdown text blocks before persisting a guest draft', function () {+ OpnFormServer::tool(CreateFormDraftTool::class, [+ 'definition' => guestDraftDefinition([+ 'properties' => [[+ 'id' => 'introduction',+ 'name' => 'Introduction',+ 'type' => 'nf-text',+ 'content' => '# Contact us\n\n**Tell us how we can help.**',+ ]],+ ]),+ ])->assertHasErrors([+ 'properties.0.content: Replace Markdown with sanitized HTML',+ ]);++ $this->assertDatabaseCount('agent_form_drafts', 0);+});+it('rejects oversized draft definitions before persistence', function () {OpnFormServer::tool(CreateFormDraftTool::class, ['definition' => guestDraftDefinition([diff --git a/api/tests/Feature/Mcp/McpFoundationTest.php b/api/tests/Feature/Mcp/McpFoundationTest.phpindex fdb61d0de..5899d4f62 100644--- a/api/tests/Feature/Mcp/McpFoundationTest.php+++ b/api/tests/Feature/Mcp/McpFoundationTest.php@@ -32,15 +32,13 @@ it('exposes the OpnForm MCP endpoint and initializes the protocol', function ()->assertJsonPath('result.instructions', function (string $instructions): bool {$discoveryInstructions = substr($instructions, 0, 1024);- return str_contains($discoveryInstructions, 'Default every request to create a new form to the guest draft workflow')- && str_contains($discoveryInstructions, 'textarea is not a valid field type')- && str_contains($discoveryInstructions, 'correct and revalidate the definition before creating a draft')- && str_contains($discoveryInstructions, 'A natural request such as "create a contact form" needs no login')- && str_contains($discoveryInstructions, 'Never ask the user to connect')- && str_contains($discoveryInstructions, 'OAuth is required only for connected-account operations')- && str_contains($discoveryInstructions, 'Enabling or selecting the plugin is not OAuth authentication')- && str_contains($discoveryInstructions, 'Follow the catalog authoring guidelines')- && str_contains($discoveryInstructions, 'quality_warnings');+ return str_contains($discoveryInstructions, 'natural request to create a form as a guest workflow')+ && str_contains($discoveryInstructions, 'Create and patch are data-only')+ && str_contains($discoveryInstructions, 'preview_form_draft exactly once')+ && str_contains($discoveryInstructions, 'Use sanitized HTML, never Markdown')+ && str_contains($discoveryInstructions, 'respondent-facing label in sentence case')+ && str_contains($discoveryInstructions, 'Correct relevant quality_warnings before persistence')+ && str_contains($discoveryInstructions, 'OAuth is only for saving or managing account forms');});});@@ -173,7 +171,10 @@ it('publishes the versioned form definition schema', function () {->assertOk()->assertSee('agent-form-definition/v1.json')->assertSee('schema_version')- ->assertSee('properties');+ ->assertSee('properties')+ ->assertSee('Respondent-facing label')+ ->assertSee('sanitized HTML fragment')+ ->assertSee('never Markdown');});it('keeps every normalized top-level key represented in the published schema', function () {@@ -198,12 +199,16 @@ it('publishes the canonical form field catalog', function () {->assertSee('focused')->assertSee('authoring_guidelines')->assertSee('polished respondent-facing form')+ ->assertSee('sentence case')+ ->assertSee('natural words and spaces')+ ->assertSee('sanitized HTML')+ ->assertSee('never Markdown')->assertSee('block_media')->assertSee('trycloudflare.com')->assertSee('save');});-it('returns non-blocking authoring quality warnings with a valid definition', function () {+it('returns authoring quality warnings with their persistence severity', function () {OpnFormServer::tool(ValidateFormDefinitionTool::class, ['definition' => ['title' => 'Contact form',@@ -225,7 +230,7 @@ it('returns non-blocking authoring quality warnings with a valid definition', fufn (AssertableJson $warnings) => $warnings->each(fn (AssertableJson $warning) => $warning- ->hasAll(['code', 'message', 'path'])+ ->hasAll(['code', 'message', 'path', 'blocking']))));diff --git a/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.php b/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.phpindex 71dcd4544..322b0b383 100644--- a/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.php+++ b/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.php@@ -15,7 +15,9 @@ it('provides one shared authoring baseline to MCP resources and native prompts',->toHaveKeys(['objective', 'rules', 'validation'])->and($reference['rules'])->toHaveKeys(['context', 'copy', 'fields', 'layout', 'completion', 'integrity'])->and($completePrompt)->toContain(- 'human-facing labels in sentence case',+ 'respondent-facing labels in sentence case with natural spaces',+ 'never expose full_name, contact_email',+ 'sanitized HTML, never Markdown','Use placeholders only for a useful example or expected format','Use a contextual submit label','Do not invent legal consent',@@ -44,6 +46,7 @@ it('injects the shared authoring baseline into native form prompts', function ()->toContain('Use a contextual submit label')->not->toContain('{authoringGuidelines}')->and($fieldsPrompt->compiled())- ->toContain('Use human-facing labels in sentence case')+ ->toContain('respondent-facing labels in sentence case with natural spaces')+ ->toContain('sanitized HTML, never Markdown')->not->toContain('{authoringGuidelines}');});diff --git a/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.php b/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.phpindex c5900b8fd..7e3567e95 100644--- a/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.php+++ b/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.php@@ -5,7 +5,7 @@ use App\Service\Forms\AgentFormQualityAnalyzer;uses(Tests\TestCase::class);-it('returns actionable non-blocking warnings for a minimal machine-like form', function () {+it('returns actionable warnings with severity for a minimal machine-like form', function () {$definition = app(AgentFormDefinition::class)->normalizeAndValidate(['title' => 'Contact form','properties' => [@@ -25,7 +25,13 @@ it('returns actionable non-blocking warnings for a minimal machine-like form', f'long_answer_should_be_multiline','generic_submit_label','generic_completion_message',- )->and($warnings)->each->toHaveKeys(['code', 'message', 'path']);+ )->and($warnings)->each->toHaveKeys(['code', 'message', 'path', 'blocking'])+ ->and($warnings)->toContainEqual([+ 'code' => 'machine_like_label',+ 'message' => 'Replace the raw label [name] with clear respondent-facing copy in sentence case.',+ 'path' => 'properties.0.name',+ 'blocking' => true,+ ]);});it('does not warn for a polished contact form', function () {@@ -52,3 +58,25 @@ it('does not warn for a polished contact form', function () {expect(app(AgentFormQualityAnalyzer::class)->analyze($definition))->toBe([]);});++it('flags markdown in text blocks because OpnForm renders sanitized HTML', function () {+ $definition = app(AgentFormDefinition::class)->normalizeAndValidate([+ 'title' => 'Contact requests',+ 'properties' => [+ [+ 'name' => 'Introduction',+ 'type' => 'nf-text',+ 'content' => '# Contact us\n\n**Tell us how we can help.**',+ ],+ ['name' => 'Email address', 'type' => 'email'],+ ],+ ]);++ expect(app(AgentFormQualityAnalyzer::class)->analyze($definition))+ ->toContainEqual([+ 'code' => 'markdown_text_content',+ 'message' => 'Replace Markdown with sanitized HTML in nf-text content, for example <h1>Contact us</h1><p>How can we help?</p>.',+ 'path' => 'properties.0.content',+ 'blocking' => true,+ ]);+});diff --git a/client/pages/agent-drafts/preview.vue b/client/pages/agent-drafts/preview.vueindex d9b8b6e4b..5d64c20f0 100644--- a/client/pages/agent-drafts/preview.vue+++ b/client/pages/agent-drafts/preview.vue@@ -80,6 +80,7 @@ const form = ref(null)const formPreview = ref(null)const isSubmitted = ref(false)const isResetting = ref(false)+let previewRetryTimer = nullconst isEmbedded = computed(() => route.query.embedded === '1')const isFocused = computed(() => form.value?.presentation_style === 'focused')provide('disableCustomCodeExecution', true)@@ -104,6 +105,67 @@ const resetForm = () => {})}+const previewErrorStatus = exception => exception?.statusCode+ || exception?.response?.status+ || exception?.status++const retryAfterSeconds = (exception) => {+ const header = exception?.response?.headers?.get?.('retry-after')+ const seconds = Number.parseInt(header || '5', 10)++ return Math.min(Math.max(Number.isFinite(seconds) ? seconds : 5, 1), 60)+}++const loadPreview = (source, canRetryRateLimit = true) => {+ loading.value = true+ error.value = null++ $fetch(source.toString()).then((response) => {+ form.value = {+ ...response.draft.definition,+ no_branding: true,+ plan_tier: 'pro',+ is_trialing: false,+ max_file_size: 10,+ workspace: { plan_tier: 'pro', features: [], limits: {} },+ }+ }).catch((exception) => {+ const status = previewErrorStatus(exception)++ if (status === 429 && canRetryRateLimit) {+ const seconds = retryAfterSeconds(exception)+ errorTitle.value = 'Preview temporarily rate-limited'+ error.value = `Too many preview requests were received. Retrying automatically in ${seconds} seconds.`+ previewRetryTimer = window.setTimeout(() => loadPreview(source, false), seconds * 1000)++ return+ }++ if (status === 403) {+ errorTitle.value = 'This preview link has expired'+ error.value = 'Ask your AI assistant to generate a fresh preview of this draft.'++ return+ }++ if (status === 404) {+ errorTitle.value = 'This draft is no longer available'+ error.value = 'Guest drafts are available for seven days. Ask your AI assistant to recreate the form if you still need it.'++ return+ }++ errorTitle.value = status === 429+ ? 'Preview temporarily rate-limited'+ : 'The preview could not be loaded'+ error.value = status === 429+ ? 'Please wait a moment, then ask your AI assistant to refresh the preview.'+ : 'Ask your AI assistant to refresh the preview. Your draft may still be available.'+ }).finally(() => {+ loading.value = false+ })+}+onMounted(() => {try {const source = new URL(String(route.query.source || ''))@@ -113,24 +175,16 @@ onMounted(() => {throw new Error('The preview link is invalid.')}- $fetch(source.toString()).then((response) => {- form.value = {- ...response.draft.definition,- no_branding: true,- plan_tier: 'pro',- is_trialing: false,- max_file_size: 10,- workspace: { plan_tier: 'pro', features: [], limits: {} },- }- }).catch(() => {- errorTitle.value = 'This draft preview is no longer available'- error.value = 'Guest drafts and their previews are available for seven days. Ask your AI assistant to recreate the form if you still need it.'- }).finally(() => {- loading.value = false- })+ loadPreview(source)} catch (exception) {error.value = exception.message || 'The preview link is invalid.'loading.value = false}})++onBeforeUnmount(() => {+ if (previewRetryTimer) {+ window.clearTimeout(previewRetryTimer)+ }+})</script>diff --git a/plugins/opnform/.codex-plugin/plugin.json b/plugins/opnform/.codex-plugin/plugin.jsonindex ae9762cf5..8b759e218 100644--- a/plugins/opnform/.codex-plugin/plugin.json+++ b/plugins/opnform/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "opnform",- "version": "1.0.2",+ "version": "1.0.3","description": "Build private form drafts without signing in, then connect OpnForm to manage forms and read submissions.","author": {"name": "OpnForm",diff --git a/plugins/opnform/plugin.json b/plugins/opnform/plugin.jsonindex 83b098ebd..bda67d48d 100644--- a/plugins/opnform/plugin.json+++ b/plugins/opnform/plugin.json@@ -1,7 +1,7 @@{"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name": "opnform",- "version": "1.0.2",+ "version": "1.0.3","description": "Create, preview, and manage OpnForm forms and read their submissions with an AI agent.","author": {"name": "OpnForm",diff --git a/plugins/opnform/skills/opnform/SKILL.md b/plugins/opnform/skills/opnform/SKILL.mdindex 11c856ac7..27ded7730 100644--- a/plugins/opnform/skills/opnform/SKILL.md+++ b/plugins/opnform/skills/opnform/SKILL.md@@ -1,104 +1,49 @@---name: opnform-description: Use this when a user asks to create, preview, revise, claim, or manage an OpnForm form through MCP, or to search, inspect, analyze, or export OpnForm submissions.+description: Create, preview, revise, save, and manage OpnForm forms through MCP, or search, analyze, and export their submissions.---# OpnForm-Use the OpnForm MCP server for OpnForm operations. Start as a guest when the user only needs a new form and an interactive preview. Connect an account only when account or workspace data is required.+Use the OpnForm MCP tools exposed by the current conversation. Keep replies concise and outcome-first.-Treat an unqualified request such as “create a contact form”, “build a survey”, or “make me a registration form” as a guest draft request. Do not infer that the user wants account persistence merely because the plugin offers OAuth or the host displays a Connect button. Do not ask the user to sign in, call `get_account_context`, or call `create_form_in_account` unless the user explicitly asks to save the new form in their OpnForm account or a workspace.+## Route the request-## Require native MCP access+- A natural request to create a form starts as a temporary guest draft. Do not ask for login, account, workspace, guest-mode, or preview confirmation.+- Use OAuth only when the user asks to save to an account, manage existing forms, choose account data, or read submissions.+- If OpnForm tools are missing, explain that the plugin is not attached and ask the user to start a new conversation with OpnForm selected. Do not use shell, raw HTTP, another connector, or a recursive agent as a fallback.+- Before an account or submission operation, read [references/account-and-submissions.md](references/account-and-submissions.md).+- For connection failures or host-specific OAuth recovery, read [references/connection-and-recovery.md](references/connection-and-recovery.md).-- Use only the OpnForm MCP tools and resources exposed by the current host session.-- Never launch another Codex or ChatGPT agent, run `codex exec`, call OpnForm through shell commands or raw HTTP, inspect a repository or plugin cache for live product data, or switch to another OpnForm connector as a fallback.-- If the required OpnForm tools or resources are absent, stop. Explain that OpnForm is not attached to the current conversation and ask the user to start a new conversation with the OpnForm plugin selected before sending the first message. Do not attempt login, installation, or discovery through another route.-- Distinguish missing tools from missing authentication. Missing tools require a correctly attached plugin; an OAuth challenge from an available account tool means the OpnForm MCP server itself is not authenticated.-- Enabling or selecting the plugin is not OAuth authentication. In local Codex, tell the user to open **Settings → MCP servers → OpnForm → Authenticate** (or run `codex mcp login opnform` themselves). After OAuth completes, start a new conversation with OpnForm selected before the first message so Codex creates the MCP client with the stored credential. Existing local conversations can remain attached to their original guest client and may not hot-reload OAuth credentials. In hosted ChatGPT, use the connection flow presented by the host and retry in the same conversation only if the host supports it.-- If the tool still returns the OAuth challenge afterward, do not loop or claim the connection succeeded. In local Codex, first verify the OpnForm MCP server is authenticated, then move the request to a new conversation. If a fresh conversation still challenges, explain that no bearer credential reached the MCP server and ask the user to verify the server's authentication status.+## Create or revise a guest draft-## Build and revise a guest draft+Success means the latest draft is valid and the turn contains exactly one final interactive preview.-This is the default workflow for new-form requests, including when the user does not mention “guest”, “draft”, “preview”, or “without login”. The presence of OAuth-protected account tools does not make authentication a prerequisite for these steps.+1. Read [references/form-authoring.md](references/form-authoring.md), then read `opnform://schemas/agent-form-definition/v1` and `opnform://reference/form-fields/v1` before generating or materially changing fields, layout, presentation, or media.+2. Call `validate_form_definition`. Correct every validation error, every entry in `quality_warnings` marked `blocking`, and other relevant warnings while preserving intentional user choices.+3. Call `create_form_draft`. It is data-only and not idempotent: after success, keep its `draft_handle` private and do not call it again.+4. Call `preview_form_draft` exactly once with that handle. Do not finish a creation turn with text alone.+5. For a requested revision, use `patch_form_draft` with the latest `expected_version`, then call `preview_form_draft` exactly once. Do not call the preview tool before the mutation or more than once after success.+6. On a version conflict, call `get_form_draft`, reconcile the requested change, and retry with the current version. On a validation error, correct the operation and retry once. Never overwrite blindly.-1. Read `opnform://schemas/agent-form-definition/v1` and `opnform://reference/form-fields/v1` before generating a definition. Follow the field reference's `authoring_guidelines`. Re-read the field reference before changing presentation style, fields, layout, or media later in the conversation. Do not inspect the OpnForm source tree or guess product behavior when the MCP resources describe it.-2. Perform the respondent-facing quality pass below, then call `validate_form_definition`. Resolve every validation error. Treat `quality_warnings` as non-blocking editorial guidance: correct relevant warnings before creating or saving while preserving intentional user choices.-3. Call `create_form_draft` with the validated definition. Its result renders the interactive MCP preview automatically; present that preview even when the user did not ask to see one, and do not finish a create turn with text alone.-4. Keep the returned `draft_handle` in tool context and pass it unchanged to guest draft tools. It is an internal opaque reference, not user-facing form content: do not quote it to the user, write it to a file, log it, or send it to another service.-5. Use `preview_form_draft` to show or re-render an existing draft when no create or patch is being performed. This is a read-only step and must not create an editor link.-6. Apply requested changes with `patch_form_draft`, passing the latest `expected_version`. Validate the changed definition before persistence when needed. Its result renders the refreshed interactive preview automatically; present it before replying so the user never needs to ask to see an update.-7. If the version conflicts or the current state is uncertain, call `get_form_draft`, reconcile the user's requested changes, validate again, and retry with the new version. Never overwrite blindly.-8. If a patch returns a validation error, correct the invalid operation and retry once with the same latest version. Report the returned validation problem accurately; do not turn a recoverable enum or field error into a generic “server error”.-9. After the preview, briefly summarize the result and ask one concise next-step question: whether the user wants another change or wants to save the form to their OpnForm account. Use the user's language. Do not end with only “the draft is ready”, and do not claim that a temporary guest draft is saved to an account.-10. Call `open_form_draft_in_editor` only after the user chooses the preview's **Open in OpnForm** action or explicitly asks to continue in the editor. The returned handoff URL is reusable until the seven-day guest draft expires; generating another URL does not revoke earlier ones.+After the preview, summarize the result or change in one sentence and ask one immediate question: whether the user wants another change or wants to save the form to their OpnForm account. If the user already supplied the next instruction, perform it instead of repeating the question.-The browser editor keeps the guest draft available through an HttpOnly session. The user can preview and edit before signing in. Authentication and workspace selection happen only when the user chooses to save the draft into an OpnForm account.+Use `preview_form_draft` without a mutation only when the user asks to refresh or redisplay an existing preview. A preview is read-only and remains valid until its seven-day guest draft expires.-### Guide the next decision+Call `open_form_draft_in_editor` only when the user explicitly asks to edit in OpnForm or uses the preview's **Edit in OpnForm** action. Editor links are reusable until the guest draft expires.-- After every successful guest creation or revision, keep the interactive preview visible, mention the meaningful result or change in one sentence, and offer the two relevant choices: continue modifying the form or save it to the user's OpnForm account.-- When the user chooses to save, that is an explicit request for account persistence. Enter the authenticated workflow, preserve the latest validated definition, and connect only if needed. If the user prefers the visual editor, use the editor handoff instead.-- After a form is saved to an account and remains unpublished, clearly say that it is saved as a draft and ask whether the user wants to publish it. Asking is not confirmation: call `publish_form` only after an explicit affirmative response.-- If the user already gave the next instruction, follow it instead of repeating a menu. Keep suggestions contextual and limited to one immediate decision; do not pile on unrelated account or submission actions.+## Save and publish-### Produce a polished first draft+Saving requires account persistence. Connect only at that point, preserve the latest validated definition, and follow the workspace rules in the account reference.-- Infer the form's purpose, audience, language, and tone. Make conservative assumptions and show a useful first draft instead of blocking on non-essential questions.-- Keep short forms short. Unless the form is intentionally trivial, begin with a concise `nf-text` heading and one supporting sentence explaining its purpose.-- Use human-facing labels in sentence case. Use short noun labels for identity fields and direct, unbiased questions for surveys; never expose raw identifiers or snake_case.-- Add placeholders only when they provide a useful example or expected format. Never use them instead of visible labels or repeat “Enter your [label]”.-- Add help text only for constraints, unfamiliar information, formatting, or why information is requested.-- Use the most specific field type and mark only essential fields as required. Avoid duplicate or unnecessary questions.-- In classic mode, pair at most two related short fields on a row and keep long answers full width. Split long forms by meaningful sections, not arbitrary field counts.-- Use clean neutral style defaults unless the user supplies brand direction. Do not invent brand colors, logos, decorative media, legal consent, sensitive questions, response times, or business commitments.-- Use a contextual action such as “Send message”, “Request a quote”, or “Join the waitlist”, not a generic “Submit”. Add a specific completion message that confirms what happened and, when known, what comes next.-- Keep language, capitalization, tone, terminology, and option style consistent throughout the form.+- An account form is first saved as an unpublished draft. Say so, then ask whether the user wants to publish it.+- Asking is not confirmation. Call `publish_form` only after an explicit affirmative response with `confirm_publish: true` and the current revision.+- Require explicit confirmation before `trash_form` with `confirm_trash: true`.+- Explain any `disabled_features` returned when plan rules disable previewed features during save.-### Common field mappings+## Safety-- Use `type: text` for both short text and long-answer fields. Set `multi_lines: true` for a message, comment, description, or other textarea-style answer; `textarea` is not a valid OpnForm field type.-- Use `type: phone_number` for phone inputs, `type: email` for email inputs, and `type: url` for website inputs.-- Use `type: select` for one choice and `type: multi_select` for multiple choices. Build their option objects exactly as documented by `opnform://reference/form-fields/v1`.-- If a requested field does not map cleanly, re-read the field reference and validate the whole definition. Never guess a field type and never continue to draft creation after validation fails.--## Presentation and media--- `classic` is a continuous form. Use widths for columns and `nf-page-break` only when the user wants explicit pagination.-- `focused` is a Typeform-like flow: every visible block becomes one step automatically. Use full-width input blocks and concise `nf-text` intro steps. Remove `nf-page-break` and do not add standalone `nf-image`, `nf-divider`, `nf-code`, `nf-video`, or `nf-audio` blocks.-- Use the exact documented style values. In particular: `border_radius` is `none`, `small`, or `full`; `width` is `centered` or `full`; `size` is `sm`, `md`, or `lg`; and `theme` is `default`, `simple`, `notion`, `minimal`, or `transparent`. Never invent aliases such as `medium` or `large`.-- To illustrate a focused step, add an `image` object to that input or `nf-text` block. Follow the layouts and media schema in `opnform://reference/form-fields/v1`; do not confuse this with the standalone `nf-image.image_block` shape.-- Use only user-provided or durable public HTTPS image URLs. Never persist localhost, private addresses, temporary tunnel domains, expiring signed URLs, or asset paths found by reading the OpnForm repository.-- Preserve the existing language, copy, field IDs, and unrelated settings unless the user asks to change them. For a focused conversion, usually set `settings.auto_next`, `settings.navigation_arrows`, and the localized `translations.focused_next_button_text` deliberately.--## Work with an authenticated account--Authenticated tools remain discoverable before the account is connected. When the user asks for account, form, or submission data, call `get_account_context`; if the host returns an OAuth challenge, ask the user to complete the connection. In local Codex, continue from a new conversation after OAuth instead of repeatedly retrying from the guest conversation. Do not report that account tools are unavailable merely because the current session started as a guest.--For new forms, enter this authenticated workflow only when the user explicitly asks to save directly to their account or names an account/workspace destination. A request to create, build, or preview a form by itself remains in the guest workflow even when an account connection is available.--After authentication, use the account context to choose a workspace. If exactly one writable workspace is available, select it without asking. If several are available, call `list_workspaces` and ask the user which one to use. Workspace access is read-only through MCP; do not attempt workspace administration.--- Use form listing and lookup tools to identify the target before changing it.-- `create_form_in_account` creates an account-owned draft. State that it is saved but unpublished, then ask whether the user wants it published.-- Before `update_form`, `publish_form`, or `trash_form`, fetch the form and pass its current `revision` as `expected_revision`. On conflict, fetch, reconcile, and retry instead of overwriting newer changes.-- Call `publish_form` only after the user explicitly confirms publication, then pass the confirmed form's `expected_revision` and `confirm_publish: true`.-- Call `trash_form` only after the user explicitly confirms moving the form to trash, then pass the confirmed form's `expected_revision` and `confirm_trash: true`. MCP does not expose form restoration or permanent deletion.-- Premium fields may appear in previews. On save, preserve and explain any `disabled_features` and warnings returned by OpnForm; never imply that MCP bypasses the workspace plan.--## Read submissions--Submission access requires OAuth. Authenticate only when the user's request needs account data.--- Use `list_submissions` to browse, filter, and search. Use `get_submission` for one result.-- Use `get_submission_stats` only for aggregates available in OpnForm's form statistics view.-- Use `export_submissions` only when the user requests an export, then poll `get_submission_export` until it is ready.-- Submission access is read-only. Do not create, update, delete, or restore submissions.-- Return only the submission fields needed for the request, especially when values contain personal or sensitive data.--## Safety and recovery--- Keep internal draft handles out of user-facing text and logs. Treat editor handoffs, OAuth tokens, and export URLs as sensitive credentials.-- If a preview or editor URL expires, call the appropriate tool for a fresh URL; never reconstruct one.-- If authentication is unavailable, continue with guest-safe draft tools when the task permits it.-- Never bypass confirmation, workspace permission, validation, revision checks, plan enforcement, or rate limits.+- Keep `draft_handle`, editor handoffs, OAuth tokens, and export URLs out of user-facing text and logs.+- Never bypass validation, version or revision checks, workspace permissions, confirmations, plan enforcement, or rate limits.+- Submission access is read-only. Never create, update, delete, or restore submissions.+- When a preview fails, report the returned error accurately. A `429` is temporary rate limiting, not an expired draft.diff --git a/plugins/opnform/skills/opnform/references/account-and-submissions.md b/plugins/opnform/skills/opnform/references/account-and-submissions.mdnew file mode 100644index 000000000..cb7d8ab48--- /dev/null+++ b/plugins/opnform/skills/opnform/references/account-and-submissions.md@@ -0,0 +1,22 @@+# Account forms and submissions++Authenticated tools remain discoverable before OAuth. Request authentication only when this workflow actually needs account data.++## Workspaces and forms++- Call `get_account_context` when the user asks to save or manage account data.+- If exactly one writable workspace is available, use it without asking. If several are available, call `list_workspaces` and ask which one to use. Workspace management is not exposed.+- `create_form_in_account` saves an unpublished draft. After success, state that it is saved but unpublished and ask whether to publish.+- Before `update_form`, `publish_form`, or `trash_form`, fetch the form and pass its current `revision` as `expected_revision`.+- On conflict, fetch, reconcile, and retry. Never overwrite newer work blindly.+- Publish only after explicit confirmation using `confirm_publish: true`.+- Move a form to trash only after explicit confirmation using `confirm_trash: true`. Restore and permanent deletion are not exposed.+- Premium fields may appear in guest previews. Preserve and explain `disabled_features` and warnings returned during save.++## Submissions++- Use `list_submissions` to browse, filter, and search response values. Use `get_submission` for one result.+- Use `get_submission_stats` only for aggregates available in OpnForm's form statistics view.+- Use `export_submissions` only when the user requests an export, then poll `get_submission_export` until ready.+- Submission access is read-only. Do not create, update, delete, or restore submissions.+- Return only the fields needed for the request, especially when submissions contain personal or sensitive data.diff --git a/plugins/opnform/skills/opnform/references/connection-and-recovery.md b/plugins/opnform/skills/opnform/references/connection-and-recovery.mdnew file mode 100644index 000000000..e88456e4d--- /dev/null+++ b/plugins/opnform/skills/opnform/references/connection-and-recovery.md@@ -0,0 +1,11 @@+# Connection and recovery++Distinguish missing tools from missing authentication.++- Missing OpnForm tools means the plugin is not attached to the conversation. Ask the user to start a new conversation with OpnForm selected before the first message.+- An OAuth challenge from an account-scoped tool means the MCP server is available but the account is not connected. Ask the user to complete the host's connection flow.+- Enabling or selecting the plugin is not OAuth authentication.+- In local Codex, the user can authenticate through **Settings → MCP servers → OpnForm → Authenticate** or run `codex mcp login opnform`. A new conversation may be required afterward because existing MCP clients do not always hot-reload credentials.+- Do not loop on an OAuth challenge or claim that connection succeeded without a successful account-scoped result.+- If a guest-safe request can continue without authentication, keep using guest tools.+- If a preview URL fails, call `preview_form_draft` for a fresh render. If the seven-day draft itself expired, explain that it must be recreated.diff --git a/plugins/opnform/skills/opnform/references/form-authoring.md b/plugins/opnform/skills/opnform/references/form-authoring.mdnew file mode 100644index 000000000..48b2b3ee3--- /dev/null+++ b/plugins/opnform/skills/opnform/references/form-authoring.md@@ -0,0 +1,73 @@+# Form authoring++Create a polished respondent-facing form, not merely a valid JSON structure.++## Visible copy and technical identifiers++- `name` is always visible respondent-facing copy. Write natural labels in sentence case with spaces: `Full name`, `Email address`, `Phone number`.+- Never put `full_name`, `contact_email`, kebab-case, database keys, variable names, or internal terminology in `name`.+- `id` is the technical identifier. Omit it for new blocks and let OpnForm generate it. Preserve existing IDs when revising a draft.+- Keep labels, placeholders, help text, options, buttons, and completion copy in the user's language.++Correct:++```json+{+ "name": "Email address",+ "type": "email",+ "placeholder": "[email protected]",+ "required": true+}+```++Incorrect:++```json+{+ "name": "contact_email",+ "type": "email"+}+```++## `nf-text` uses HTML++The `content` property of an `nf-text` block is a sanitized HTML fragment. Never use Markdown syntax such as `# Heading`, `**bold**`, Markdown links, or fenced code blocks.++Use semantic HTML including `<h1>`, `<h2>`, `<p>`, `<strong>`, `<em>`, `<a>`, `<ul>`, `<ol>`, and `<li>`.++Correct:++```json+{+ "name": "Introduction",+ "type": "nf-text",+ "content": "<h1>Contact us</h1><p>Send us a message and we will get back to you.</p>"+}+```++Incorrect:++```json+{+ "name": "Introduction",+ "type": "nf-text",+ "content": "# Contact us\n\nSend us a message."+}+```++## Form quality++- Validate before every creation or save. Correct validation errors and every quality warning marked `blocking`, then retry once; do not create or patch after a validation failure or describe a recoverable field error as a generic server error.+- Use only documented enum values. For example, `border_radius` is `none`, `small`, or `full`; never invent aliases such as `medium` or `large`.+- Infer purpose, audience, language, and tone. Make conservative assumptions instead of blocking on optional details.+- Keep short forms short. Begin a non-trivial form with one concise `nf-text` heading and supporting sentence.+- Use the most specific field type. A message or other long answer is `type: text` with `multi_lines: true`; `textarea` is not a valid type.+- Add placeholders only for useful examples or expected formats. Never use them instead of visible labels or merely repeat the label.+- Add help text only for a constraint, unfamiliar information, formatting guidance, or why data is requested.+- Require only essential fields. Do not invent consent, sensitive questions, promises, response times, or brand assets.+- In classic mode, pair at most two related short fields on a row and keep long answers full width.+- In focused mode, every visible block is already one step. Use full-width blocks and no `nf-page-break` or standalone media blocks.+- To illustrate a field or focused step, attach an `image` object directly to that input or `nf-text` block.+- Use a contextual action such as `Send message` or `Request a quote`, plus a specific completion message.++Use only durable public HTTPS media URLs. Never persist localhost, private addresses, temporary tunnels, or expiring signed URLs.