Skip to content

Beautiful Open-Source Form Builder

Preserve MCP draft preview versions and restore earlier revisions (#1331)

Julien Nahum32ee650f42d6
diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml
index c3978c140..0d9ee1173 100644
--- a/.github/workflows/ci-cd.yml
+++ b/.github/workflows/ci-cd.yml
@@ -14,6 +14,7 @@ on:
- "scripts/e2e-*.sh"
- "scripts/setup-env.sh"
- "scripts/tests/setup-env-test.sh"
+ - "scripts/tests/mcp-draft-preview.test.mjs"
- ".github/workflows/**"
pull_request:
paths:
@@ -25,6 +26,7 @@ on:
- "scripts/e2e-*.sh"
- "scripts/setup-env.sh"
- "scripts/tests/setup-env-test.sh"
+ - "scripts/tests/mcp-draft-preview.test.mjs"
- ".github/workflows/**"
workflow_dispatch:
@@ -97,6 +99,10 @@ jobs:
- name: Install npm dependencies
run: npm ci --no-audit --no-progress --silent
+ - name: Test MCP draft preview version pinning
+ working-directory: .
+ run: node --test scripts/tests/mcp-draft-preview.test.mjs
+
- name: Run ESLint
run: npm run lint
diff --git a/api/app/Http/Controllers/AgentFormDraftController.php b/api/app/Http/Controllers/AgentFormDraftController.php
index 4306f4ed3..ca6425f56 100644
--- a/api/app/Http/Controllers/AgentFormDraftController.php
+++ b/api/app/Http/Controllers/AgentFormDraftController.php
@@ -14,12 +14,18 @@ class AgentFormDraftController extends Controller
{
public const SESSION_HEADER = 'x-agent-draft-session';
- public function preview(AgentFormDraft $draft, AgentFormDraftService $drafts): JsonResponse
+ public function preview(Request $request, AgentFormDraft $draft, AgentFormDraftService $drafts): JsonResponse
{
- abort_unless($draft->isAvailable(), Response::HTTP_NOT_FOUND);
+ $validated = $request->validate(['version' => ['sometimes', 'integer', 'min:1']]);
+ // Existing signed snapshot links remain readable after saving the draft.
+ // Unversioned links and guest editing capabilities keep their active-only lifecycle.
+ $savedSnapshot = isset($validated['version'])
+ && $draft->status === AgentFormDraft::STATUS_CLAIMED
+ && $draft->expires_at->isFuture();
+ abort_unless($draft->isAvailable() || $savedSnapshot, Response::HTTP_NOT_FOUND);
return response()->json([
- 'draft' => $drafts->serialize($draft),
+ 'draft' => $drafts->serialize($drafts->atVersion($draft, isset($validated['version']) ? (int) $validated['version'] : null)),
])->header('Cache-Control', 'private, no-store, max-age=0');
}
diff --git a/api/app/Mcp/Servers/OpnFormServer.php b/api/app/Mcp/Servers/OpnFormServer.php
index 45b409942..e1a74fd51 100644
--- a/api/app/Mcp/Servers/OpnFormServer.php
+++ b/api/app/Mcp/Servers/OpnFormServer.php
@@ -25,6 +25,7 @@ use App\Mcp\Tools\ExportSubmissionsTool;
use App\Mcp\Tools\GetSubmissionExportTool;
use App\Mcp\Tools\PatchFormDraftTool;
use App\Mcp\Tools\PreviewFormDraftTool;
+use App\Mcp\Tools\RestoreFormDraftVersionTool;
use App\Mcp\Tools\OpenFormDraftInEditorTool;
use App\Mcp\Tools\ValidateFormDefinitionTool;
use Laravel\Mcp\Server;
@@ -46,6 +47,7 @@ class OpnFormServer extends Server
CreateFormDraftTool::class,
GetFormDraftTool::class,
PatchFormDraftTool::class,
+ RestoreFormDraftVersionTool::class,
PreviewFormDraftTool::class,
OpenFormDraftInEditorTool::class,
GetAccountContextTool::class,
diff --git a/api/app/Mcp/Tools/GetFormDraftTool.php b/api/app/Mcp/Tools/GetFormDraftTool.php
index fb332d377..08d85e57a 100644
--- a/api/app/Mcp/Tools/GetFormDraftTool.php
+++ b/api/app/Mcp/Tools/GetFormDraftTool.php
@@ -15,7 +15,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[Name('get_form_draft')]
-#[Description('Fetch the current canonical definition and version of a private guest draft. Use this after a version conflict or whenever the current state is uncertain.')]
+#[Description('Fetch a private guest draft. Omit version for the current canonical definition, especially after a conflict. Provide version to inspect an earlier saved revision without changing the current draft.')]
#[IsReadOnly]
#[IsDestructive(false)]
#[IsOpenWorld(false)]
@@ -25,16 +25,18 @@ class GetFormDraftTool extends GuestDraftMcpTool
{
$validated = $request->validate([
'draft_handle' => ['required', 'string', 'size:43'],
+ 'version' => ['sometimes', 'integer', 'min:1'],
]);
return Response::structured([
- 'draft' => $drafts->serialize($drafts->get($validated['draft_handle'])),
+ 'draft' => $drafts->serialize($drafts->get($validated['draft_handle'], $validated['version'] ?? null)),
]);
}
public function schema(JsonSchema $schema): array
{
return [
+ 'version' => $schema->integer()->min(1)->description('Optional historical version. Omit to read the latest version.'),
'draft_handle' => $schema->string()
->description('Opaque reference returned by create_form_draft. Pass it unchanged.')
->min(43)
diff --git a/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php b/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
index fd2b341f3..71679dba7 100644
--- a/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
+++ b/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
@@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[Name('open_form_draft_in_editor')]
-#[Description('Create a reusable OpnForm editor link only after the user chooses to continue editing the guest draft in OpnForm. The link remains valid until the seven-day draft expires.')]
+#[Description('Create an OpnForm editor link only after the user chooses to continue editing the guest draft in OpnForm. Pass expected_version from the displayed preview to pin the link; it can be reused while that version remains current and the seven-day draft has not expired. Restore an old version before opening it.')]
#[IsReadOnly(false)]
#[IsDestructive(false)]
#[IsOpenWorld(false)]
@@ -40,9 +40,10 @@ class OpenFormDraftInEditorTool extends GuestDraftMcpTool
{
$validated = $request->validate([
'draft_handle' => ['required', 'string', 'size:43'],
+ 'expected_version' => ['sometimes', 'integer', 'min:1'],
]);
- $handoff = $drafts->issueEditorHandoff($validated['draft_handle']);
+ $handoff = $drafts->issueEditorHandoff($validated['draft_handle'], $validated['expected_version'] ?? null);
return Response::structured([
'editor_handoff_ready' => true,
@@ -53,6 +54,7 @@ class OpenFormDraftInEditorTool extends GuestDraftMcpTool
public function schema(JsonSchema $schema): array
{
return [
+ 'expected_version' => $schema->integer()->min(1)->description('Version displayed in the preview. If it is no longer current, restore that version first instead of opening a different version.'),
'draft_handle' => $schema->string()
->description('Opaque reference returned by create_form_draft. Pass it unchanged.')
->min(43)
diff --git a/api/app/Mcp/Tools/PreviewFormDraftTool.php b/api/app/Mcp/Tools/PreviewFormDraftTool.php
index d892a3ef9..f69d41202 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('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. After success, briefly summarize the result and ask one question offering two choices: modify the draft again or save it to the user\'s OpnForm account. Do not request OAuth unless the user chooses save. 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.')]
+#[Description('Render an interactive preview for an existing guest draft without changing it. Call exactly once after a successful create_form_draft, patch_form_draft, or restore_form_draft_version. Also use it when the user asks to refresh, redisplay, or compare a version: pass version for a historical preview, or omit it for latest. Comparing history does not restore or mutate the draft. After success, briefly summarize the result and ask one question offering two choices: modify the draft again or save it to the user\'s OpnForm account. Do not request OAuth unless the user chooses save. Each preview stays pinned to its displayed version 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)]
@@ -38,8 +38,9 @@ class PreviewFormDraftTool extends GuestDraftMcpTool
{
$validated = $request->validate([
'draft_handle' => ['required', 'string', 'size:43'],
+ 'version' => ['sometimes', 'integer', 'min:1'],
]);
- $draft = $drafts->get($validated['draft_handle']);
+ $draft = $drafts->get($validated['draft_handle'], $validated['version'] ?? null);
return Response::structured([
'draft_handle' => $validated['draft_handle'],
@@ -51,6 +52,7 @@ class PreviewFormDraftTool extends GuestDraftMcpTool
public function schema(JsonSchema $schema): array
{
return [
+ 'version' => $schema->integer()->min(1)->description('Optional historical version to compare. Each preview is pinned to the version returned and never follows later edits. Omit for latest.'),
'draft_handle' => $schema->string()
->description('Opaque reference returned by create_form_draft. Pass it unchanged.')
->min(43)
diff --git a/api/app/Mcp/Tools/RestoreFormDraftVersionTool.php b/api/app/Mcp/Tools/RestoreFormDraftVersionTool.php
new file mode 100644
index 000000000..445c44fd8
--- /dev/null
+++ b/api/app/Mcp/Tools/RestoreFormDraftVersionTool.php
@@ -0,0 +1,55 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Mcp\Support\McpOutputSchema;
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('restore_form_draft_version')]
+#[Description('Use only when the user asks to return to an earlier guest draft version. Fetch the latest draft first for expected_version. Copies the selected historical version into a new current version, preserving all intervening revisions. Does not save or publish an account form. Data-only: after success call preview_form_draft once. Do not retry after success; on a version conflict fetch current state before retrying.')]
+#[IsReadOnly(false)]
+#[IsDestructive]
+#[IsOpenWorld(false)]
+class RestoreFormDraftVersionTool extends GuestDraftMcpTool
+{
+ public function handle(Request $request, AgentFormDraftService $drafts): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'draft_handle' => ['required', 'string', 'size:43'],
+ 'expected_version' => ['required', 'integer', 'min:1'],
+ 'version' => ['required', 'integer', 'min:1'],
+ ]);
+ $draft = $drafts->restore($validated['draft_handle'], $validated['expected_version'], $validated['version']);
+
+ return Response::structured([
+ 'draft_handle' => $validated['draft_handle'],
+ 'draft' => $drafts->serialize($draft),
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'draft_handle' => $schema->string()->min(43)->max(43)->required(),
+ 'expected_version' => $schema->integer()->min(1)->description('Latest version returned by get_form_draft without a version parameter.')->required(),
+ 'version' => $schema->integer()->min(1)->description('Historical version requested by the user.')->required(),
+ ];
+ }
+
+ public function outputSchema(JsonSchema $schema): array
+ {
+ return [
+ 'draft_handle' => $schema->string()->min(43)->max(43)->required(),
+ 'draft' => McpOutputSchema::draft($schema)->required(),
+ ];
+ }
+}
diff --git a/api/app/Models/Forms/AgentFormDraft.php b/api/app/Models/Forms/AgentFormDraft.php
index 86b00d355..80664c943 100644
--- a/api/app/Models/Forms/AgentFormDraft.php
+++ b/api/app/Models/Forms/AgentFormDraft.php
@@ -61,4 +61,9 @@ class AgentFormDraft extends Model
{
return $this->hasMany(AgentFormDraftHandoff::class);
}
+
+ public function versions(): HasMany
+ {
+ return $this->hasMany(AgentFormDraftVersion::class);
+ }
}
diff --git a/api/app/Models/Forms/AgentFormDraftHandoff.php b/api/app/Models/Forms/AgentFormDraftHandoff.php
index c628ff3ad..7b4fa67f8 100644
--- a/api/app/Models/Forms/AgentFormDraftHandoff.php
+++ b/api/app/Models/Forms/AgentFormDraftHandoff.php
@@ -10,6 +10,7 @@ class AgentFormDraftHandoff extends Model
protected $fillable = [
'agent_form_draft_id',
'token_hash',
+ 'expected_version',
'last_used_at',
'expires_at',
];
@@ -21,6 +22,7 @@ class AgentFormDraftHandoff extends Model
protected function casts(): array
{
return [
+ 'expected_version' => 'integer',
'last_used_at' => 'datetime',
'expires_at' => 'datetime',
];
diff --git a/api/app/Models/Forms/AgentFormDraftVersion.php b/api/app/Models/Forms/AgentFormDraftVersion.php
new file mode 100644
index 000000000..8fd0576d4
--- /dev/null
+++ b/api/app/Models/Forms/AgentFormDraftVersion.php
@@ -0,0 +1,15 @@
+<?php
+
+namespace App\Models\Forms;
+
+use Illuminate\Database\Eloquent\Model;
+
+class AgentFormDraftVersion extends Model
+{
+ protected $fillable = ['version', 'schema_version', 'definition'];
+
+ protected function casts(): array
+ {
+ return ['version' => 'integer', 'schema_version' => 'integer', 'definition' => 'array'];
+ }
+}
diff --git a/api/app/Service/Forms/AgentFormDraftService.php b/api/app/Service/Forms/AgentFormDraftService.php
index 0152cc84c..defb9593c 100644
--- a/api/app/Service/Forms/AgentFormDraftService.php
+++ b/api/app/Service/Forms/AgentFormDraftService.php
@@ -46,9 +46,59 @@ class AgentFormDraftService
return ['draft' => $draft, 'token' => $token];
}
- public function get(string $token): AgentFormDraft
+ public function get(string $token, ?int $version = null): AgentFormDraft
{
- return $this->resolveActive($token);
+ return $this->atVersion($this->resolveActive($token), $version);
+ }
+
+ /** Return a detached view of a revision; never save this view back to the draft. */
+ public function atVersion(AgentFormDraft $draft, ?int $version): AgentFormDraft
+ {
+ if ($version === null || $version === $draft->version) {
+ return $draft;
+ }
+
+ $revision = $draft->versions()->where('version', $version)->first();
+ if (! $revision) {
+ throw ValidationException::withMessages([
+ 'version' => ['This draft version is unavailable. Older versions from before version history was enabled cannot be recovered.'],
+ ]);
+ }
+
+ return (clone $draft)->forceFill([
+ 'version' => $revision->version,
+ 'schema_version' => $revision->schema_version,
+ 'definition' => $revision->definition,
+ ]);
+ }
+
+ public function restore(string $token, int $expectedVersion, int $version): AgentFormDraft
+ {
+ return DB::transaction(function () use ($token, $expectedVersion, $version) {
+ $draft = $this->resolveActive($token, lock: true);
+ $this->assertActiveVersion($draft, $expectedVersion);
+ $definition = $this->atVersion($draft, $version)->definition;
+ $definition['visibility'] = 'draft';
+ $definition = $this->formDefinition->normalizeAndValidate($definition);
+ $this->qualityAnalyzer->assertReadyForAgentPersistence($definition);
+ $this->preserveVersion($draft);
+ $draft->forceFill([
+ 'definition' => $definition,
+ 'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
+ 'version' => $draft->version + 1,
+ ])->save();
+
+ return $draft->refresh();
+ });
+ }
+
+ private function preserveVersion(AgentFormDraft $draft): void
+ {
+ // Called while holding the parent row lock, in the same transaction as its update.
+ $draft->versions()->firstOrCreate(['version' => $draft->version], [
+ 'schema_version' => $draft->schema_version,
+ 'definition' => $draft->definition,
+ ]);
}
public function patch(string $token, int $expectedVersion, array $operations): AgentFormDraft
@@ -67,6 +117,7 @@ class AgentFormDraftService
$definition = $this->formDefinition->normalizeAndValidate($definition);
$this->qualityAnalyzer->assertReadyForAgentPersistence($definition);
+ $this->preserveVersion($draft);
$draft->forceFill([
'definition' => $definition,
'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
@@ -91,15 +142,19 @@ class AgentFormDraftService
/**
* @return array{handoff_token: string, editor_url: string, expires_at: string}
*/
- public function issueEditorHandoff(string $draftToken): array
+ public function issueEditorHandoff(string $draftToken, ?int $expectedVersion = null): array
{
- return DB::transaction(function () use ($draftToken) {
+ return DB::transaction(function () use ($draftToken, $expectedVersion) {
$draft = $this->resolveActive($draftToken, lock: true);
+ if ($expectedVersion !== null) {
+ $this->assertActiveVersion($draft, $expectedVersion);
+ }
$handoffToken = $this->generateToken();
$expiresAt = $draft->expires_at->copy();
$draft->editorHandoffs()->create([
'token_hash' => $this->hashToken($handoffToken),
+ 'expected_version' => $expectedVersion,
'expires_at' => $expiresAt,
]);
@@ -143,6 +198,12 @@ class AgentFormDraftService
]);
}
+ if ($handoff->expected_version !== null && $handoff->expected_version !== $draft->version) {
+ throw ValidationException::withMessages([
+ 'handoff_token' => ["This editor link points to draft v{$handoff->expected_version}, but the current version is v{$draft->version}. Open the latest preview, or ask ChatGPT to restore v{$handoff->expected_version}."],
+ ]);
+ }
+
$editorSession = $this->editorSessionToken($draft);
$handoff->forceFill(['last_used_at' => now()])->save();
$draft->forceFill([
@@ -167,6 +228,7 @@ class AgentFormDraftService
$definition['visibility'] = 'draft';
$definition = $this->formDefinition->normalizeAndValidate($definition);
+ $this->preserveVersion($draft);
$draft->forceFill([
'definition' => $definition,
'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
@@ -201,6 +263,7 @@ class AgentFormDraftService
$definition = $this->formDefinition->normalizeAndValidate($definition, $workspace);
$created = $this->formCreation->create($definition, $user, $workspace);
+ $this->preserveVersion($draft);
$draft->forceFill([
'status' => AgentFormDraft::STATUS_CLAIMED,
'claimed_form_id' => $created['form']->id,
@@ -220,7 +283,7 @@ class AgentFormDraftService
$sourceUrl = URL::temporarySignedRoute(
'agent-drafts.preview',
$draft->expires_at,
- ['draft' => $draft->id],
+ ['draft' => $draft->id, 'version' => $draft->version],
);
return front_url('/agent-drafts/preview?source='.rawurlencode($sourceUrl));
diff --git a/api/database/migrations/2026_10_22_000000_add_agent_form_draft_version_history.php b/api/database/migrations/2026_10_22_000000_add_agent_form_draft_version_history.php
new file mode 100644
index 000000000..5b3430c70
--- /dev/null
+++ b/api/database/migrations/2026_10_22_000000_add_agent_form_draft_version_history.php
@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ public function up(): void
+ {
+ Schema::create('agent_form_draft_versions', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('agent_form_draft_id')->constrained()->cascadeOnDelete();
+ $table->unsignedInteger('version');
+ $table->unsignedInteger('schema_version');
+ $table->json('definition');
+ $table->timestamps();
+ $table->unique(['agent_form_draft_id', 'version']);
+ });
+
+ Schema::table('agent_form_draft_handoffs', function (Blueprint $table) {
+ $table->unsignedInteger('expected_version')->nullable();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('agent_form_draft_handoffs', function (Blueprint $table) {
+ $table->dropColumn('expected_version');
+ });
+
+ Schema::dropIfExists('agent_form_draft_versions');
+ }
+};
diff --git a/api/resources/views/mcp/form-draft-preview-app.blade.php b/api/resources/views/mcp/form-draft-preview-app.blade.php
index 64a3bcb15..a51e146c7 100644
--- a/api/resources/views/mcp/form-draft-preview-app.blade.php
+++ b/api/resources/views/mcp/form-draft-preview-app.blade.php
@@ -13,6 +13,7 @@
.eyebrow::before { width: 6px; height: 6px; border-radius: 999px; background: #3b82f6; content: ''; }
h1 { overflow: hidden; margin: 0; font-size: 16px; line-height: 1.25; text-overflow: ellipsis; white-space: nowrap; }
.meta { flex: none; margin: 0; color: var(--color-text-secondary, #6b7280); font-size: 11px; line-height: 1.25; }
+ .version-hint { margin: 7px 0 0; color: var(--color-text-secondary, #6b7280); font-size: 11px; }
.zoom-controls { display: flex; align-items: center; overflow: hidden; border: 1px solid var(--color-border-primary, #d1d5db); border-radius: 7px; background: var(--color-background-primary, #fff); }
.zoom-button { display: grid; width: 28px; height: 28px; place-items: center; border: 0; border-radius: 0; padding: 0; background: transparent; color: var(--color-text-primary, #111827); font-size: 15px; font-weight: 500; cursor: pointer; }
.zoom-button:hover:not(:disabled), .zoom-value:hover { background: var(--color-background-secondary, #f3f4f6); }
@@ -54,6 +55,7 @@
let presentationStyle = 'classic';
let resizeScriptPromise;
let draftHandle = null;
+ let draftVersion = null;
let currentPreviewUrl = null;
let rendered = false;
const initialOpenButtonText = openButton.textContent;
@@ -124,9 +126,11 @@
?? {};
const applyToolInput = (input) => {
+ if (rendered) return;
+
const args = input?.arguments ?? input ?? {};
draftHandle = args.draft_handle ?? draftHandle;
- openButton.disabled = !draftHandle;
+ openButton.disabled = true;
};
const renderToolResult = (result) => {
@@ -135,17 +139,28 @@
const draft = payload.draft ?? {};
const definition = draft.definition ?? {};
const previewUrlValue = resultMeta.preview_url;
+ const nextDraftHandle = payload.draft_handle ?? draftHandle;
+
+ if (!Number.isInteger(draft.version) || draft.version < 1 || !nextDraftHandle) {
+ return false;
+ }
- if (!previewUrlValue && !draft.version && !definition.title) {
+ // A conversation preview represents one revision, even if the host
+ // later delivers another tool result to the same component.
+ if (rendered && (draft.version !== draftVersion
+ || (payload.draft_handle && payload.draft_handle !== draftHandle))) {
return false;
}
rendered = true;
window.clearTimeout(loadingFallback);
- draftHandle = payload.draft_handle ?? draftHandle;
+ draftHandle = nextDraftHandle;
+ draftVersion = draft.version ?? null;
+ document.getElementById('version-hint').textContent = `Fixed preview · Ask ChatGPT to return to v${draftVersion ?? '?'} to continue from this version.`;
presentationStyle = definition.presentation_style ?? 'classic';
title.textContent = definition.title ?? 'Untitled form';
meta.textContent = `Draft v${draft.version ?? '?'} · ${presentationStyle} layout`;
+ meta.title = `This preview stays on v${draft.version ?? '?'}. Ask ChatGPT to restore this version to continue from it.`;
applyPreviewLayout();
if (previewUrlValue) {
const previewUrl = new URL(previewUrlValue);
@@ -200,7 +215,7 @@
app.onToolResult(renderToolResult);
openButton.onclick = async () => {
- if (!draftHandle) return;
+ if (!rendered || !draftHandle || !Number.isInteger(draftVersion) || draftVersion < 1) return;
const actionStatus = document.getElementById('action-status');
openButton.disabled = true;
@@ -210,6 +225,7 @@
try {
const result = await app.callServerTool('open_form_draft_in_editor', {
draft_handle: draftHandle,
+ expected_version: draftVersion,
});
const resultMeta = toolMeta(result);
const editorUrl = resultMeta.editor_url;
@@ -220,7 +236,7 @@
await app.openLink({ url: editorUrl });
} catch (error) {
- actionStatus.textContent = 'Could not open the OpnForm editor. Please try again.';
+ actionStatus.textContent = `Could not open this version. If the draft has changed, ask ChatGPT to restore v${draftVersion ?? '?'} first, or open its latest preview.`;
actionStatus.hidden = false;
} finally {
openButton.textContent = initialOpenButtonText;
@@ -252,6 +268,7 @@
<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="version-hint" class="version-hint"></p>
<p id="action-status" class="action-status" role="status" aria-live="polite" hidden></p>
<div id="preview-viewport" class="preview-viewport" hidden>
<div id="preview-canvas" class="preview-canvas">
diff --git a/api/tests/Feature/Mcp/AgentDraftVersionsTest.php b/api/tests/Feature/Mcp/AgentDraftVersionsTest.php
new file mode 100644
index 000000000..a662ceb96
--- /dev/null
+++ b/api/tests/Feature/Mcp/AgentDraftVersionsTest.php
@@ -0,0 +1,212 @@
+<?php
+
+use App\Mcp\Servers\OpnFormServer;
+use App\Mcp\Tools\GetFormDraftTool;
+use App\Mcp\Tools\PreviewFormDraftTool;
+use App\Mcp\Tools\RestoreFormDraftVersionTool;
+use App\Models\Forms\Form;
+use App\Service\Forms\AgentFormDraftService;
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Validation\ValidationException;
+use Illuminate\Support\Facades\URL;
+
+beforeEach(function () {
+ config()->set('app.self_hosted', false);
+ config()->set('app.front_url', 'https://opnform.test');
+});
+
+function versionedDraft(): array
+{
+ return app(AgentFormDraftService::class)->create([
+ 'title' => 'Contact v1',
+ 'properties' => [['id' => 'name', 'name' => 'Name', 'type' => 'text']],
+ ]);
+}
+
+function versionedPreviewSource($draft): string
+{
+ parse_str(parse_url(app(AgentFormDraftService::class)->previewUrl($draft), PHP_URL_QUERY), $query);
+
+ return $query['source'];
+}
+
+it('keeps signed previews pinned after patches and restoration', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $v1 = $created['draft']->definition;
+ $firstUrl = versionedPreviewSource($created['draft']);
+ $patched = $service->patch($created['token'], 1, [
+ ['op' => 'set_form_values', 'values' => ['title' => 'Contact v2']],
+ ['op' => 'add_block', 'block' => ['name' => 'Email', 'type' => 'email']],
+ ]);
+ $v2 = $patched->definition;
+ $secondUrl = versionedPreviewSource($patched);
+
+ $this->getJson($firstUrl)->assertOk()->assertJsonPath('draft.version', 1)->assertJsonPath('draft.definition', $v1);
+ $this->getJson($secondUrl)->assertOk()->assertJsonPath('draft.version', 2)->assertJsonPath('draft.definition', $v2);
+
+ $restored = $service->restore($created['token'], 2, 1);
+ expect($restored->version)->toBe(3)->and($restored->definition)->toBe($v1);
+ $this->getJson($firstUrl)->assertOk()->assertJsonPath('draft.definition', $v1);
+ $this->getJson($secondUrl)->assertOk()->assertJsonPath('draft.definition', $v2);
+ expect($service->get($created['token'], 2)->definition)->toBe($v2);
+});
+
+it('preserves revisions written through the editor too', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $source = versionedPreviewSource($created['draft']);
+ $session = $service->consumeEditorHandoff($service->issueEditorHandoff($created['token'])['handoff_token']);
+ $definition = $created['draft']->definition;
+ $definition['title'] = 'Edited in OpnForm';
+ $service->replaceFromEditor($session['editor_session'], 1, $definition);
+
+ $this->getJson($source)->assertOk()->assertJsonPath('draft.definition.title', 'Contact v1');
+ expect($service->get($created['token'])->version)->toBe(2);
+});
+
+it('rejects stale restoration without changing either revision', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $service->patch($created['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Newer work']]]);
+
+ expect(fn () => $service->restore($created['token'], 1, 1))->toThrow(ValidationException::class);
+ expect($service->get($created['token'])->definition['title'])->toBe('Newer work');
+ $this->assertDatabaseCount('agent_form_draft_versions', 1);
+});
+
+it('never substitutes latest for a missing revision or another drafts revision', function () {
+ $service = app(AgentFormDraftService::class);
+ $first = versionedDraft();
+ $service->patch($first['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Other draft v2']]]);
+ $service->restore($first['token'], 2, 1);
+ $second = versionedDraft();
+
+ expect(fn () => $service->get($second['token'], 2))->toThrow(ValidationException::class);
+ expect(fn () => $service->restore($second['token'], 1, 2))->toThrow(ValidationException::class);
+ expect($service->get($second['token'])->version)->toBe(1);
+});
+
+it('signs the version and keeps expiry enforcement', function () {
+ $created = versionedDraft();
+ $source = versionedPreviewSource($created['draft']);
+ expect($source)->toContain('version=1');
+ $this->getJson(str_replace('version=1', 'version=2', $source))->assertForbidden();
+ $this->travel(8)->days();
+ $this->getJson($source)->assertForbidden();
+ expect(fn () => app(AgentFormDraftService::class)->get($created['token'], 1))->toThrow(ValidationException::class);
+});
+
+it('keeps signed snapshots readable after saving without exposing later account edits', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $firstUrl = versionedPreviewSource($created['draft']);
+ $current = $service->patch($created['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Contact v2']]]);
+ $secondUrl = versionedPreviewSource($current);
+ $unversionedUrl = URL::temporarySignedRoute('agent-drafts.preview', $current->expires_at, ['draft' => $current->id]);
+ $session = $service->consumeEditorHandoff($service->issueEditorHandoff($created['token'], 2)['handoff_token']);
+ $user = $this->createUser();
+ $workspace = $this->createUserWorkspace($user);
+ $saved = $service->claim($session['editor_session'], 2, $workspace, $user);
+ $saved['form']->forceFill(['title' => 'Changed after saving'])->save();
+
+ $this->getJson($firstUrl)->assertOk()->assertJsonPath('draft.version', 1)->assertJsonPath('draft.definition.title', 'Contact v1');
+ $this->getJson($secondUrl)->assertOk()->assertJsonPath('draft.version', 2)->assertJsonPath('draft.definition.title', 'Contact v2');
+ $this->getJson($unversionedUrl)->assertNotFound();
+ expect(fn () => $service->get($created['token']))->toThrow(ValidationException::class);
+ expect(fn () => $service->restore($created['token'], 2, 1))->toThrow(ValidationException::class);
+ $this->travel(8)->days();
+ $this->getJson($firstUrl)->assertForbidden();
+});
+
+it('keeps the guest draft independent when ChatGPT saves a copy in an account', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $source = versionedPreviewSource($created['draft']);
+ $user = $this->createUser();
+ $workspace = $this->createUserWorkspace($user);
+ $saved = app(McpFormManagementService::class)->create($user, $workspace->id, $created['draft']->definition);
+ $form = Form::query()->findOrFail($saved['form']['id']);
+
+ $service->patch($created['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Guest v2']]]);
+ expect($form->refresh()->title)->toBe('Contact v1');
+ $form->forceFill(['title' => 'Edited in the account'])->save();
+ $restored = $service->restore($created['token'], 2, 1);
+
+ expect($restored->version)->toBe(3)
+ ->and($restored->definition['title'])->toBe('Contact v1')
+ ->and($service->get($created['token'])->isAvailable())->toBeTrue()
+ ->and($form->refresh()->title)->toBe('Edited in the account');
+ $this->getJson($source)->assertOk()->assertJsonPath('draft.version', 1)->assertJsonPath('draft.definition.title', 'Contact v1');
+});
+
+it('does not open a newer draft from a historical preview', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $service->patch($created['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Newer work']]]);
+
+ expect(fn () => $service->issueEditorHandoff($created['token'], 1))->toThrow(ValidationException::class);
+ $this->assertDatabaseCount('agent_form_draft_handoffs', 0);
+ expect($service->issueEditorHandoff($created['token'], 2)['editor_url'])->toContain('/agent-drafts/edit');
+});
+
+it('checks a pinned editor link again when it is consumed', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $link = $service->issueEditorHandoff($created['token'], 1);
+ $service->patch($created['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Newer work']]]);
+
+ expect(fn () => $service->consumeEditorHandoff($link['handoff_token']))->toThrow(ValidationException::class);
+ expect($created['draft']->refresh()->editor_session_hash)->toBeNull();
+ expect($service->get($created['token'])->definition['title'])->toBe('Newer work');
+});
+
+it('allows a pinned editor link to be reused while its version is still current', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $link = $service->issueEditorHandoff($created['token'], 1);
+ $first = $service->consumeEditorHandoff($link['handoff_token']);
+ $second = $service->consumeEditorHandoff($link['handoff_token']);
+
+ expect($second['editor_session'])->toBe($first['editor_session'])
+ ->and($second['draft']->version)->toBe(1);
+});
+
+it('exposes historical reads previews and restoration to MCP without mutating old versions', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ $service->patch($created['token'], 1, [['op' => 'set_form_values', 'values' => ['title' => 'Contact v2']]]);
+ foreach ([GetFormDraftTool::class, PreviewFormDraftTool::class] as $tool) {
+ OpnFormServer::tool($tool, ['draft_handle' => $created['token'], 'version' => 1])
+ ->assertOk()->assertSee('Contact v1')->assertDontSee('Contact v2');
+ }
+ OpnFormServer::tool(RestoreFormDraftVersionTool::class, [
+ 'draft_handle' => $created['token'], 'expected_version' => 2, 'version' => 1,
+ ])->assertOk()->assertSee('Contact v1');
+ expect($service->get($created['token'])->version)->toBe(3)
+ ->and($service->get($created['token'], 2)->definition['title'])->toBe('Contact v2');
+});
+
+it('starts history from the existing version without inventing lost history', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ // Simulate a pre-migration draft whose first four definitions were overwritten.
+ $created['draft']->forceFill(['version' => 5])->save();
+ $source = versionedPreviewSource($created['draft']);
+ $service->patch($created['token'], 5, [['op' => 'set_form_values', 'values' => ['title' => 'Version 6']]]);
+ $this->getJson($source)->assertOk()->assertJsonPath('draft.version', 5)->assertJsonPath('draft.definition.title', 'Contact v1');
+ expect(fn () => $service->get($created['token'], 4))->toThrow(ValidationException::class);
+ expect($service->restore($created['token'], 6, 5)->version)->toBe(7);
+});
+
+it('does not save a revision for a rejected modification', function () {
+ $service = app(AgentFormDraftService::class);
+ $created = versionedDraft();
+ expect(fn () => $service->patch($created['token'], 1, [
+ ['op' => 'set_form_values', 'values' => ['title' => 'Changed']],
+ ['op' => 'not_an_operation'],
+ ]))->toThrow(ValidationException::class);
+ $this->assertDatabaseCount('agent_form_draft_versions', 0);
+ expect($service->get($created['token'])->version)->toBe(1)
+ ->and($service->get($created['token'])->definition['title'])->toBe('Contact v1');
+});
diff --git a/api/tests/Feature/Mcp/McpFoundationTest.php b/api/tests/Feature/Mcp/McpFoundationTest.php
index 0d6c39d24..51ef8640c 100644
--- a/api/tests/Feature/Mcp/McpFoundationTest.php
+++ b/api/tests/Feature/Mcp/McpFoundationTest.php
@@ -85,6 +85,7 @@ it('advertises explicit safety annotations for every MCP tool', function () {
];
$destructivePrivateWrites = [
'patch_form_draft',
+ 'restore_form_draft_version',
];
$destructiveOpenWorldWrites = [
'trash_form',
diff --git a/docs/integrations/mcp.mdx b/docs/integrations/mcp.mdx
index a369d8372..f0974f703 100644
--- a/docs/integrations/mcp.mdx
+++ b/docs/integrations/mcp.mdx
@@ -256,6 +256,21 @@ A logic condition may use that calculated value by setting `property_meta.type`
With `patch_form_draft`, replace the complete `computed_variables` list through `set_form_values`, and add or modify a block's `logic` through `add_block` or `update_block`. The draft is normalized and validated atomically before its version changes.
+### Compare and restore draft versions
+
+Each new interactive preview is pinned to the draft version it displays. Later chat or editor changes do not update that earlier preview. Ask your assistant to “show version 1” to compare it, or “return to version 1” to continue from it.
+
+- `get_form_draft` and `preview_form_draft` accept an optional `version`. Omit it to use the current version.
+- `restore_form_draft_version` takes `draft_handle`, the latest `expected_version`, and the historical `version` to restore. It creates a new current version without deleting intervening versions. For example, restoring V1 while on V3 creates V4 with V1's content.
+- Restoration does not save or publish an account form. After restoring, request a new preview and continue the normal save flow.
+- An old preview cannot silently open a newer version in the editor. Restore it first, or use the latest preview. A version-pinned editor link is checked both when created and when opened; if the draft changes in between, request a new link.
+
+History follows the seven-day guest draft lifetime. Saving through the browser editor claims the guest draft: guest editing and restoration stop, but existing signed, version-pinned previews remain readable until the original expiry. Saving through ChatGPT with `create_form_in_account` instead creates an independent account form and leaves the guest draft active until expiry, so you can still compare or restore its versions. Guest edits and restoration never update the saved account form, and account-form edits never change the guest snapshots. Use account tools for changes to saved forms; this feature does not add account-form revision history or rollback.
+
+Versions overwritten before this feature was enabled cannot be recovered, and previously generated unversioned preview links are not retroactively pinned.
+
+Self-hosted deployments must run the database migration before enabling the updated MCP code. Refresh tools in your AI assistant to discover the restoration tool and optional version parameters.
+
## Self-hosted OAuth configuration
The following settings apply only to self-hosted instances.
diff --git a/plugins/opnform/skills/opnform/SKILL.md b/plugins/opnform/skills/opnform/SKILL.md
index b8dd9d370..236d73536 100644
--- a/plugins/opnform/skills/opnform/SKILL.md
+++ b/plugins/opnform/skills/opnform/SKILL.md
@@ -17,20 +17,24 @@ Use the OpnForm MCP tools exposed by the current conversation. Keep replies conc
## Create or revise a guest draft
-Success means the latest draft is valid and the turn contains exactly one final interactive preview.
+For creation or edits, success means the latest draft is valid and the turn contains exactly one final interactive preview. For historical comparison, show the requested version without changing the current draft.
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.
+5. For a requested content or layout change, 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.
Required final reply after each successful preview: summarize the result or change in one sentence, then ask exactly one question offering two choices—make another change or save the form to the user's OpnForm account. A status-only response is incomplete. If the user already supplied the next instruction, perform it instead of repeating the question.
-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.
+To compare an earlier version, pass its `version` to `get_form_draft` or `preview_form_draft`. Omit `version` to fetch the current draft. Comparing history is read-only; do not patch or restore it.
-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.
+When the user asks to return to an earlier version, fetch the latest draft without `version`, then call `restore_form_draft_version` with that latest `expected_version` and the historical `version`. Restoration creates a new current version and preserves intervening revisions. After success, call `preview_form_draft` exactly once. Do not reconstruct the old definition through patch operations or retry a successful restoration.
+
+Use `preview_form_draft` without a mutation when the user asks to refresh, redisplay, or compare an existing version. Each preview stays pinned until the seven-day guest draft expires. Saving via the browser editor claims the draft: guest editing and restoration stop, but existing signed, versioned previews remain readable until expiry. `create_form_in_account` creates an independent copy and leaves the guest draft active until expiry. Guest edits or restoration never update that account form; use account tools for saved-form changes.
+
+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. Pass the displayed version as `expected_version`. A pinned editor link can be reused while that version remains current and the draft has not expired. If it becomes stale, open the latest preview; restore an older version only when the user asks to return to it.
## Save and publish
diff --git a/plugins/opnform/skills/opnform/references/connection-and-recovery.md b/plugins/opnform/skills/opnform/references/connection-and-recovery.md
index e88456e4d..2c81f0839 100644
--- a/plugins/opnform/skills/opnform/references/connection-and-recovery.md
+++ b/plugins/opnform/skills/opnform/references/connection-and-recovery.md
@@ -8,4 +8,4 @@ Distinguish missing tools from missing 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.
+- If a preview URL fails while the guest draft is active, call `preview_form_draft` for a fresh render, passing the displayed `version` when known so recovery does not substitute the latest content. If the seven-day draft itself expired, explain that it must be recreated. Saving through the browser editor claims the guest draft: only existing signed snapshots remain readable until expiry, and guest tools cannot generate new previews or restore it. Saving through `create_form_in_account` copies the definition without claiming the guest draft, so guest preview and restoration remain available until expiry. Guest restoration never changes the independent saved account form.
diff --git a/scripts/tests/mcp-draft-preview.test.mjs b/scripts/tests/mcp-draft-preview.test.mjs
new file mode 100644
index 000000000..f6c0269a2
--- /dev/null
+++ b/scripts/tests/mcp-draft-preview.test.mjs
@@ -0,0 +1,113 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const template = readFileSync(new URL('../../api/resources/views/mcp/form-draft-preview-app.blade.php', import.meta.url), 'utf8')
+const script = template.match(/<script type="module">([\s\S]*?)<\/script>/)[1]
+
+async function widget() {
+ const elements = new Map()
+ const element = () => ({
+ textContent: '', style: {}, clientWidth: 500, hidden: true,
+ replaceChildren() {}, appendChild() {},
+ })
+ const get = id => {
+ if (!elements.has(id)) elements.set(id, element())
+ return elements.get(id)
+ }
+ const calls = []
+ let render
+ let input
+ let ready
+ vm.runInNewContext(script, {
+ URL,
+ ResizeObserver: class { observe() {} },
+ document: {
+ getElementById: get,
+ createElement: element,
+ head: { appendChild(script) { script.onload() } },
+ },
+ window: { setTimeout() { return 1 }, clearTimeout() {}, iFrameResize() {} },
+ createMcpApp(setup) {
+ ready = setup({
+ onToolInput(handler) { input = handler },
+ onToolResult(handler) { render = handler },
+ autoResize() {},
+ async callServerTool(name, args) {
+ calls.push({ name, ...args })
+ return { _meta: { editor_url: 'https://opnform.test/editor' } }
+ },
+ async openLink() {},
+ })
+ },
+ })
+ await ready
+ return { get, render, input, calls }
+}
+
+function result(version, handle = 'draft-a') {
+ return {
+ structuredContent: {
+ draft_handle: handle,
+ draft: { version, definition: { title: `Contact v${version}`, properties: [] } },
+ },
+ _meta: { preview_url: `https://opnform.test/agent-drafts/preview?version=${version}` },
+ }
+}
+
+test('each widget stays on its initial revision, including late host results', async () => {
+ const first = await widget()
+ const second = await widget()
+ first.render(result(1))
+ const originalUrl = first.get('preview').src
+ second.render(result(2))
+ assert.equal(first.render(result(2)), false)
+ assert.equal(first.render(result(1, 'another-draft')), false)
+ assert.equal(first.get('title').textContent, 'Contact v1')
+ assert.equal(first.get('preview').src, originalUrl)
+ assert.equal(second.get('title').textContent, 'Contact v2')
+ assert.match(first.get('version-hint').textContent, /return to v1/)
+})
+
+test('editor action sends the displayed revision, not another host result', async () => {
+ const preview = await widget()
+ preview.render(result(1))
+ preview.render(result(2))
+ await preview.get('open-editor').onclick()
+ assert.equal(preview.calls.length, 1)
+ assert.equal(preview.calls[0].name, 'open_form_draft_in_editor')
+ assert.equal(preview.calls[0].expected_version, 1)
+ assert.equal(preview.calls[0].draft_handle, 'draft-a')
+})
+
+test('editor action waits for a complete versioned result', async () => {
+ const preview = await widget()
+ preview.input({ arguments: { draft_handle: 'draft-a' } })
+ assert.equal(preview.get('open-editor').disabled, true)
+ await preview.get('open-editor').onclick()
+ assert.equal(preview.calls.length, 0)
+
+ preview.render(result(1))
+ assert.equal(preview.get('open-editor').disabled, false)
+ await preview.get('open-editor').onclick()
+ assert.equal(preview.calls.length, 1)
+ assert.equal(preview.calls[0].expected_version, 1)
+})
+
+test('late tool input cannot retarget the editor action of a rendered preview', async () => {
+ const preview = await widget()
+ preview.render(result(1))
+ preview.input({ arguments: { draft_handle: 'another-draft' } })
+ await preview.get('open-editor').onclick()
+ assert.equal(preview.calls[0].draft_handle, 'draft-a')
+ assert.equal(preview.calls[0].expected_version, 1)
+})
+
+test('an incomplete host result does not prevent the full initial preview loading', async () => {
+ const preview = await widget()
+ preview.render({ _meta: { preview_url: 'https://opnform.test/preview' } })
+ preview.render(result(1))
+ assert.equal(preview.get('title').textContent, 'Contact v1')
+ assert.match(preview.get('preview').src, /version=1/)
+})