Commit Graph
2290 Commits
Author SHA1 Message Date
Oleg Isonen 97c18cc937 fix: configure published asset origin 2026-09-20 11:44:00 +01:00
Oleg Isonen cd1881bde6 fix: upload asset tickets serially (#6414)
## Summary

- Reserve and complete each asset upload before requesting the next
upload ticket.
- Prevent concurrent identical uploads from triggering the server's
in-progress deduplication error.
- Keep the upload result mapping keyed by the folder-scoped upload key.

## Verification

- `pnpm --filter @webstudio-is/builder exec vitest run
app/builder/shared/assets/upload-assets.test.ts
app/builder/shared/assets/directory-drop.test.ts
app/builder/shared/assets/asset-upload.test.tsx`
- 41 tests passed.
2026-09-18 14:38:13 +02:00
Oleg Isonen 0e30263787 fix: Fix multi-file asset drops and folder-scoped deduplication (#6413)
## Summary
- Preserve all files when dropping multiple local files into Assets.
- Scope client-side duplicate detection by folder.
- Allow the same underlying file to have asset entries in different
folders.

## Validation
- Focused asset upload and directory-drop tests passed locally.
- `git diff --check` passed.
2026-09-18 13:33:00 +02:00
Oleg Isonen e7181fffdc feat: Add GitHub-style Alert component (#6279)
## Summary

- Add one official `Alert` component with a content-editable `variant`
property for note, tip, important, warning, and caution.
- Register Alert in the component catalog with a generated title
descendant and Storybook story.
- Render GitHub-style alerts in Markdown Embed using the same DOM,
class, role, and variant contract.
- Materialize connected Content Block MDX alerts as actual Alert
instances and serialize content or variant edits back to `> [!TYPE]`.
- Document the component and both Markdown workflows.

## Implementation

Alert labels and variants live in Content Engine and are shared across
the component, Markdown renderer, and MDX adapters.

1. The Alert React component owns the wrapper, generated title, stable
classes, `role="note"`, and `data-variant`.
2. Markdown Embed transforms candidate micromark HTML before the
existing sanitizer and emits the same markup contract. It remains
sanitized HTML rather than a Builder instance tree.
3. Content Engine retains alert metadata on parsed Markdown blockquotes.
Project Build maps those nodes to Alert instances, reconciles their
authored children, and restores canonical GitHub syntax during MDX
serialization.
4. The component registry exports one Alert insertion template with a
styleable title descendant.

Unsupported, lowercase, misplaced, and malformed markers remain ordinary
blockquotes. There are no schema, migration, persisted-data, or
sanitizer-policy changes.

## Checklist

- [x] Add Alert as an official component with one Variant property.
- [x] Support all five GitHub alert types.
- [x] Share alert metadata and marker recognition.
- [x] Preserve nested Markdown and ordinary blockquote behavior.
- [x] Keep URL and HTML sanitization in the existing security boundary.
- [x] Add shared, title, and type-specific Markdown Embed descendants.
- [x] Materialize Content Block alerts as Alert instances.
- [x] Preserve alert content and variant changes through MDX
serialization.
- [x] Regenerate component props and Storybook artifacts from source.
- [x] Review documentation impact and update Alert, Markdown Embed,
Content Block, and navigation docs.
- [x] Verify fixture impact; no fixture inputs or generated fixture
outputs are changed.

## Verification

- [x] New tests demonstrated failure before implementation and pass
afterward.
- [x] `pnpm --filter @webstudio-is/content-engine test` — 417 passed.
- [x] `pnpm --filter @webstudio-is/project-build test` — 2,282 passed.
- [x] `pnpm --filter @webstudio-is/sdk-components-react test` — 144
passed, 1 skipped.
- [x] SDK component registry tests.
- [x] Relevant package typechecks, declaration builds, and production
builds.
- [x] Root lint, formatting, package-boundary, generated-doc, and diff
checks.
- [x] GitHub Actions main, E2E, lint, submodule, deployment, and
approved visual-regression checks.

## Known limitations

Alert identifiers must be uppercase and appear at the start of the
blockquote's first paragraph, matching the documented syntax. Markdown
Embed emits the component's markup contract but cannot create Builder
instances inside sanitized HTML.

Closes #6278
2026-09-18 00:42:50 +02:00
Oleg Isonen 18d171212f feat: Resolve asset paths in HTML embeds (#6409)
## Description

- Resolve root-relative script, stylesheet, image, and other asset
attributes in HTML Embed markup.
- Use the same asset-path map in Builder Canvas and generated published
sites.
- Keep SaaS asset proxy URLs deployment-relative instead of hard-coding
the `p-….apps.webstudio.is` project origin.
- Preserve canonical `/cgi/asset/` versus `/cgi/image/` routing and
`?format=raw` behavior in Canvas.

## Regression coverage

Added coverage for SaaS prebuild URLs, the real Builder
asset-map-to-HTML-Embed integration, every supported asset attribute,
HTML character references, and responsive-image `srcset` edge cases.

## Verification

- [x] CLI prebuild suite: 69 passed
- [x] HTML Embed suites: 63 passed
- [x] Full Builder browser suite: 2,646 passed
- [x] Asset URL map tests: 2 passed
- [x] CLI, Builder, React SDK, and project-build typechecks
- [x] Lint and package-boundary checks
- [x] Previous PR CI: 29 successful, 1 skipped

## Code Review

- [x] Self-reviewed
- [x] Added regression and integration tests
2026-09-17 20:38:40 +02:00
Oleg Isonen 60c549c46f fix: preserve local styles and improve issue diagnostics (#6408)
Fixes #6386

## Summary

- Keep local `ws:style` declarations after `ws:tokens` so instance
styles override token defaults.
- Capture privacy-safe HTTP timing/status, exceptional session namespace
states, preview freshness/version agreement, and validation paths in
issue reports.
- Derive reportable validation roots from the public operation catalog
instead of maintaining a duplicate allowlist.
- Keep captured failures current by clearing them after a successful
tool call.

## Verification

- Protocol issue-report tests: 3 passed
- Project build MCP: 128 tests passed
- CLI project session: 27 tests passed
- Builder issue reporter: 5 tests passed
- Relevant package typechecks passed
- Generated API metadata is clean
2026-09-17 20:13:27 +02:00
Oleg Isonen fc15ebf81a perf: avoid repeated MDX parsing in publish diagnostics (#6407)
## Description

The cold `build.contentDatabasePublishDiagnostics` path was parsing the
same reachable MDX documents while the publication plan converged, then
parsing them a third time to produce omission diagnostics. Content-heavy
projects can approach or exceed the 15-second serverless limit on that
first request.

This change:

- creates a request-scoped MDX dependency resolver that reuses parse
results by asset revision while the publication plan converges;
- carries the final template omissions out of the existing publication
pass, so the diagnostics endpoint does not walk the artifact again;
- keeps the existing sequential asset validation/preparation/stability
checks unchanged;
- does not use module-level caching or depend on a warm serverless
instance;
- leaves the timeout error handling from #6406 unchanged.

## Performance evidence

An isolated cold-path benchmark used the same MDX payload (2,000
sections) and compared the previous three independent
dependency-resolution walks with the new request-scoped convergence
path:

| path | time |
| --- | ---: |
| before | 1,178 ms |
| after | 404 ms |

That is a 66% reduction in the measured MDX resolution phase. The tests
also assert the underlying work reduction directly: an unchanged
revision is parsed once across convergence passes, while a changed
revision is parsed again. For a stable 214-document candidate set, this
removes up to 428 of the previous 642 parse operations.

## Verification

- `pnpm --filter @webstudio-is/project-build test` — 2,420 tests passed
- `pnpm --filter @webstudio-is/builder exec vitest run --project
core-server` — 336 tests passed, including server-side e2e runner tests
- `pnpm --filter @webstudio-is/project-build typecheck`
- `pnpm --filter @webstudio-is/builder typecheck`
- `pnpm lint`
- `pnpm check:package-boundaries`
- `pnpm check:generated-api`

## Code Review

- [x] made a self-review
- [x] added comments for the request-scoped cache and revision safety
- [x] added tests for parse reuse, revision invalidation, and the
optimized endpoint integration path

## Before merging

- [ ] tested on a deployment preview with a production-sized content
project

## Additional content-read optimization

Successive compilation plans now share already-fetched, revision-keyed
content bytes within one callback-scoped preparation session. The byte
store:

- is created inside one asset-stability attempt and discarded when that
attempt finishes;
- is not stored on the repository, in a module, or outside the request;
- remains bounded by the existing 2 MiB hydration limit;
- refetches changed revisions and starts clean on stability retries.

Tests verify that two overlapping plans read unchanged content once, a
revision change forces another read, a new session reads again, and a
stability retry creates a new session. A fully overlapping two-pass
workload therefore performs up to 50% fewer object-storage content
reads.

Additional verification:

- `pnpm --filter @webstudio-is/asset-uploader test` — 292 tests passed
- `pnpm --filter @webstudio-is/asset-uploader typecheck`

## Remaining optimization assessment

The percentages below estimate whole-request improvement and are
workload-dependent; they are not additive.

| optimization | estimated improvement | complexity | decision |
| --- | ---: | ---: | --- |
| Request-local content-byte reuse | 10–35% | 3/10 | Implemented |
| Stop when the initial dependency plan is already a fixed point | 5–15%
for static/known MDX; ~0% for dynamic discovery | 2/10 | Implemented |
| Reuse a canonical source snapshot/materialized entries across
different plans | 15–30% | 8/10 | Deferred: large semantic and
invalidation surface |
| Reuse the bundle's initial asset-data snapshot | 1–5% | 5/10 | Not
worthwhile |
| Add a diagnostics-specific bundle loader | 2–8% | 6/10 | Not
worthwhile for this PR |
| Parallelize or skip unrelated user/project metadata | 0–3% | 2/10 |
Not meaningful |
| Combine collection validation and reserved-asset inspection | 0–5%
normally | 4/10 | Only meaningful for projects with many collections |

The fixed-point fast path is covered by a test asserting one artifact
preparation and one dependency-resolution call when the original plan is
already stable.
2026-09-17 10:47:48 +02:00
Oleg Isonen 0d448313ab fix: harden MCP mutations and validation (#6402)
## Summary

Fixes the reproducible MCP regressions reported today:

- validate font upload metadata locally instead of surfacing an HTTP 500
- replace only the addressed child when `insertIndex` is supplied
- support cross-parent duplication
- bind data-variable assignments in actions
- reject string-valued `style` bindings
- include descriptions for every advertised MCP tool
- preserve resource data-source exposure on full updates
- render mixed expression/element children in the Builder canvas
- preserve explicit outer Collection references in nested scopes
- reject unsupported `update-page-settings` fields instead of dropping
them
- reject unavailable asset-query variables and log server error details

Closes #6390
Closes #6391
Closes #6392
Closes #6393
Closes #6394
Closes #6395
Closes #6398
Closes #6399
Closes #6401
Closes #6404
Closes #6405

## Verification

- 484 project-build tests
- 62 CLI tests
- 35 Builder browser tests
- 25 SDK tests
- project-build, Builder, CLI, and SDK type checks
- root lint and generated runtime contracts
2026-09-17 10:16:11 +02:00
Oleg Isonen aa1587c100 fix: Clarify publish timeout errors (#6406)
## Summary

- detect pre-publish HTTP timeouts from the response metadata already
attached to `TRPCClientError`
- show a clear publish-specific message instead of the JSON parser error
- cover both HTTP 504 and Vercel timeout responses

## Why

When `build.contentDatabasePublishDiagnostics` exceeds the serverless
function duration, the proxy returns HTML or plain text. tRPC's JSON
parser fails, but the resulting client error still contains the original
HTTP response. The publish flow now uses that response to report:

> Pre-publish checks timed out. Publishing was not started. Please try
again.

This PR intentionally does not change the shared tRPC transport or claim
to solve the underlying diagnostics performance problem.

## Verification

- `pnpm --filter @webstudio-is/builder exec vitest run --project
core-browser-builder-features
app/builder/features/publish/publish-error.test.ts`
- `pnpm --filter @webstudio-is/builder typecheck`
- `pnpm exec oxlint --deny-warnings <changed files>`
- `pnpm exec oxfmt --check <changed files>`
2026-09-17 09:30:08 +02:00
Oleg Isonen b7a11e4bc2 feat: Delay canvas scripts until resources render (#6380)
HTML Embed scripts in canvas and preview now wait until the complete
resource queue settles. Their markup remains rendered while loading;
only executable scripts are delayed, so scripts can read the committed
resource-backed DOM without requiring a custom event.

## Implementation

- Add an internal `$resourcesState` atom with `pending` and `settled`
states, driven by the complete resource queue.
- Synchronize the atom from the Builder to the canvas iframe.
- At the Builder component-render boundary, pass only HTML Embed the
private prop `$ws$executeScripts={isSafeMode !== true && resourcesState
=== "settled"}`.
- In the SDK HTML Embed component, default `$ws$executeScripts` to
`true`, keep markup inert while it is false, and execute scripts after
React commits the transition to true.
- Treat failed requests as settled so scripts cannot wait forever.
- Keep the private prop out of generated component arguments and
metadata through the existing `$`-prefixed prop convention.
- Keep published rendering unchanged because published sites do not pass
the private Builder prop.
- Keep the existing standard `DOMContentLoaded` / `load` compatibility
and sequential script queue.
- Remove the canvas wrapper and component-registry override.

## Todo

- [x] Track collective resource readiness in the Builder.
- [x] Synchronize readiness into the canvas.
- [x] Delay HTML Embed scripts in both canvas and preview.
- [x] Combine safe mode and resource readiness into one private
execution prop.
- [x] Preserve rendered HTML while scripts are delayed.
- [x] Preserve pages with no resources and failed-resource behavior.
- [x] Keep the private prop out of user-facing component metadata.
- [x] Add resource-state, sync, Builder-prop, and browser regression
tests.
- [x] Review documentation impact; no user-facing documentation changes
are needed.
- [x] Review fixture impact; no fixture inputs or generated outputs are
affected.

## Verification

- SDK HTML Embed browser tests — 44 passed
- Builder private-prop tests — 15 passed
- Resource tests — 28 passed
- Sync tests — 14 passed
- React SDK, SDK components, and Builder typechecks — passed
- Focused Oxlint and formatting — passed

Closes #6379
2026-09-14 15:53:26 +02:00
Oleg Isonen 9963c95ef8 fix: Sync OAuth profile fields on login (#6376)
Closes #6375

## Summary

- Refresh username, avatar, and provider fields when an existing user
logs in through OAuth.
- Avoid unnecessary database writes when profile fields are unchanged.
- Preserve existing development-login behavior.
- Add regression coverage for changed GitHub profile data.

## Testing

- `pnpm --filter @webstudio-is/builder exec vitest run --project
core-server app/shared/db/user.server.test.ts`
- `pnpm --filter @webstudio-is/builder typecheck`
2026-09-14 12:29:10 +02:00
Oleg Isonen 2aec79774e fix: focus spacing input when popover opens (#6374)
## Description

Restore automatic focus to the CSS value input when the spacing popover
opens.

The property label became focusable after its migration to
`ResettableLabel`, making it the first tabbable element in the popover
and causing Radix to focus the label. Marking the intended value input
with `autoFocus` makes React focus it as the popover content mounts;
Radix then detects that focus is already inside its focus scope and
preserves it.

## Steps for reproduction

1. Select an element.
2. Open the Style panel spacing section.
3. Click any margin or padding value.
4. Verify focus is placed in the CSS value input.

## Verification

- [x] Builder typecheck
- [x] Prettier check
- [x] Oxlint
- [x] `git diff --check`

## Code Review

- [ ] conceptual review
- [ ] detailed review
- [ ] test on preview
2026-09-14 12:26:50 +02:00
Oleg Isonen 649ee3669d fix: Batch asset queries during project import (#6368)
## Problem

Project import sent every asset filename in one database request. Large
projects produced an oversized URL and failed before assets could
upload.

Closes #6367

## Changes

- [x] Reuse the existing encoded filename chunking rule for imports
- [x] Batch imported file lookup and restore requests
- [x] Add regression coverage for long filename lists
- [x] Review documentation impact: no user-facing documentation changes
are needed

## Verification

- [x] Builder import tests: 21 passed
- [x] Asset uploader tests: 50 passed
- [x] Builder and asset-uploader typechecks
- [x] Lint, formatting, and diff checks
- [x] Real CLI import passed the original metadata lookup and began
uploading 380 assets
- [ ] Agent evaluations were not run; they require separate approval

The real import later reached the target project's separate 350-asset
limit. That limit is outside this fix.
2026-09-11 23:33:09 +02:00
Oleg Isonen 5d34b77fac feat: Improve collection entry authoring (#6361)
Collection authors and editors get clearer field help, direct entry
navigation, and actionable validation instead of warnings that point at
the wrong place.

Closes #6360

## Implementation

- [x] Keep resettable help open after a click while the label remains
hovered
- [x] Stop repeating the property label inside resettable help
- [x] Store JSON Schema field descriptions and show them in entry forms
- [x] Add an optional dynamic collection entry page for explicit canvas
navigation
- [x] Rename entry file actions to **Edit file**
- [x] Add **Open on canvas** to entry menus and Entry settings
- [x] Put the entry filename in the Entry settings title
- [x] Make collection validation banners explain the problem and open
the first affected entry
- [x] Remove false output-only `UNOBSERVED_FIELD` warnings while keeping
filter and sort diagnostics
- [x] Encourage useful field descriptions in general MCP collection
guidance
- [x] Update Content Engine documentation
- [x] Confirm no database migration is required
- [x] Regenerate the affected asset-query runtime fixture
- [ ] Visually review the affected Storybook states in light and dark
themes
- [ ] Run the complete local agent evaluation suite
- [x] Run broader package and Builder checks
- [x] Complete final diff review

## Technical notes

- `entryPageId` lives in `collection.json` under `x-webstudio`; no
database schema changes are needed.
- Entry creation still leaves the current canvas unchanged. Canvas
navigation only happens after the user selects **Open on canvas**.
- An entry page must contain exactly one URL parameter. The entry
filename supplies that parameter, so the page can identify the selected
entry.
- Output projection fields are schemaless and may be produced after
reference resolution, so catalog absence is no longer reported there.
Filter and sort fields still report catalog diagnostics.
- The structured-query runtime change affects the generated
`webstudio-features` fixture, which is regenerated in this PR.

## Verification

- 561 Content Engine tests
- 2,413 Project Build tests
- 253 Design System tests
- 1,794 Builder tests
- 67 focused Builder regression tests after the final navigation change
- 11 ResettableLabel browser tests
- 128 focused MCP tests
- Builder, Content Engine, Design System, and Project Build typechecks
- Repository lint and package-boundary checks
- Generated documentation checks
- Full workspace fixture build with `pnpm -r fixtures:build`
- Formatting and diff checks
- New regression tests were demonstrated failing before their fixes and
passing afterward

## Documentation impact

- [x] Updated the Content Engine guide for field descriptions, dynamic
entry pages, actionable validation, **Edit file**, and **Open on
canvas**
- [x] Updated MCP guidance so collection fields include editor-facing
descriptions
2026-09-11 19:25:04 +02:00
Oleg Isonen 39c290bfa7 fix: resolve MCP-reported runtime and component issues (#6362)
## Summary

- harden MCP runtime behavior around asset uploads and resources, HTTP
responses, component and Content Block application, data reads, and
Chromium screenshots
- reject shared Slots inside Content Block templates and avoid unsafe
unused-asset findings when Content Blocks can hide MDX dependencies
- expand named grid-area values according to CSS shorthand fallback
rules
- add a consent-safe YouTube preconnect control and only warm origins
that are actually used
- add focused and end-to-end regression coverage for the reported paths

## Verification

- project-build: 2,419 tests passed
- css-data: 4,623 tests passed, 1 skipped
- sdk-components-react: 134 tests passed, 1 skipped
- high-impact CLI fixture: 7 tests passed
- Builder asset REST service: 22 tests passed

Closes #6336
Closes #6339
Closes #6353
Closes #6354
Closes #6355
Closes #6356
Closes #6357
Closes #6358
Closes #6359
2026-09-10 21:32:14 +02:00
Oleg Isonen eb61139e5a feat: Scale publishing allowance with workspace seats (#6352)
Builder already counts production builds for the project owner,
including publishes created through MCP and CLI. This change scales the
allowance used by Builder with the owner's paid seat capacity, so five
seats at 100 publishes each give 500 publishes per day. Free stays at
10.

Closes #6351

## Implementation

The existing `userPublishCount` endpoint still reads the owner-wide
`user_publish_count` view. For a project, it now returns the project
owner's base allowance multiplied by the owner, included member seats,
and purchased extra seats. Builder uses that returned allowance in its
existing publish UI.

The count remains owner-wide. MCP and CLI publishes contribute to it
because they create production build records, but their publish
endpoints do not enforce this Builder-side limit. No database, server
publish-path, dependency, fixture, or generated-file changes are
included.

## Checklist

- [x] Calculate the paid allowance from the owner, included seats, and
purchased extra seats.
- [x] Keep Free at 10 publishes per day.
- [x] Reuse the existing owner-wide publish count.
- [x] Use the calculated allowance in Builder.
- [x] Review documentation impact; no Builder documentation changes are
needed for this small allowance update.
- [ ] Update the pricing page to explain the publishing allowance and
how seats increase it.
- [x] Review fixture impact; fixture inputs and outputs are unchanged.
- [x] Review the final diff for unnecessary changes.

## Verification

- The project router tests pass, including the five-seat 500-publish
allowance.
- The new assertion fails against the previous implementation and passes
with this change.
- Builder browser tests passed.
- Project and Builder typechecks passed.
- Formatting, lint, and package-boundary checks passed.
- All GitHub Actions workflows passed.
- Agent evaluations do not cover this flow and were not run.
2026-09-10 18:39:54 +02:00
Oleg Isonen e69a3d2f8e feat: Create structured MDX entries from collection folders (#6317)
## Paragraph editing follow-up — 42a16db02c (September 9)

Nested formatted paragraphs now retain their text, links, styling
identity, and existing labels during editing and saving. No database
migration.

- [x] Review all four changed text-editor files.
- [x] Preserve text before and after nested links inside emphasis,
strong text, and spans.
- [x] Preserve existing instance labels on save and keep inherited
formatting from overwriting a link's styling identifier.
- [x] Demonstrate regression failures without each fix, then pass all 41
focused text-editor and MDX synchronization tests.
- [x] Pass Builder typecheck, lint, formatting, and diff checks.
- [x] Verify the reported paragraph in Design and Content modes: edits
reach MDX and survive reload; original text restored. Verify matching
link color and underline inside and outside editing.
- [x] Review documentation and fixture impact: this restores existing
documented behavior; no fixture inputs, generated output, or
documentation changes are needed.
- [x] Commit and push the reviewed fixes.
- [ ] Confirm CI on this commit before merging.

Full E2E and agent evaluations were not rerun for this focused
follow-up. Earlier CI and suite results below apply to their recorded
commits, not this new head.

---

## Final verification — 50093ed2b7 (September 9)

Article edits now retain inline formatting and save newly inserted
custom components reliably. Saving a file no longer sends a second
project-sync write that could restore an older revision. No database
migration.

- [x] Fix iframe-blur saves, inherited template defaults, unused
resolved assets, and stale template tag metadata.
- [x] Remove duplicate server writes for already saved file revisions;
share the result with the canvas using the existing external-content
sync channel.
- [x] Demonstrate new regression tests fail without their fixes and pass
with them. Keep E2E file-write, content-order, and reload assertions;
remove the obsolete duplicate metadata-write wait.
- [x] Pass all 2,955 Builder tests, all 2,409 Project Build tests, and
all 8 focused MDX E2E checks.
- [x] Pass Builder and Project Build typechecks, lint, formatting, and
diff checks.
- [x] Run the complete fixture pipeline with no generated changes. The
later Builder-only save-acknowledgment changes affect no fixture inputs
or outputs.
- [x] Verify live article fields, hero replacement/save/reload/restore,
Accordion text edits, and YouTube URL edits. Verify UI edits reach MDX
and MDX edits persist after reload. Restore original article content.
- [x] Review documentation impact: these fixes restore the documented
Content Block editing behavior; no further documentation change is
needed.
- [x] Apply `visual-change-approved` after the user's explicit approval
of the 24 reviewed intended visual changes.
- [x] Commit and push the reviewed changes; worktree is clean.
- [x] Confirm CI and mergeability on this final commit: all 19 Main
workflow jobs passed, including all six E2E shards; PR lint and
submodule checks passed. Visual approval run 34383497017 passed. Its
predecessor reported the 24 intended differences; all 24 current images
were byte-identical to the reviewed report, with zero capture errors.
GitHub reports no merge conflict.

Agent evaluations were explicitly skipped for these final runtime fixes,
as requested. Earlier evaluation results below apply to their recorded
commits, not this final commit. This summary supersedes historical
pending-check notes below. The PR has not been merged.

---

## Final merge check — 9bc31ca679 (September 9)

- [x] Merge main without rewriting branch history. Preserve main's
image-picker fix and description-list validation.
- [x] Reset inherited HTML parent context at template boundaries. All
four new regressions fail without the fix and pass with it.
- [x] Fix shared navigation style composition and alignment; verify the
browser regression fails before and passes after. Review focused
screenshots.
- [x] Pass 2,408 Project Build tests, 251 design-system tests, and 3
image-picker tests; Builder, Project Build, and design-system
typechecks; lint, formatting, and diff checks.
- [x] Run the complete fixture pipeline with no generated changes.
- [x] Rerun all six agent evaluation scenarios on the merged code with
GPT-5.5. All functional checks pass; incompatible/missing token-baseline
comparison remains explicitly disabled.
- [x] Review documentation impact: this merge preserves documented
behavior; the image-editing guidance was already updated in f90e39cfcc.
- [x] Commit and push; worktree is clean and GitHub reports no merge
conflict.
- [x] Confirm Main CI on 9bc31ca679: all 19 jobs passed, including all
six E2E shards.
- [x] Review final visual artifact 10110845203 from run 34367911826: 24
added/changed stories, zero capture errors. Reviewed collection dialogs
and icons, light/dark login gradients, dashboard and project-settings
navigation, panel spacing, button variants, inset lists, and resettable
labels. Fourteen captures are byte-identical to the previously inspected
CI images. Updated navigation and collection-settings captures were
inspected; the formerly blank story renders normally. Pixel measurements
confirm the columns story retains its intended column positions (second
column x=261, third around x=388).
- [x] Apply visual approval after renewed explicit user approval.
Final-head CI is tracked above.

The live hero replacement and article/custom-component checks below are
now complete. The PR has not been merged.

---

## Merge-readiness follow-up — September 9

- [x] Remove contradictory image guidance and add an executable
writable-source/read-only-alt binding recipe. Regenerate CLI/MCP docs.
- [x] Verify the recipe regression fails with the old guidance and
passes with the new guidance. All 10 focused documentation tests, 2
content-reference tests, CLI/docs typechecks, lint, formatting, and
generated-documentation checks passed.
- [x] Rerun all six agent evaluation scenarios with GPT-5.5: all
functional checks passed. The incompatible/missing token-baseline gate
was explicitly disabled; existing baselines are unchanged.
- [x] Commit the documentation follow-up as f90e39cfcc.
- [x] Review existing CI screenshots and identify unintended shared-list
alignment changes. Implement a local shared-style composition/alignment
fix with a regression test demonstrated failing before and passing
after; all 251 design-system tests and its typecheck passed.
- [x] Visually verify and push the shared list fix in 9bc31ca679. The
focused run compared 28 stories; navigation is left aligned, column
layouts remain intact, and the previously blank collection-settings
story rendered normally. No product fix was inferred from that one blank
capture.
- [x] Review and approve the intended visual differences. See the
current final-head CI status above.
- [x] Verify these changes affect no fixture inputs or generated fixture
output. No database migration.

The previously pending live hero-swap and article/custom-component
checks are now complete. See the current verification summary above.

---

## Article editing follow-up — d307c8ba3d (September 9)

The target blog's hero source was incorrectly marked read-only. It now
uses the existing writable image picker. Reading time and the author URL
also use direct writable values. Time properties now have native
date/date-time controls. No database migration.

- [x] Fix the target's hero source, reading-time structure, and author
URL bindings while preserving the current content and link destination.
- [x] Verify Content-mode category, title, excerpt, date, reading-time,
shared image Description, author name/URL, MDX heading, and list-item
edits reach their source files. Check reloads and restore test values.
- [x] Add date-only, local timestamp, UTC timestamp, empty-value, and
legacy-value regression coverage; demonstrate failure without the date
control and passing results with it.
- [x] Fix the macOS Bash runner's empty-argument failure. Demonstrate
default invocation and argument-forwarding regressions fail without
their behavior and pass afterward.
- [x] Update authoritative Content Block/Time docs and generated CLI/MCP
guidance: inventory every article field, use direct writable bindings
and appropriate controls, check saved source and reload, and never infer
full editability from one heading.
- [x] Pass 291 date/text/Time/design-system tests (one existing skip), 2
runner tests, and 9 documentation tests; relevant typechecks, lint,
package boundaries, formatting, and diff checks.
- [x] Run the complete fixture pipeline: no generated fixture changes.
The later runner/docs-only edits do not affect fixture inputs or
outputs.
- [x] Run the full Builder E2E suite: 82 passed. This used an explicit
reporter; the default invocation correction was then covered by the
runner tests.
- [x] Run all six agent evaluation scenarios on gpt-5.5 after the final
image guidance correction. All functional checks passed. The older-model
token-baseline gate was disabled explicitly; accepted baselines were not
changed.
- [x] Review, commit, and push code and generated documentation.
- [x] With explicit approval, replace the live hero image through
Content mode, verify the MDX reference and reload, then restore and
verify the original image.
- [x] Complete the article-field checks listed above. Insert Accordion
and YouTube from templates; verify UI edits reach MDX and MDX edits
persist after reload. Restore the original article content.
- [x] Inspect CI for 7834d90a61: formatting, lint, typechecks, generated
docs, package/Builder tests, build checks, and five E2E shards passed.
The long MDX lifecycle exhausted its total 120-second budget at its
final assertion; the trace showed completed edits and reloads, not a
stalled save.
- [x] Give only that lifecycle a 180-second total budget; leave
individual save waits and assertions unchanged. Both local repeats
passed (plus setup). Push d307c8ba3d; this test-timeout-only follow-up
affects no fixture inputs or generated output.
- [x] Verify Main CI for d307c8ba3d: all 19 jobs passed, including all
six E2E shards. Visual approval remains separate.
- [x] Finish visual review and approval after correcting navigation
alignment and verifying the collection-settings story renders. The user
approved the reviewed 24 intended differences.
- [x] Recheck target publication preparation: seven documents included,
zero omitted, zero missing-template omissions. No deployment.
- Deferred: manual Storybook/screenshots; not authorized for this pass.

These results supersede the earlier pending image-product decisions and
live-check notes. Evaluation status for the latest fixes is recorded
above.

---

## Blog authoring fixes — 6359f979a3 (September 9)

This review fixes failed UI-to-MDX saves, missing source Undo/Redo,
editor recovery and focus, and publication preparation for the migrated
blog. No database migration.

- [x] Stop treating template-record ordering as a style edit; still
reject actual style changes that cannot be saved in MDX.
- [x] Share save-preparation errors with property controls across the
canvas frame.
- [x] Keep malformed MDX as an unsaved draft, with repair and discard
paths; focus the source editor when opened from the Navigator.
- [x] Enable supported Content-mode Move actions using the existing
central permission rules.
- [x] Keep source Undo/Redo separate from transient rendering history.
Serialize rapid commands, wait for pending canvas edits, reject
stale-source conflicts, and retain the last 20 edits per project
session.
- [x] Fix publication candidate discovery for projected documents and
unrelated author references; keep rejecting unsupported references used
as the actual MDX source.
- [x] Demonstrate regression tests failing without their fixes and
passing afterward.
- [x] Run the complete Builder (2,938), Content Engine (559), and
Project Build (2,395) suites: 5,892 tests passed.
- [x] Pass relevant package typechecks, root lint, formatting, package
boundaries, and diff checks.
- [x] Run the full fixture pipeline; no generated fixture changes.
- [x] Review documentation impact and document draft recovery and source
Undo/Redo.
- [x] Verify live heading edits, author-file edits, malformed-draft
recovery, and immediate delete/Undo/Redo; restore test content and
confirm persisted source.
- [x] Verify target publication preparation: seven documents included,
zero omitted, no missing-template omissions. This did not deploy the
site.
- [x] Review, commit, and push.

### Remaining verification and decisions

- [x] Correct the target's read-only Image source binding. The existing
Content-mode picker replaces the article reference; shared Description
edits use Asset settings. No new image-editing API or data model is
needed. See the latest verification limits above.
- [x] Repeat the full E2E and agent evaluation suites after these
changes: 82 E2E tests and all six evaluation scenarios passed.
- [x] Repeat the live Accordion/YouTube insertion and editing flow after
the save fixes, including UI-to-MDX saves and MDX edits surviving
reload.
- Historical note: this round did not run CI or Storybook checks; later
results are recorded above.

Unknown JSX already has source-range lint diagnostics; it remains an
editable missing-template placeholder, not an unconditionally blocked
save. The target author's binding was also repaired through the UI so
Content mode can edit its referenced author file. Shared resolved URLs
remain read-only text; the image picker changes the article reference,
and Asset settings edits the shared Description.

This section supersedes earlier claims of complete verification for the
latest code; historical results below remain records of earlier runs.

---

## Sync and import verification — a2a567551c (September 9)

Ordinary `link` → `sync` → `import` now exports the current saved
Builder project with its current assets. It no longer mixes an older
published build with current files. Import uploads assets before
assigning their source folders, then restores those assignments when
importing the bundle.

- [x] Fix foldered asset imports without a database migration.
- [x] Preserve file formats, folder assignments, build metadata, and
stable repeat-sync output.
- [x] Keep explicit `--buildId` export behavior unchanged; default sync
does not require publishing.
- [x] Review implementation and demonstrate regression tests failing
before the fixes and passing afterward.
- [x] Update protocol test servers for the current Builder data
endpoint.
- [x] Review documentation impact and update CLI documentation and
README.
- [x] Run all 1,121 CLI tests and 43 HTTP-client tests, both package
typechecks, root lint, package boundaries, formatting, and diff checks.
- [x] Run the full fixture pipeline and include expected current-build
fixture changes.
- [x] Verify the real source through the local CLI: repeated sync gives
identical output; import into the supplied target succeeds. Blog listing
and article rendering were also checked during the import investigation.
- [x] Commit and push the fix.
- Deferred at user request: agent evaluations for this round. Later CI
results are recorded above.

Sync still downloads the project and missing asset files and builds the
content index locally. This is not a transfer-free operation. Default
sync exports editable-build metadata rather than published deployment
metadata; use the explicit build option when selecting a particular
build.

---

## Final review and verification — ab3a6b7c55 (September 9)

Existing entries now use the same field controls as New entry. The
author-name permission fix, field-level validation, publishing warnings,
and final cache fixes are included. No database migration.

### Completed

- [x] Review all 38 local files, including entry autosave, revision
conflicts, permissions, shared fields, collection discovery, and
publishing diagnostics.
- [x] Allow existing-folder setup without rewriting entries or rejecting
unconfigured frontmatter.
- [x] Add Entry settings with autosave, repairable invalid fields,
immutable filename slugs, and preserved MDX body/unknown properties.
- [x] Warn before publication when missing or ambiguous custom templates
omit content, including discovered dynamic sources.
- [x] Allow authorized frontmatter writes to referenced Markdown author
files and preserve error messages across the canvas-frame boundary.
- [x] Reject impossible integer limits, slugless generated-filename
patterns, and slug maximum length zero. Existing raw configurations
remain readable for repairs.
- [x] Share collection discovery across Assets, file editors, and
property controls. Builder first synchronizes project asset metadata
into the browser. The browser then groups that metadata once per update
and shares configuration/template reads, instead of repeating them for
each control. This does not remove initial synchronization or
entry-frontmatter reads. Preserve project/access isolation, refresh
retries, stale-response protection, and duplicate-filename invalidation.
- [x] Demonstrate new regressions fail before fixes and pass afterward.
- [x] Correct the folder-drag E2E's obsolete root-folder assumption and
verify remembered-folder persistence.
- [x] Review and update authoritative Content Engine and Content Block
documentation.
- [x] Merge current main and regenerate the conflicting CLI
documentation from its source.
- [x] Fix generated previews with shared development dependencies:
invoke React Router binaries through Node, isolate each preview's Vite
cache, and forward script options correctly through npm and pnpm.
- [x] Fix a false MDX conflict when a new edit arrives immediately after
the previous save is acknowledged. Advance the local revision before
asynchronous parsing and ignore stale refresh results.
- [x] Run the full fixture link/sync/build pipeline. Generated changes
contain only the expected React Router scripts and Vite cache location.
No database migration.
- [x] Review the final diff and scan added lines for credential
patterns.

### Verification results

- Builder: **2,934 tests passed**. CLI: **1,120 tests passed**.
- Content Engine: **559 passed**; Asset Uploader: **291 passed**;
Project Build: **2,394 passed**; Design system: **250 passed**.
- The clean full workspace run passed all 35 non-CLI packages. Its two
CLI failures exposed pnpm argument forwarding; the complete CLI rerun
passed after that fix. Earlier load-related test timeouts did not recur
in the clean run.
- All workspace typechecks passed. Builder and CLI typechecks and
repository lint were repeated after their final changes. Package
boundaries, generated API checks, and the complete
generated-documentation gate passed. Documentation was regenerated from
source; the post-commit clean-file check passed.
- Full Builder E2E: **82 passed** from a fresh build, including
generated previews, collection creation/reload, MDX editing, stale
revisions, and permission checks. The isolated disposable test database
was cleaned up afterward; development data was untouched.
- Full agent evaluations: **all six scenarios passed on gpt-5.5**,
including every functional check for Markdown blogs, reference
discovery, MDX article editing, authentication, fonts, and design input.
The account cannot use the old **gpt-5.4-mini** baseline model. Five
baseline comparisons are incompatible and the MDX scenario has no
accepted baseline; token-baseline gating was disabled explicitly.
Accepted baselines are unchanged.
- New preview and MDX regressions were demonstrated failing before their
fixes and passing afterward.
- Working-tree/diff checks passed. Main was merged without rewriting
branch history. CI was not checked, as requested.

### Final delivery checklist

- [x] Finish the full Builder E2E rerun.
- [x] Finish the full agent evaluation rerun with the authorized
accessible model.
- [x] Commit, verify the clean generated-documentation gate, and push.
GitHub reports the branch mergeable with current main.

No known code or functional-test blocker remains from this review. CI
was not checked at the user's request. Manual Storybook/screen-reader
checks remain deferred; the automated E2E and agent visual checks above
passed.

The historical review sections below retain their original run results.
This section supersedes earlier claims about strict entry validation,
entry editing, browsing reads, and evaluation authorization.

## Outcome

Content editors can create structured MDX entries from a collection
folder without writing frontmatter. Designers configure flat fields,
limits, optional slug behavior, and the Markdown template in the
Builder.

## High-level goals

- [x] Keep folders ordinary in the database and derive collection
behavior from a direct **collection.json**.
- [x] Add **Use as content collection** to folder creation.
- [x] Give designers a visual configurator for the JSON Schema and MDX
template.
- [x] Show a collection badge and a generic **New entry** action.
- [x] Generate independent MDX entries from the configured schema and
template.
- [x] Keep the current page unchanged after creating an entry; no
automatic preview navigation.
- [x] Select direct MDX entries with URLPattern filename rules; keep
ignored files as ordinary supporting assets.
- [x] Keep reserved collection files out of collection query results and
generated content indexes.
- [x] Preserve broken collections as visible, repairable collection
folders.
- [x] Restore normal folder behavior when **collection.json** is
removed.

## Implementation todos

- [x] Add the Content Engine collection contract, default
schema/template, slug normalization, validation, serialization, and
entry generation.
- [x] Discover collections from Assets files without a database folder
type or migration.
- [x] Create **template.mdx** and **collection.json** when the folder
checkbox is selected.
- [x] Add basic field controls for text, long text, slug, number,
integer, and Boolean values.
- [x] Support required fields, string length limits, numeric limits,
template defaults, and generated slugs.
- [x] Add designer collection settings and template editing.
- [x] Remove dynamic preview-page configuration and ignore its legacy
metadata.
- [x] Add the schema-generated **New entry** form and creation endpoint.
- [x] Preserve reserved-file portability in authenticated export/import
while excluding it from content query and generated-index results.
- [x] Document the feature in the authoritative Content Engine guide.

## Deep review checklist

A checked item means the area was inspected and evidence was recorded.
It does not mean the behavior passed. Unresolved defects and product
decisions remain listed in **Review findings**.

### 1. Product contract

- [x] Decide whether the collection checkbox creates defaults
immediately or opens the configurator first.
- [x] Decide whether existing folders can be converted through the UI.
- [x] Define collection activation when **collection.json** exists but
is invalid.
- [x] Define an entry: every valid direct MDX child or only files
created through **New entry**.
- [x] Confirm collection membership is direct-child only and nested
folders can define their own collections.
- [x] Define designer, content editor, viewer, service, CLI/MCP,
old-client, and direct-API authority.
- [x] Decide whether content mode is simplified UI or a server
authorization boundary.
- [x] Decide whether slugs are permanently immutable.
- [x] Decide whether schema changes may invalidate existing entries or
must migrate them.
- [x] Decide whether invalid unused collections block unrelated queries
or whole-project publication.
- [x] Decide what happens to the preserved template after collection
removal.
- [x] Define the promised JSON Schema dialect and supported subset.
- [x] Decide whether temporary invalid collection states are admitted
for repair.
- [x] Define duplicate-request semantics: no duplicates, exactly one
success, and retry behavior.
- [x] Decide whether entries require valid frontmatter only or valid
complete MDX.

### 2. State machine

- [x] Review ordinary folders and root-level **collection.json**.
- [x] Review empty-folder, template-only, config-uploading, and
config-loading initialization states.
- [x] Review ready collections.
- [x] Review invalid JSON, UTF-8, size, schema, and duplicate-config
states.
- [x] Review missing, duplicate, wrong-type, oversized,
invalid-frontmatter, and invalid-MDX template states.
- [x] Review forbidden direct files, invalid entries, and slug/filename
mismatches.
- [x] Distinguish transient read/network failures from persistent
invalid content.
- [x] Review removing, removed, moved, renamed, restored, duplicated,
and deleted collection states.
- [x] For every state, inspect visibility, allowed actions, server
admission, query/publish behavior, recovery, and concurrent-client
behavior; record recovery behavior.

### 3. Activation and deactivation paths

- [x] Review checkbox creation.
- [x] Review create/upload/rename/move/paste/duplicate of
**collection.json**.
- [x] Review restore, import, project duplication, and sync behavior.
- [x] Review delete/rename/move/replace of **collection.json**.
- [x] Verify all activation paths produce the same state and validation.
- [x] Verify all deactivation paths restore ordinary-folder behavior
without accidental data loss.

### 4. Folder membership and nested collections

- [x] Verify only direct children are collection entries or reserved
files.
- [x] Verify a nested folder with its own direct config becomes its own
collection.
- [x] Verify parent rules do not leak into nested folders.
- [x] Define filename and extension case sensitivity.
- [x] Define duplicate logical-name behavior over generated storage
names.
- [x] Define how uploading, deleted, and stale assets affect folder
state.
- [x] Review moving entries out and between collections with different
schemas.
- [x] Review ordinary subfolders with arbitrary files inside a
collection.
- [x] Review template behavior after collection removal.

### 5. Roles and authorization

- [x] Review config/template listing and download for every role.
- [x] Review config/template content edits for every role.
- [x] Review config/template rename, move, restore, and deletion for
every role.
- [x] Review entry create/edit/rename/move/delete/restore for every
role.
- [x] Review generic upload and subfolder operations for every role.
- [x] Review collection removal and repair for every role.
- [x] Verify server enforcement separately from hidden or disabled
controls.
- [x] Recheck permission changes while operations are in flight.

### 6. Mutation surfaces

- [x] Review REST upload-ticket creation and upload completion.
- [x] Review asset-content replacement and asset metadata changes.
- [x] Review runtime add/update/duplicate operations.
- [x] Review sync patches and direct persistence helpers.
- [x] Review clipboard, drag/drop, move, rename, and duplicate paths.
- [x] Review import/export, restore, and project/folder duplication
paths.
- [x] Review delete-unused-assets and recursive folder deletion.
- [x] Verify invariants at the final persistence boundary, not only in
UI preflight.

### 7. Concurrent operations

- [x] Review create entry against schema save, template save, raw config
edit, and collection removal.
- [x] Review edit/delete/restore entry against schema and template
changes.
- [x] Review two collection-settings editors and raw editor versus
configurator.
- [x] Review schema writer A interleaved with template writer B.
- [x] Review upload/move/rename against collection activation and
removal.
- [x] Review template/config deletion against creation and publication.
- [x] Review folder deletion/move and project switch against all async
operations.
- [x] Review final validity, conflict detection, cleanup, user outcome,
cache invalidation, and publish behavior across the implemented
intersections; record conflict and recovery behavior.
- [x] Review retry after the server commits but the HTTP response is
lost.

### 8. Collection initialization and recovery

- [x] Review project switch, permission revocation, dialog close, folder
rename/move/delete, and conflicting uploads during initialization.
- [x] Verify retry is idempotent and does not duplicate reserved files.
- [x] Verify partial setup has a visible finish, retry, or cleanup path.
- [x] Verify generic actions cannot corrupt the initialization window.
- [x] Verify project and folder identities are captured for the whole
operation.
- [x] Review asset-count, storage, filename, and folder limits with
cleanup.

### 9. JSON Schema conformance

- [x] Confirm the exact draft and validate configs against its
meta-schema.
- [x] Review unknown dialects, boolean schemas, malformed keyword types,
and duplicate JSON keys.
- [x] Review refs/defs, recursion, composition, conditionals,
dependencies, and nullable/multiple types.
- [x] Review enum, const, format, pattern, patternProperties, and
additionalProperties.
- [x] Review min/max properties, array constraints, contains, and
uniqueItems.
- [x] Review exclusive numeric bounds and all string/number/integer
limits.
- [x] Differential-test validation against an independent draft 2020-12
implementation.
- [x] Verify unsupported keywords are rejected or explicitly documented,
never silently ignored.

### 10. Schema resource limits and hostile input

- [x] Bound schema bytes, depth, field count, enum size, and reference
depth.
- [x] Bound validator compilation and validation time.
- [x] Review recursive references and excessive composition branches.
- [x] Review catastrophic patterns and regex denial of service.
- [x] Review huge labels, keys, defaults, and values.
- [x] Review prototype-sensitive and structurally awkward field names.
- [x] Review memory and CPU amplification across many collections.

### 11. Configurator ownership and round trips

- [x] Define owned, preserved, read-only, and rejected schema paths.
- [x] Verify parse/save/parse semantic equivalence and repeated-save
idempotence.
- [x] Verify a UI edit changes only explicitly owned schema paths.
- [x] Review property/form order and required-array order.
- [x] Review unknown root, property, and Webstudio extension metadata.
- [x] Review editable primitive fields that also contain enum, const,
format, composition, readOnly, or custom constraints.
- [x] Review type changes for incompatible preserved or removed
keywords.
- [x] Review rename/removal collisions with unsupported properties and
requirements.
- [x] Surface hidden preserved rules that can cause unexplained
validation errors.
- [x] Review field ordering/reordering.
- [x] Review choosing/changing slug field, slug source, and template
filename.
- [x] Review turning newly added fields into slug or slug-source fields.

### 12. Required/default/unset semantics

- [x] Review absent, empty string, false, zero, null, default, and
user-cleared values for every field type.
- [x] Define required-property versus non-empty-value behavior.
- [x] Verify required Boolean false remains valid and understandable.
- [x] Review optional Boolean absence versus explicit false.
- [x] Review explicitly clearing template-backed values.
- [x] Review JSON Schema default as annotation versus persisted entry
value.
- [x] Verify precedence among template values, schema defaults,
generated slug, and user values.
- [x] Review hidden/non-renderable required fields and template
requirements.
- [x] Verify a collection cannot be ready when every entry form must
fail.

### 13. Schema evolution and migration

- [x] Review add/remove optional and required fields.
- [x] Review field rename and label-only changes.
- [x] Review type changes and tightened/relaxed limits.
- [x] Review enum option, default, slug field/source, template name, and
additionalProperties changes.
- [x] Verify compatible save ordering and identify impossible two-write
migrations.
- [x] Decide whether entries are rewritten and whether migration is
atomic.
- [x] Review entry changes after validation but before schema commit.
- [x] Ensure designers see all incompatible entries or an actionable
summary.

### 14. Template, YAML, and MDX

- [x] Review absent/empty frontmatter and empty YAML.
- [x] Review BOM, CRLF, final-newline, and alternate YAML delimiter
behavior.
- [x] Review duplicate keys, anchors, aliases, tags, comments, quoting,
and multiline strings.
- [x] Review Unicode and byte limits.
- [x] Verify frontmatter and starter-body preservation.
- [x] Review invalid MDX bodies, imports, exports, expressions, and
unsafe nodes.
- [x] Review missing, renamed, duplicate, wrong-type, and oversized
templates.
- [x] Verify template changes affect future entries only.
- [x] Review reserved template exposure through direct asset URLs and
build copying.

### 15. New-entry form and creation

- [x] Verify every required field is renderable or supplied safely.
- [x] Verify deterministic field order and correct controls/constraints.
- [x] Compare client and authoritative server validation.
- [x] Prevent submitted values from overwriting protected hidden fields.
- [x] Preserve values and focus after failed creation.
- [x] Review per-field errors, error summary, and first-error focus.
- [x] Prevent duplicate submission and define lost-response recovery.
- [x] Verify local sync, reload persistence, and project-switch
handling.
- [x] Review no/stale preview page, query delay, and draft-filtered
entries.
- [x] Review large forms and narrow/mobile layouts.

### 16. Entry editing and lifecycle

- [x] Review body-only, frontmatter-only, and combined edits.
- [x] Review invalid intermediate frontmatter and invalid complete MDX.
- [x] Review slug change, filename rename, and reference consequences.
- [x] Review delete, restore, move out, move between collections,
duplicate, paste, and undo.
- [x] Review slug reuse after delete and restore collision.
- [x] Review edits concurrent with schema/template changes.
- [x] Review repair of legacy invalid entries and blocked intermediate
saves.
- [x] Decide whether existing entries receive a generated settings form
or raw MDX editing.

### 17. Slug and filename identity

- [x] Review slug source selection, same slug/source field, manual
override, and visible final normalization.
- [x] Enforce lowercase-dash identity independently of editable schema
metadata.
- [x] Review empty normalized slugs and template/schema slug defaults.
- [x] Review diacritics, non-Latin scripts, and emoji-only sources.
- [x] Use locale-independent case comparison and Unicode normalization.
- [x] Review character/byte limits and case-insensitive filesystems.
- [x] Review collisions with reserved config/template filenames.
- [x] Review concurrent creation, stale reservations, deletion, reuse,
restoration, and URL encoding.

### 18. Collection-root restrictions

- [x] Review upload, external drop, internal drag, generic text
creation, paste, duplicate, move, rename, and extension changes.
- [x] Review runtime add, sync patch, import, and restore bypasses.
- [x] Review upload tickets completed after activation.
- [x] Review moving or renaming **collection.json** through metadata
changes.
- [x] Review dedicated entry creation, initialization, repair, body
editing, and collection removal exceptions.
- [x] Verify subfolder creation and arbitrary files inside subfolders
remain allowed.

### 19. Storage, database, idempotency, and cleanup

- [x] Review object-without-File, File-without-Asset, stale UPLOADING,
and soft-deleted states.
- [x] Review storage success/database failure and database
success/storage failure.
- [x] Review postcheck failure, object cleanup, row cleanup, and cleanup
failure.
- [x] Verify cleanup preserves the original error and cannot delete
another request's asset.
- [x] Review timeout/lost response after commit and safe retries.
- [x] Review reservation lookup/cleanup failure and expiration.
- [x] Review failed creation cleanup and distinguish incomplete uploads
from existing entries with repairable field errors. Existing field
errors do not hide entries or block publication.
- [x] Verify orphan reclamation and project-scoped cleanup.

### 20. Query, build, and publication

- [x] Verify config/template exclusion only for an identified
collection.
- [x] Verify ordinary root-level **collection.json** remains ordinary
content.
- [x] Review template queryability after collection removal.
- [x] Validate actual entry frontmatter and decide complete-MDX
requirements.
- [x] Review invalid content versus transient read failure.
- [x] Decide invalid-collection blast radius across queries, field
catalog, build, and publish.
- [x] Review direct asset IDs, document references, build copying, and
public URLs for reserved-file leakage.
- [x] Verify preview and publish use the same collection rules.

### 21. Cache and snapshot consistency

- [x] Verify config, template, entries, filenames, folder movement,
activation, and removal affect source revision.
- [x] Verify immutable/revision-pinned reads under concurrent swaps.
- [x] Verify config and template come from one logical version.
- [x] Review revision consistency between entry reads and indexing.
Queries do not require entry-schema validation.
- [x] Review rejected-promise caching and retry after repair.
- [x] Verify no cross-project cache collision.

### 22. Performance and availability

- [x] Review sequential versus bounded parallel reads.
- [x] Review request cancellation and repeated preview-query work.
- [x] Review rate limits and resource-exhaustion protection.
- [x] Review progress/cancellation and actionable limit errors.

### 23. Invalid-state repair

- [x] Review repair for every config, template, forbidden-file, entry,
and slug mismatch state.
- [x] Show exact folder, file, field, and rule.
- [x] Distinguish retryable transport errors from content errors.
- [x] Provide missing-template creation despite normal root
restrictions.
- [x] Provide duplicate-file deletion and forbidden-file move recovery.
- [x] Preserve raw repair when the configurator cannot parse the schema.
- [x] Show collection health after repair.
- [x] Prevent custom-template leakage to content editors when config
cannot identify it.

### 24. Entry navigation

- [x] Remove dynamic preview configuration and automatic navigation
after entry creation.
- [x] Verify entry creation leaves the selected page unchanged, with or
without a slug field.

### 25. Accessibility and responsive behavior

- [x] Review native form submission and required semantics beyond an
asterisk.
- [x] Review linked errors, error summary, live announcements, and busy
state.
- [x] Review focus after errors, add/remove field, key edits,
confirmation transitions, and dialog close.
- [x] Review dirty-close warning, explicit cancel/retry, and durable
feedback beyond toasts.

### 26. Portability, compatibility, and rollback

- [x] Review export/import, folder/project duplication, and restore
ordering.
- [x] Verify logical filenames, not storage names, define the portable
contract.
- [x] Review case-insensitive filesystem behavior.
- [x] Review rollback after collection files already exist.
- [x] Verify removal or rollback leaves content recoverable.
- [x] Confirm database/migration assumptions.

### 27. Observability and supportability

- [x] Review state-transition and validation diagnostics.
- [x] Track cleanup failures and orphaned reservations.
- [x] Make publish errors actionable without logging private content.
- [x] Ensure client errors do not expose stack traces or sensitive
internals.

### 28. Verification strategy

- [x] Unit-test schema, slug, merge, serialization, and validators.
- [x] Demonstrate each new regression test fails without its fix.
- [x] Run affected unit suites, typechecks, lint, docs checks, E2E,
fixture-impact review, and final diff review.
- [x] Review authoritative documentation impact.

## Persistence and recovery

No database migration is needed. Folders remain ordinary database rows;
their direct **collection.json** activates collection behavior. This PR
adds no table, column, index, RPC, folder type, or backfill.

- Setup writes the template first and **collection.json** last.
Interrupted setup leaves an ordinary folder and can be retried.
- Existing immutable File revisions, conditional Asset updates, and
upload reservations provide conflict detection and retry-safe entry
creation.
- Settings saves validate the intended template and schema together,
then write only the files that changed. Existing entry field errors stay
repairable and do not block unrelated saves, queries, or publication.
New entry creation remains strict.
- Invalid or interrupted collections remain visible and repairable.
Configuration/template structure errors remain distinct from entry-field
errors; entry-field errors do not invalidate the entire collection.
- Public/service publication excludes configuration and template files.
Authenticated CLI exports retain them for lossless import.

## Review findings

The implementation review is complete. Confirmed defects were fixed and
the following tradeoffs remain explicit.

### Fixed

- Enforced collection structure and permissions across REST, runtime
patches, import, query, and publication, while keeping existing
entry-field errors non-blocking for queries and publication.
- Preserved Undo/Redo, including restoring shared File revisions in
cloned projects.
- Rejected forged shared-file metadata while preserving metadata edits
on legacy files with null uploader provenance.
- Added retry and recovery behavior for setup, settings saves, lost
responses, and transient reads.
- Moved collection setup into one retry-safe server operation and kept
the local Builder update as one Undoable transaction.
- Centralized collection inspection and limited schemas to the flat
fields the configurator can represent. Opening a collection still reads
its entries in the background to report field errors.
- Guarded stale dialogs and deferred saves against permission changes,
protected files, project switches, and replaced revisions.
- Kept Asset settings open while choosing nested folders; the existing
browser regression fails before the fix and passes afterward.
- Preserved required Boolean false values, field-level errors,
dirty-close prompts, and inline Markdown editing.
- Separated authenticated portable exports from public runtime assets.
- Updated the authoritative Content Engine guide.

### Known tradeoffs

- A failure after template content saves but before configuration saves
can temporarily leave an invalid collection. Retrying the settings save
completes it; otherwise the visible files allow repair. The
template/config rename endpoint remains retry-safe and rolls back a
rename when its config write fails.
- Cloned-project Undo can retain an unused prior File revision. Separate
read-then-delete cleanup could race with another restore, so this path
retains the revision.
- Build/asset persistence and import already use multiple calls. This PR
validates before writes and provides retry/conflict handling; it does
not provide a transaction spanning every resource or a global collection
lock.
- Opening a collection loads its configuration and template through
shared Builder discovery, then checks entry frontmatter in the
background for field errors. Unchanged configuration/template content is
reused across controls and entry edits. Frontmatter checks still require
entry reads; ordinary folder browsing does not discover every
collection’s file content.

## Latest unstaged-change review — 2026-09-07

- [x] Review collection settings, validation, autosave/error recovery,
entry creation, reserved-file actions, and conversion flows.
- [x] Review shared labels, list keyboard handling, dialog focus/Escape,
buttons, and panel spacing migrations.
- [x] Fix Enter/Space list activation lost when arrow navigation
replaced the existing press handler.
- [x] Recognize historical generated ASCII/Unicode slug patterns, use
the bundled Unicode slug schema, and save a locally resolved $ref
without changing existing filenames.
- [x] Prevent duplicate slugless entries after a lost response: New
entry sends a stable UUID per attempt, reused by the repository's
existing filename/content retry checks. No database migration. Callers
omitting the optional requestId retain the previous behavior.
- [x] Preserve Content Block template validation independently of page
HTML placement, without accepting invalid rendered nesting.
- [x] Demonstrate the new review regressions fail without their fixes
and pass afterward.
- [x] Review authoritative documentation and update legacy slug
behavior.
- [x] Run fixtures and inspect generated changes: none.
- Deferred manual verification: Storybook screenshots were not
authorized for this pass.
- Historical evaluation status: not run in this pass; superseded by the
final verification section above.

## Verification

Local checks for commit **2b8195692e**:

- Builder app: 1,739 tests; Builder core: 1,150 tests. After the final
fixes, entry/settings tests and shared asset REST checks also passed,
including the added stable-retry test.
- Content Engine: 535 tests.
- Asset Uploader: 279 tests.
- Design system: 249 tests.
- Project Build: 2,392 tests.
- All five affected package typechecks, changed-file lint/formatting,
package boundaries, and Content Engine documentation tests passed.
- Complete fixture link/sync/build pipeline passed with no tracked
fixture changes.
- Staged diff and credential-pattern checks passed. No database schema,
migration, or generated database type changes. The lockfile includes the
collection validator and filename matcher dependencies.
- CI for this commit is pending. Builder E2E, manual
screen-reader/mobile checks, Storybook screenshots, and agent
evaluations were not run in this pass.

## MDX editing review — commit c3702a7238

- [x] Review all 36 local changed files: MDX parsing/materialization,
template enforcement, mutation commits, persistence, Assets refresh,
Navigator, source binding, editor diagnostics, dialogs, and query menus.
- [x] Validate new custom components at the shared Builder mutation
commit before applying tree changes. Cover move, reparent, paste, nested
paste, duplicate, and batched operations; preserve unchanged authored
content.
- [x] Match template names and component structure, including renamed
templates, instead of accepting any component type found in Templates.
- [x] Remove the registered-component fallback from MDX materialization
and completion; report untemplated JSX in the editor.
- [x] Preserve unresolved JSX until its placeholder is deleted, then
persist its removal without clearing the Assets resource during refresh.
- [x] Keep custom designer content outside the MDX body; omit the extra
body for fresh unconnected Content Blocks.
- [x] Resolve Navigator's MDX-file action from the active content root
for dynamic sources.
- [x] Fix the first dialog drag jump while honoring subsequent explicit
size changes; contain long query menus and prevent editor Backspace from
deleting instances.
- [x] Demonstrate new review regression failures before the fixes and
passing results afterward.
- [x] Review and update authoritative Content Block documentation.
- [x] Run the complete fixture pipeline; no generated fixture changes.
- Historical evaluation status: deferred in this pass; superseded by the
final verification section above.
- Historical verification limits: no Storybook screenshots, Builder E2E,
or manual accessibility checks in this pass. See the final verification
section for the current E2E result; manual checks remain deferred.

### Latest verification

- Builder affected suites: **624 tests passed**.
- Project Build full suite: **2,394 tests passed**.
- Design system full suite: **250 tests passed**.
- Query Builder React full suite: **14 tests passed**.
- Component Registry full suite: **7 tests passed**.
- All five affected package typechecks, repository lint, changed-source
formatting, staged diff checks, and credential-pattern scan passed.
- Fixture link/sync/build passed without generated changes. No database
migration.
- CI for this commit has not yet been verified.

The new mutation-commit check covers Builder operations affecting loaded
external content roots. It is not a claim that every remote API mutation
is now guarded by this client-side check.

Closes #6316


## Local-change review — 2026-09-08

- [x] Review all 47 changed files and trace collection setup, filename
filters, public metadata/upload APIs, sync patches, Content-mode write
targets, local folder persistence, and MCP downloads.
- [x] Fix ignored MDX files being renamed into entries through the
metadata API. Selected filenames require New entry.
- [x] Fix supporting-asset moves/renames being blocked by unrelated
invalid entries. Configuration/template checks still run. The later
entry-repair work also removed entry-field validation as a blocker for
unrelated writes and publication.
- [x] Validate frontmatter directly with Ajv, resolve the bundled slug
$ref without network fetching, preserve the flat schema contract, and
avoid retaining old validator instances.
- [x] Verify Unicode generation, legacy-pattern upgrades, sibling
constraints, field error paths, optional binding paths, referenced-file
permissions, and independent queued edits.
- [x] Review authoritative documentation, correct contradictory
referenced-write guidance, and regenerate CLI/MCP documentation.
- [x] Demonstrate new review regression failures with the fixes
disabled, then restore and pass them.
- [x] Pass Content Engine (553), asset uploader (284), SDK (570),
project-build (2,394), MCP command (61), and collection/Content-mode
browser tests (279), plus expression tests and documentation checks.
- [x] Pass seven affected package typechecks, repository lint,
formatting, package boundaries, and fixture link/sync/build. No
generated fixture changes or database migration.
- Historical evaluation status: deferred in this pass; the user
subsequently authorized the full suite. See the final verification
section above.
- Historical verification limits: no Builder E2E or manual
visual/accessibility checks in this pass. See the final verification
section for the current E2E result; manual checks remain deferred.
2026-09-09 21:31:04 +02:00
Oleg Isonen e33ce76489 fix: Keep image picker width stable and accept quick clicks (#6344)
Choosing an image now works with a quick thumbnail click, and selecting
an asset keeps the Source picker at its intended width, including long
names and nested folder paths.

The dialog's content-based width was overriding the floating panel's
width. Focusing a thumbnail widened the panel, triggering resize
handling that briefly disabled pointer events before mouse release. Pass
the floating panel styles through the dialog's `css` override so the
intended width wins. Explicit dimensions and drag/resize handlers remain
as implemented.

Closes #6343

- [x] Reproduce both failures in Chromium using the actual Source
picker.
- [x] Fix floating panel style precedence.
- [x] Add three regressions for root and nested asset selection widths
and an 80 ms thumbnail click. All three fail without the fix and pass
with it.
- [x] Run related Builder tests (50 passed), the design-system suite
(228 passed), both package typechecks, repository lint, and formatting.
- [x] Review documentation impact: the Image Source instructions already
describe the restored behavior; no update needed.
- [x] Verify no fixture inputs or generated outputs are affected.

Validation used headless Chromium component tests. Full canvas E2E and
Storybook screenshot checks were not run.
2026-09-09 12:04:52 +02:00
Oleg Isonen 722b3af113 feat: Copy links to instances from the context menu (#6342)
Right-click an instance in the Navigator and choose **Copy link to
instance** to share its full Builder URL. Opening it restores the page
and the same instance occurrence, including descendants of shared Slots.
The shared menu also exposes the action on the canvas.

Copying and opening a link use the same existing
`getDeepLinkedInstanceSelection` function, moved unchanged from
`use-switch-page.ts` into `shared/instance-utils/link.ts`, alongside URL
creation and the existing instance URL parser. It validates the instance
path and page access. The context menu and pre-publish “Show element”
links both call `getInstanceLink(instanceSelector)`. It lives in
`shared/instance-utils/link.ts` and owns validation and the complete URL
setup: project, page, full selector, origin, share token, editor mode,
and safe mode, using the existing `builderUrl`. There is no separate
link-permission implementation.

The link keeps the current share access and editor mode, clears
unrelated scroll anchors, and shows clipboard success or failure. Body
is supported; Global Root and multiple selections are unavailable.

Instance-only navigation now preserves loaded Builder data: the route
comparison recognizes the `instance` parameter as well as the older
`instanceId`. A functional regression test confirms that changing the
target does not change the data URL comparison, while changing share
access does.

MCP guidance explains how to extract the target ID from the link for
`inspect-instance`, verify the project and shared Slot context, and
avoid guessing when an instance no longer exists. This does not add a
URL-taking MCP endpoint.

1. [x] Add the menu action and reuse complete instance-link construction
with pre-publish links.
2. [x] Share existing instance-link validation between copying and
opening links.
3. [x] Update the Navigator and MCP guidance; regenerate CLI
documentation.
4. [x] Extend the existing functional test to round-trip a shared Slot
URL, including share access and editor mode. Verify it fails without the
instance parameter and passes after restoration.
5. [x] Remove the React/clipboard test harness and duplicate
permission-test matrix. Confirm no fixture inputs or outputs are
affected.

Validation: 28 focused Builder tests, Builder typecheck, repository
lint, and `git diff --check` pass on this revision. The earlier CLI
documentation checks passed and their inputs are unchanged. An earlier
GPT-5.4 mini subagent at low reasoning passed a focused native MCP test
against commit 072a8dc534: given only a link and text-edit request, it
changed the correct heading among three identical-looking headings,
leaving all other fixture records unchanged. It used four MCP calls with
broad instance/text reads. That agent test used an isolated local
fixture; it was not a production or shared-Slot agent test. Screenshots
and the full agent evaluation suite were not run.

Closes #4610
Ref #4364
2026-09-08 15:23:29 +02:00
Oleg Isonen 05706b5425 feat: Make Content Block templates the MDX authoring interface (#6307)
Closes #6306

## Outcome

Content Block templates are now the public component model for MDX
authoring.

- Standard Markdown resolves through matching Content Block templates.
- PascalCase JSX resolves to a named template first, then to a
registered component.
- Adding or changing a template immediately affects matching MDX,
including content authored before that template existed.
- Every supported standard MDX element is present in new Content Blocks
by default.
- Template `name` is a stable PascalCase JSX identifier. `label` remains
optional display text only.
- Lowercase JSX represents native HTML and SVG without exposing
`ws.element` in authored syntax.
- Unknown, ambiguous, and unsafe JSX stays in source, produces a
source-ranged Builder diagnostic, and is omitted from published output.
- Frontmatter images preserve exact `$ref` values and use the Asset
description for `alt` text.
- Keyboard and mouse insertion from the slash menu remove the trigger
slash and preserve the selected template.

## Public MDX contract

- Markdown is canonical for standard prose.
- Lowercase JSX creates native elements:
`<section><p>Text</p></section>`.
- PascalCase JSX uses templates and registered components:
`<PromotionCard />`, `<Heading tag="h1">Title</Heading>`, and `<YouTube
src="https://youtu.be/KI5JHpzBK1s" />`.
- Component-name collisions use stable qualified identifiers such as
`Checkbox` and `RadixCheckbox`.
- A self-closing template keeps its designed default subtree. An
explicitly paired empty template clears it.
- Static quoted values and bare booleans are supported.
- Imports, exports, expressions, spreads, functions, executable
JavaScript, unsafe attributes, `<$.*>`, and authored `<ws.element>` are
rejected.
- `ws` remains only for compiler primitives with no React component.

## Implementation

- [x] Add stable, unique template names and keep them separate from
labels.
- [x] Parse and validate Markdown and JSX through their ASTs with
precise source ranges.
- [x] Share component identity between template JSX, Content MDX,
Builder materialization, reload, copy, and publication.
- [x] Resolve templates live after add, edit, rename, reorder, removal,
undo/redo, collaboration updates, and reload.
- [x] Preserve authored props, children, Asset references, template
defaults, and the exact slash-menu template choice.
- [x] Make one typed MDX semantic inventory drive default templates and
slash-menu eligibility.
- [x] Move component-dependent template assembly into the component
registry.
- [x] Replace production `$`, `animation`, and `radix` JSX namespaces
with direct component imports.
- [x] Keep only explicit compiler primitives in `ws` template JSX.
- [x] Migrate repository templates, fixtures, stories, examples, MCP
guidance, CLI guidance, and generated outputs.
- [x] Add Builder unit and Playwright coverage for authoring,
diagnostics, insertion, synchronization, reload, and publication.
- [x] Review and update the authoritative Content Block and generated
MCP documentation.

## Compatibility

- Persisted project data continues to use namespaced component IDs and
`ws:element` for generic HTML elements. No project-data migration is
required.
- Legacy `<ws.element ws:tag="…">`, `<ws.element ws:name="…">`, `<$.*>`,
`<animation.*>`, and `<radix.*>` input remains readable during the
compatibility window.
- Current serializers and repository-owned sources emit only canonical
Markdown, lowercase intrinsic JSX, or PascalCase identifiers.
- Untouched user MDX is not rewritten automatically. Legacy syntax is
canonicalized when its owning source is edited.
- Deferred follow-up: remove legacy namespace readers and proxy support
only after the canonical writer is deployed and existing projects are
backfilled. This is intentionally outside this PR.

## Verification

- [x] CI package tests, typechecks, lint, package boundaries, generated
assets, migrations, and size checks pass.
- [x] All six Builder E2E shards pass.
- [x] Fixture checks pass on Ubuntu and Windows.
- [x] Targeted local Content Engine, Template, SDK, registry, Project
Build, migration, Builder, component, CLI, and Playwright tests pass.
- [x] Runtime contracts, CLI docs, and MCP docs were regenerated from
their owning sources.
- [x] Local fixture generation completed without an unexpected fixture
diff.
- [x] Documentation impact reviewed and included in this PR.
- [x] Review and approve the intentional List visual snapshot change.
- [x] Run the complete agent evaluation suite after explicit approval.
- [x] Run the network fixture link/sync pipeline against the matching PR
deployment after explicit permission.

## Known visual change

The generated List story now targets its actual default `ul` element
instead of `ol`, so the default list styling appears in the visual
snapshot. The visual change was reviewed and the approved visual check
passes.
2026-09-06 15:19:54 +02:00
Oleg Isonen 55920c57c4 fix: Show all Markdown and Assets query diagnostics (#6308)
Ref #6305

## Outcome

Show actionable Markdown, MDX, and Assets query problems in the editor,
query Diagnostics, API, and MCP.

The current implementation substantially improves source diagnostics,
query error aggregation, query scoping, exact paths, MCP feedback, and
loading states. The exhaustive audit below also records what is not
complete yet.

## Completion rule

An error state is complete only when all applicable checks pass:

- [x] The editor uses the production validator and shows every issue for
the open file.
- [x] Query execution uses the same validation and returns every issue
for every file that matches the query, not only the returned page.
- [ ] MCP can reproduce the state through a real tool call and returns
the same code, severity, message, file, and location.
- [x] Diagnostics shows fatal errors and nonfatal warnings in the
correct place.
- [x] Exact file is always present; line and column are present whenever
the parser can determine them.
- [x] Multiple issues in the same file, multiple files, and multiple
validation phases are returned together.
- [ ] A regression test proves failure without the behavior and success
with it.

## Cross-surface contract

### Required validator parity

- [x] Editor, query execution, and MCP file operations invoke the same
exported production file-validation pipeline for byte decoding,
source/frontmatter, Markdown/MDX, Content Block semantics, and
references. Copied schemas, adapter-only checks, or reimplementations do
not count as parity.
- [x] Query builder, query execution, `validate-asset-query`, and
`preview-asset-query` invoke the same exported structural and
catalog-aware semantic query validator with the same project snapshot
and context.
- [x] Every surface preserves the same complete, deterministically
ordered diagnostic array: severity, code, message, phase/scope, asset
ID, file path, line/column/range, query path, and
fatal-versus-warning/result behavior. UI, API, and MCP serializers must
not drop or remap fields.
- [ ] A table-driven contract suite calls the real editor, query, API,
and MCP entry points—including MCP upload, update, download, validate,
and preview—and compares full normalized arrays for multiple errors,
multiple warnings, multiple files, and pre-pagination matches.

- [x] Markdown and MDX source syntax/frontmatter use
validateTextAssetSource in editor, query compilation, and MCP file
tools.
- [x] Query request execution and MCP local parsing use
assetQueryRequest.
- [x] Fatal query setup errors retain all detected semantic errors and
accompanying warnings.
- [x] Nonfatal query warnings retain a stable code and exact query path.
- [x] Source diagnostics retain severity, phase, code, asset ID, path,
and available source position.
- [x] Query Diagnostics excludes diagnostics produced only by unrelated
published queries.
- [x] Query, Preview, and Diagnostics tabs show loading states.
- [x] Authenticated diagnostics can show a sanitized internal message;
public/pre-auth errors remain redacted.
- [x] Share byte-level UTF-8 validation instead of decoding separately
in query and MCP.
- [x] Make the query editor and MCP call one literal shared
query-validation function before execution.
- [x] Share cross-file reference validation across editor, query, and
MCP file operations.
- [x] Share contextual Content Block/template validation across all
applicable surfaces.
- [x] Preserve an invalid stored query in the editor and explain it
instead of replacing it with defaults.
- [x] Define and enforce whether “matches the query” includes every
pre-pagination match; current source validation follows
returned/paginated IDs.
- [x] Continue through source, reference, and runtime phases where safe
so one phase does not hide later issues.
- [x] Map every user-triggerable graph/storage/runtime failure to a
structured public error instead of INTERNAL_ERROR.
- [ ] Label candidate-file warnings separately from returned-file
diagnostics.

## File transport and encoding

- [x] Empty Markdown and MDX are accepted.
- [x] UTF-8 BOM and CRLF are accepted.
- [x] Whole Markdown/MDX file over 1 MiB is detected.
- [x] Missing or unavailable selected content is reported.
- [x] Invalid UTF-8 frontmatter returns the same structured diagnostic
in query and MCP.
- [x] Invalid UTF-8 body returns the same structured diagnostic in query
and MCP.
- [x] MCP download must use fatal UTF-8 decoding rather than replacement
characters.
- [x] Validate bytes before committing an upload, or return the
committed Asset ID and explicit cleanup state when post-commit feedback
fails.
- [x] Reject filename/format mismatches instead of allowing either hint
to bypass Markdown/MDX validation.
- [x] Storage status, missing body, invalid metadata, revision mismatch,
format mismatch, short read, and excess read each return structured file
context.
- [x] Content changing during validation has a clear retryable conflict
diagnostic.

## Frontmatter

- [x] No frontmatter.
- [x] Empty frontmatter.
- [x] Opening delimiter without a closing delimiter.
- [x] Frontmatter over 64 KiB.
- [x] Invalid YAML grammar.
- [x] Multiple YAML parser errors.
- [x] Duplicate keys.
- [x] YAML aliases.
- [x] Unsupported YAML tags.
- [x] Scalar or array root instead of an object.
- [x] Non-JSON values, NaN, Infinity, and unsafe integers.
- [x] Nesting deeper than 8.
- [x] More than 256 fields/array entries.
- [x] One string over 16 KiB.
- [x] Normalized indexed properties over 64 KiB.
- [x] Frontmatter warnings remain nonfatal and visible.
- [x] Collect all post-parse normalization/limit errors; this phase
currently stops at the first.
- [ ] Prove every state above through real MCP upload, update, download,
query, and Diagnostics paths.

## Markdown body

- [x] Treat ordinary CommonMark/GFM as permissive; malformed-looking
Markdown and raw HTML are not automatically syntax errors.
- [x] Preserve and validate the body when frontmatter is invalid.
- [x] Detect the 1 MiB body/file limit.
- [x] Handle body extraction and bounded excerpts.
- [x] Return a shared structured invalid-UTF-8 body error from every
byte-reading surface.
- [ ] Distinguish author errors from internal
excerpt-limit/configuration errors.
- [ ] Prove body-size and decoding states through real MCP and
Diagnostics.

## MDX grammar and safety

- [x] Malformed MDX/JSX grammar.
- [x] Imports.
- [x] Exports.
- [x] Executable flow expressions.
- [x] Executable text expressions.
- [x] JSX expression attributes.
- [x] JSX spread attributes.
- [x] Arbitrary components.
- [x] HTML-looking JSX outside ws.element.
- [x] Unsupported/raw MDX node types.
- [x] Duplicate attributes and normalized alias collisions.
- [x] Event-handler attributes.
- [x] srcdoc, srcset, and dangerouslySetInnerHTML.
- [x] Unsafe URL protocols in link/source/action-like props.
- [x] Forbidden tags: base, link, meta, noscript, script, style,
template, title.
- [x] Conflicting, empty, or non-static ws:name and ws:tag.
- [x] More than 20,000 nodes.
- [x] Nesting deeper than 100.
- [x] More than 4,000 props.
- [x] Multiple recoverable unsafe-mdx warnings are collected.
- [ ] Collect multiple fatal grammar/structural errors when parser
recovery can do so; unrecoverable parsing currently stops at the first
fatal error.
- [x] Preserve sibling expression warnings when unsupported JSX is also
present; {first()}, <Card />, {second()} currently reports only the Card
warning.
- [ ] Prove every state above through real MCP and Diagnostics, not only
validator unit tests.

## Content Block semantics

- [x] Unresolved template warning exists.
- [x] Unknown template prop warning exists.
- [x] Incompatible template prop warning exists.
- [x] Design-only template prop warning exists.
- [x] Stale template prop warning exists.
- [x] Invalid materialized HTML content model error exists.
- [x] Run these checks for an MDX file even when no active editor
Content Block root has materialized it.
- [x] Run applicable semantic checks in query Diagnostics.
- [x] Run applicable semantic checks for MCP upload as well as
contextual update/download.
- [x] Return all Content Block frontmatter diagnostics; one path still
throws only diagnostics[0].
- [ ] Add real MCP and UI coverage for every semantic state.

## Cross-file references

- [x] Non-string $ref marker.
- [x] Invalid reference URL.
- [x] Invalid fragment encoding.
- [x] Invalid fragment.
- [x] Invalid JSON Pointer.
- [x] Missing referenced document.
- [x] Missing referenced JSON path.
- [x] Missing referenced local Asset warning.
- [x] Unsupported target representation.
- [x] Reference cycle.
- [x] Duplicate document ID or URL.
- [x] Missing graph source or target.
- [x] Root not found.
- [x] Duplicate/unused/unresolved reference.
- [x] Invalid resolved value.
- [x] Content identity conflict.
- [x] Target revision mismatch.
- [x] Representation selector required/invalid.
- [ ] Diagnose {$ref: value, extraKey: value} as an invalid marker or
explicitly document it as ordinary data.
- [x] Collect all bad references and targets instead of stopping at the
first graph failure.
- [x] Validate references from the editor and MCP file tools, not only
query compilation.
- [x] Map graph compilation/resolution, Markdown-document, and
JSON-document errors to exact structured Diagnostics rows.
- [x] Prevent an unrelated file's graph error or duplicate canonical URL
from blocking an exact-file query.
- [ ] Prove missing targets, cycles, bad representations, and bad JSON
paths through real MCP.

## Query request and structure

- [x] Invalid JSON, invalid request UTF-8, empty/non-object request, and
request over 512 KiB.
- [x] Missing query and unknown request/query keys.
- [x] Invalid result mode.
- [x] Malformed where/all/any/filter shape.
- [x] More than 32 filters or children.
- [x] Filter nesting deeper than 8.
- [x] Empty field path or segment.
- [x] Field path deeper than 9.
- [x] Bare properties path.
- [x] Unknown or nested standard field.
- [x] Missing or unknown operator.
- [x] Non-JSON operator value.
- [x] Invalid in value or more than 1,000 in values.
- [x] Non-boolean exists/isEmpty value.
- [x] More than 8 sort entries.
- [x] Invalid sort field or direction.
- [x] first/last without a sort.
- [x] Invalid output mode or includeMetadata.
- [x] Duplicate output fields or more than 256 fields.
- [x] No selected output.
- [x] Negative, fractional, or over-1,000 limit.
- [x] Negative, fractional, or over-1,000 offset.
- [x] Invalid content mode.
- [x] Invalid full/markdown-body-ref maxBytes outside 1..1 MiB.
- [x] Invalid range offset/length or range over 256 KiB.
- [x] Empty or over-255-character index revision.
- [x] Multiple simultaneous schema issues retain exact query paths.
- [x] Make content option objects strict; unknown keys are currently
stripped.
- [x] Show an invalid persisted resource body rather than silently
loading the default query.
- [x] Aggregate unknown-key errors with every other structural issue;
MCP currently stops at the first unsupported key.
- [x] Add field-value type validation, for example reject size gt
"large" and id contains {}.
- [x] Warn about unobserved dynamic fields selected only as output.
- [ ] Prove the full structural matrix through the MCP server/API end to
end; the current broad matrix tests the local adapter.

## Query semantic states

- [x] INCOMPATIBLE_OPERATOR is fatal for standard fields.
- [x] UNOBSERVED_FIELD is a nonfatal warning.
- [x] INCOMPATIBLE_OBSERVED_TYPES is a nonfatal warning.
- [x] STRUCTURED_SORT_ORDER is a nonfatal warning.
- [x] Every incompatible standard-field operator is collected.
- [x] Fatal semantic errors retain nonfatal warnings.
- [x] Successful warnings appear with exact query paths.
- [ ] Reproduce every catalog-dependent semantic state through real MCP.
- [x] Test repeated warnings at distinct query paths without accidental
deduplication.

## Query execution and hydration

- [x] Stale index revision.
- [x] result one matching multiple files, including matchedCount.
- [x] Candidate document limit of 1,000.
- [x] Result payload limit of 16 MiB.
- [x] Hydrated file count limit of 20.
- [x] Per-file hydration limit of 1 MiB.
- [x] Total hydration limit of 2 MiB.
- [x] Range limit of 256 KiB.
- [x] Binary content requested as text.
- [x] Invalid UTF-8 during hydration.
- [x] Missing, stale, or conflicting content identity.
- [x] Canonical metadata/byte-count mismatch.
- [x] Storage returning more bytes than requested.
- [x] Missing content reader.
- [x] Selected content not returned.
- [x] Runtime Asset URL unavailable.
- [x] Document graph document-count/per-file/total limits.
- [x] Classify candidate-document and result-byte limits as
CONTENT_LIMIT_EXCEEDED instead of INVALID_REQUEST.
- [x] Give unavailable URL, missing reader/content, storage, selection,
and assembly failures stable codes and exact asset/file details instead
of INTERNAL_ERROR.
- [x] Never silently turn an exact-file unavailable-content failure into
an empty successful result.
- [x] Add direct regression tests for duplicate identity, excess bytes,
and canonical byte mismatch.
- [ ] Reproduce every runtime/hydration state through real MCP.

## Scoping and aggregation

- [x] Errors and warnings from multiple loaded result files are returned
together.
- [x] Nonfatal errors do not suppress successful query results.
- [x] Unrelated published-query diagnostics do not replace current-query
diagnostics.
- [x] File path and available line/column are shown.
- [x] Exact nested query paths are shown.
- [x] Validate and report every pre-pagination matching file if that is
the product definition.
- [ ] Explain candidate metadata warnings when invalid metadata prevents
deciding whether a file matches.
- [ ] Stop including METADATA_PREPARATION_FAILED globally unless the UI
labels its candidate scope.
- [x] Aggregate reference errors instead of stopping at the first.
- [x] Aggregate across validation phases where safe.
- [x] Add a matrix for same-file multiple errors, multiple files,
outside-page errors, filter-only candidate files, and unrelated queries.

## Transport, authorization, cancellation, and internal failures

- [x] UNAUTHORIZED and FORBIDDEN.
- [x] REQUEST_CANCELLED in query HTTP paths.
- [x] Sanitized authenticated internal message.
- [x] Generic unauthenticated/public internal message.
- [x] Preserve structured causes for document-load HTTP
status/body/metadata failures.
- [x] Preserve structured causes for object-storage read failures.
- [x] Preserve structured causes for graph selection/assembly failures.
- [ ] Test MCP/API cancellation directly.
- [ ] Reproduce authorization, cancellation, storage, and
sanitized-internal states through real MCP where safe.

## MCP reproduction

- [x] Real MCP reproduction: multiple Markdown YAML errors.
- [x] Real MCP reproduction: multiple simultaneous structural query
errors.
- [x] MCP update returns Markdown and MDX source diagnostics.
- [x] MCP upload returns Markdown and MDX source diagnostics.
- [x] MCP download returns Markdown and MDX source diagnostics.
- [x] Temporary remote fixtures are removed after reproduction.
- [ ] Real MCP reproduction for every frontmatter code.
- [ ] Real MCP reproduction for every MDX fatal/warning class.
- [ ] Real MCP reproduction for every Content Block semantic diagnostic.
- [ ] Real MCP reproduction for every reference/graph error.
- [ ] Real MCP reproduction for every semantic query warning/error.
- [ ] Real MCP reproduction for every hydration/runtime/limit error.
- [ ] Real MCP reproduction for auth, cancellation, storage, and
internal errors where safe.
- [ ] A durable table-driven test proves code/severity/message/path
parity between editor, query, Diagnostics, and MCP.
- [x] Preserve stable top-level error identity and structured details
through MCP instead of flattening known errors to MCP_TOOL_FAILED.
- [x] Prove failed post-commit MCP feedback reports whether a mutation
committed and returns enough identity for cleanup.

## Real MCP recheck and follow-up fixes (2026-09-03)

Ran the branch CLI against the PR preview backend. The first run exposed
that the saved CLI origin pointed to a different backend, so those
results were discarded. Every MCP result below came from the PR preview.
All temporary remote and local fixtures were removed afterward. The
failures found in that run were then fixed and covered by regression
tests.

- [x] Exact broken Markdown query returns FRONTMATTER_INVALID with
severity, filename, message, line, and column.
- [x] Exact MDX query returns unsafe-mdx with severity, filename,
message, line, and column.
- [x] A no-extension query returns warnings from both matching Markdown
and MDX files.
- [x] A Markdown-only query excludes the unrelated MDX warning.
- [x] Two fatal MDX files inside the returned page are both reported;
matching warnings remain attached.
- [x] Structural query validation returns three independent errors with
exact paths in one call.
- [x] Semantic query validation returns three fatal operator errors and
two warnings with exact paths in one call.
- [x] MCP upload, update, download, and exact-file query return multiple
source diagnostics for the same MDX source.
- [x] Query preview reports a missing Asset reference as ASSET_NOT_FOUND
with the source file and reference.
- [x] All temporary MCP fixtures were deleted and the saved CLI
connection was restored.
- [x] Fixed after recheck: validate every matching file before
pagination, including broken files outside the returned page.
- [x] Fixed after recheck: unrelated graph failures no longer block an
exact-file query.
- [x] Fixed after recheck: update, download, editor, and query paths use
shared reference validation.
- [x] Fixed after recheck: graph failures map to structured diagnostics
with the exact file.
- [x] Fixed after recheck: shared fatal UTF-8 validation runs before
upload writes and preserves structured error identity.
- [x] Fixed after recheck: MCP rejects filename/format mismatches.
- [x] Fixed after recheck: MDX validation keeps sibling and nested
warnings around unsupported components.
- [x] Fixed after recheck: MCP preserves stable top-level error codes
and structured details.
- [x] Fixed after recheck: query and MCP serializers preserve full
normalized diagnostic fields.
- [x] Fixed after recheck: unknown keys are aggregated with all other
structural query errors.
- [x] Fixed after recheck: shared query validation covers literal types,
output-only fields, and strict content options.
- [x] Fixed after recheck: unavailable selected content returns an
exact-file diagnostic instead of a silent empty result.

## Tests and delivery

- [x] Full Builder suite: 2,707 tests.
- [x] Content Engine suite: 445 tests.
- [x] Asset uploader suite: 211 tests.
- [x] Project runtime/MCP targeted suite: 128 tests.
- [x] CLI/MCP suite: 1,051 tests.
- [x] Relevant package typechecks, lint, generated docs, and diff
checks.
- [x] Documentation impact reviewed and generated Content Engine/MCP
reference updated.
- [x] Add the missing cross-surface error matrix described above.
- [ ] Demonstrate red/green behavior for every new matrix case.
- [ ] Run the complete agent evaluation suite after explicit approval.
- [ ] Re-run all checks after the remaining checklist is implemented.

## Compatibility and risk

Normal query result and expression-binding shapes remain unchanged.
Diagnostics add optional fields. Existing public/pre-auth error
redaction remains intact. The remaining unchecked items are broader
exhaustive real-MCP coverage, parser-recovery limits, candidate-warning
labeling, cancellation coverage, and agent evaluations.
2026-09-04 16:00:28 +02:00
d292502037 fix: Paste in Firefox navigator (#6329)
## Summary

- Read every clipboard mime type before the first await in both paste
handlers.
- Call the paste handler registered by the active mode from `emitPaste`
instead of dispatching a synthetic clipboard event.
- Add regression coverage for both paths: a clipboard event that
disconnects after dispatch, and a Firefox-shaped `ClipboardEvent`.

## Root cause

Two independent Firefox behaviors, one per entry point.

Keyboard paste: the plugin loop re-read `event.clipboardData` on every
iteration. Firefox disconnects a paste event's `DataTransfer` as soon as
the handler yields, so once `pageText` — first in the list, and async —
awaited, every later plugin read an empty string and `instanceText`
never received the payload. Chrome keeps the data readable across
microtasks, which is why this only surfaced in Firefox. Introduced in
#5798, which put `pageText` at the head of the plugin list.

Context menu paste: `emitPaste` dispatched `new ClipboardEvent("paste",
{ clipboardData })`. Gecko's `ClipboardEventInit` has no `clipboardData`
member, so the event arrived with a non-null but empty `clipboardData`.
`validateClipboardEvent` only rejects a null one, so the paste silently
did nothing — no toast, no error.

Measured in Firefox 134 against Chrome and Edge 152: `getData` after one
microtask returns the payload in Chromium and an empty string in
Firefox; a synthetic event's `getData` likewise returns the payload in
Chromium and an empty string in Firefox.

No behavior change in Chromium. Every plugin returns `pasteIgnored`
before its first await, so reading all mime types up front yields the
same input the loop received before.

## Verification

- `pnpm --filter @webstudio-is/builder exec vitest run
app/shared/copy-paste app/builder/shared/asset-manager
app/shared/commands-emitter.test.ts` — 335 tests passed.
- `pnpm --filter @webstudio-is/builder typecheck` — passed.
- `pnpm exec oxlint --deny-warnings apps/builder/app/shared/copy-paste/`
— passed.
- `pnpm exec oxfmt --check
apps/builder/app/shared/copy-paste/copy-paste.ts
apps/builder/app/shared/copy-paste/copy-paste.test.ts` — passed.
- Reverted each fix in turn against the new tests: 13 failures for the
keyboard path, 2 for the context menu, all passing again once restored.
- e2e runs Chromium only, and the previous test `DataTransfer` never
disconnected, so neither path was covered before.

Closes #6288

---------

Co-authored-by: Anmol <anmol@fathershops.com>
Co-authored-by: Oleg Isonen <oleg008@gmail.com>
2026-09-04 15:36:20 +02:00
Oleg Isonen e33a269802 fix: show unsupported browser warning in a dialog (#6332)
The unsupported-browser warning now uses the Builder’s regular modal
dialog. Users can acknowledge it and continue, while the small-window
state remains a blocking alert.

Closes #6331

## Implementation

- Render the existing browser guidance and links inside the
design-system `Dialog`.
- Set the dialog to modal and keep close, Escape, outside-click, and
**Continue** dismissal behavior.
- Keep unsupported-browser detection, preview-mode suppression, and
Builder-ready timing unchanged.
- Keep the small-window alert blocking and remove its now-unused
dismissible-alert path.
- Add a focused Storybook state and browser regression test.
- Increase Main and Visual Regression workflow job timeouts from five to
seven minutes after otherwise healthy jobs were cancelled during slow
dependency setup.
- Run failed E2E diagnostics and service teardown through the backend
shell script so cleanup does not depend on pnpm remaining on `PATH`
after cancellation.
- Route `safe-to-deploy` label events through one reusable gate that
starts both Main and Vercel workflows.
- Remove revision-specific deployment and visual approval labels in one
synchronization-only cleanup job.
- Reduce expected skipped jobs from 6 to 1 on a normal branch update and
from 17 to 3 on a visual approval label event.

No migrations or compatibility changes are required.

## Todo

- [x] Replace the unsupported-browser alert with a modal dialog.
- [x] Preserve the small-window blocking alert.
- [x] Add regression coverage.
- [x] Give CI enough time for slower dependency setup.
- [x] Keep E2E cleanup available after runner cancellation.
- [x] Simplify label-triggered Main and Vercel workflows.
- [x] Consolidate revision-specific approval cleanup.
- [x] Review documentation impact: no product documentation changes are
needed for this presentation-only warning update.
- [x] Review fixture impact: no fixture inputs or generated fixture
outputs are affected.

## Verification

- [x] Focused browser regression test
- [x] Builder typecheck
- [x] Oxlint on changed files
- [x] Oxfmt and `git diff --check`
- [x] Workflow YAML parsing and backend shell syntax checks
- [x] Workflow trigger, nesting, permissions, and reusable-job contract
assertions
- [x] Prettier checks for changed workflows
- [ ] Storybook screenshot review was not run locally because explicit
visual-test approval was not available.

## Known limitations

- The visual state was not screenshot-tested locally.
- The reduced `pull_request_target` fan-out takes effect after these
workflow files reach the default branch, because GitHub loads those
workflow definitions from that branch.
2026-09-04 15:06:34 +02:00
Oleg Isonen b832a8e808 refactor: Centralize Builder ID generation (#6323)
## Outcome

Builder-owned code now routes standard ID generation through
`@webstudio-is/sdk/createId` while preserving existing NanoID and UUID
formats.

Closes #6322

## Technical choices

- Use `createId("nano")` for Builder records, assets, transaction IDs,
and other existing NanoID-backed values.
- Use `createId()` for UUID-backed database records and browser-side
client IDs.
- Keep `BuilderRuntimeContext.createId` as an injectable dependency.
Runtime operations, copy/paste, and deterministic tests rely on that
injection.
- Keep Node's `randomUUID` in CLI paths that explicitly support running
without the Web Crypto global.
- Keep specialized generators for custom-alphabet project domains and
actual hash generation.
- Remove direct `nanoid` dependencies from packages where no specialized
use remains.
- Do not migrate existing data or change database schemas.

## Todo

- [x] Migrate Builder app ID creation.
- [x] Migrate project runtime and template defaults.
- [x] Migrate asset, project, domain, and authorization-token IDs.
- [x] Preserve runtime ID injection.
- [x] Review remaining direct generators as explicit exceptions.
- [x] Add NanoID-format regression coverage for the default runtime
context.
- [x] Review documentation impact: no user-facing documentation changes
are needed.
- [x] Review fixture impact: no fixture input or generated output format
changes are needed.
- [x] Run targeted tests, typechecks, lint, and package-boundary checks.

## Verification

- Targeted Builder tests: 153 passed after preserving runtime-context
injection.
- Project-build runtime tests: 270 passed.
- Asset uploader tests: 61 passed.
- Authorization-token tests: 17 passed.
- Project tests: 52 passed.
- Domain tests: 18 passed.
- CLI tests: 32 passed.
- Typechecks passed for Builder, project-build, asset-uploader,
authorization-token, project, and domain.
- `pnpm lint` passed.
- `pnpm check:package-boundaries` passed.
- The runtime-context format test was demonstrated to fail with a UUID
default and pass with the NanoID default.
- Agent evaluations were not run because they require separate explicit
approval.
2026-09-03 15:56:23 +02:00
Oleg Isonen fc9fa39fbc fix: Reduce style source padding (#6315)
## Result

Style source controls now use spacing level 1 for their inner padding
instead of spacing level 2.

## Implementation

- [x] Change only the inner padding of `StyleSourceControl`.
- [x] Keep interactions and accessible behavior unchanged.
- [x] Review documentation impact: no documentation changes are needed
for this visual spacing correction.
- [x] Verify formatting, lint, and Builder types.

## Verification

- `pnpm exec oxfmt --check
apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx`
- `pnpm exec oxlint --deny-warnings
apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx`
- `pnpm --filter=@webstudio-is/builder typecheck`

No fixture inputs or generated outputs are affected. No known
limitations.

Closes #6314
2026-09-02 14:57:23 +02:00
Oleg Isonen d4b1994a6a fix: Improve editor selection and project tag contrast (#6302)
Closes #6301

## Summary

- Restore Dashboard project tags to the pre-color-refactor treatment:
fixed white text over a 30% black scrim in both application themes.
- Use one high-contrast text-selection treatment across native inputs,
textareas, contenteditable fields, and every shared CodeMirror editor.
- Preserve the existing subtle selection treatment for Navigator,
Project Settings, command menus, Dashboard navigation, and other
selected controls.
- Add direct Storybook coverage for the CSS fragment editor.
- Simplify chromatic color derivation from 571 to 329 lines without
changing computed colors.

## Technical choices

- Keep project tags independent from application-theme polarity because
they overlay arbitrary thumbnail artwork.
- Keep the existing `selectionBackground` control-state export unchanged
at its original 12% light / 20% dark accent blend.
- Define separate `--background-text-selection` and
`--foreground-on-text-selection` tokens exclusively for selected text.
- Use the bounded accent in light mode and a luminance-lifted accent in
dark mode so selected text remains distinct even with extreme custom
theme colors.
- Style CodeMirror through its existing selection layer and
`::selection` CSS hooks; no selection tracking or editor-state logic is
added.
- Leave canvas rich-text selection independent: authored canvas
documents do not load the Builder UI theme stylesheet.
- Replace five duplicated XYZ clamp formulas with the exact
upper-luminance cap they reduce to. The removed lower-bound and
white-mixing branches were unreachable because the minimum was fixed at
zero.

## Todo

- [x] Restore the original project-tag scrim and foreground in both
themes.
- [x] Inventory native, CodeMirror, and canvas rich-text selection
paths.
- [x] Unify native and shared CodeMirror text-selection colors.
- [x] Keep text selection independent from selected control and
navigation states.
- [x] Add the missing CSS fragment editor story.
- [x] Add light- and dark-mode browser regressions and confirm they fail
before the fix.
- [x] Enforce 4.5:1 selected-text contrast and 3:1 highlight-to-surface
contrast across supported theme inputs.
- [x] Remove duplicated and unreachable chromatic color derivation while
preserving outputs.
- [x] Review documentation impact; the design-system color-token
reference is updated, with no user-facing product documentation change
required.
- [x] Verify fixture impact; no fixture inputs or generated outputs are
affected.

## Verification

- `pnpm --filter @webstudio-is/design-system test` — 227 tests passed,
including the control/text separation regression, Navigator tree
interaction, default-palette comparisons, and the full supported-theme
contrast sweep
- `pnpm --filter @webstudio-is/design-system typecheck`
- `pnpm --filter @webstudio-is/builder exec vitest run
app/shared/code-editor-base.browser.test.tsx --project
app-browser-shared`
- `pnpm --filter @webstudio-is/builder exec vitest run
app/dashboard/projects/project-card.browser.test.tsx --project
app-browser-canvas-dashboard`
- `pnpm --filter @webstudio-is/builder typecheck`
- Targeted `oxlint`, formatting, and `git diff --check`
- Live dark-mode Dashboard verification of the restored subtle
navigation selection
- Storybook visual checks for the full color system and input/CodeMirror
selection in light and dark modes
2026-09-01 17:05:14 +02:00
Oleg Isonen 1de752f2ae fix: Keep Slot colors consistent (#6296)
## Summary

- Define the purple treatment as a semantic secondary-accent CSS color
family.
- Use its foreground in the Layers panel and its
background/on-background pair on the canvas.
- Add visual regression coverage that shows the actual Navigator and
canvas Slot treatments together.
- Keep the same purple in light mode and use a more chromatic, readable
foreground in dark mode.

## Implementation

The dark-theme migration replaced the former reusable-instance color
with two unrelated choices: the blue accent foreground in the navigator
and an accent-derived purple canvas fill.

This change adds three generated, theme-aware semantic colors using
Craft's existing naming and explicit foreground pairing conventions:

- `--background-accent-secondary` for Slot canvas labels and outlines.
- `--foreground-accent-secondary` for reusable instances in the
navigator.
- `--foreground-on-accent-secondary` for content on the strong
secondary-accent background.

The secondary accent derives from the theme accent. Its foreground keeps
the existing strong purple in light mode and raises dark-mode lightness
without washing out its chroma, so reusable instances remain visibly
distinct from ordinary Navigator text.

Portable light and dark visual stories render the real `NavigatorTree`
beside the real canvas `Outline` and `Label` Slot variant. This covers
the user-reported cross-surface consistency and the dark-mode foreground
directly.

## Todo

- [x] Trace the regression to the color-system migration.
- [x] Add the secondary-accent semantic CSS family and generated types.
- [x] Add foreground/background contrast contracts across supported
themes.
- [x] Update navigator and canvas consumers.
- [x] Add light and dark visual regression coverage for the actual
Navigator and canvas treatments.
- [x] Confirm the visual comparison fails before approval and inspect
the rendered screenshot.
- [x] Run Design System and focused Builder tests.
- [x] Run Design System and Builder typechecks, scoped lint, and
formatting checks.
- [x] Review fixture impact; no fixture inputs or generated fixture
outputs are affected.
- [x] Review documentation impact; update the internal color-system
reference. Authoritative user documentation is unaffected.

## Verification

- `pnpm --filter @webstudio-is/design-system test` — 223 tests passed.
- `pnpm --filter @webstudio-is/builder exec vitest run --project
core-browser-builder-features
app/builder/features/navigator/navigator-tree.test.ts` — 20 tests
passed.
- The dark secondary-accent regression test was confirmed to fail with
the washed-out foreground, then pass with the stronger chromatic
foreground.
- `pnpm --filter @webstudio-is/design-system typecheck` — passed,
including generated color-type freshness.
- `pnpm --filter @webstudio-is/builder typecheck` — passed.
- Scoped `oxlint --deny-warnings` — passed.
- Scoped `oxfmt --check` — passed.
- `pnpm visual-regression -- --base origin/main --grep
"Builder/Navigator/Navigator tree"` — expected failure with two added
visual stories; both light and dark screenshots were inspected.

The source-contract test was confirmed to fail before the semantic
variables were added, then pass with the implementation. Browser
contrast tests cover both new pairings across light/dark modes and the
complete supported theme parameter range.

Closes #6295
2026-09-01 02:51:13 +02:00
Oleg Isonen c49c0786be fix: unify dashboard background surface (#6287)
## Description

1. What is this PR about (link the issue and add a short description)

## Steps for reproduction

1. click button
2. expect xyz

## Code Review

- [ ] hi @kof, I need you to do
  - conceptual review (architecture, feature-correctness)
  - detailed review (read every line)
  - test it on preview

## Before requesting a review

- [ ] made a self-review
- [ ] added inline comments where things may be not obvious (the "why",
not "what")

## Before merging

- [ ] tested locally and on preview environment (preview dev login:
0000)
- [ ] updated [test
cases](https://github.com/webstudio-is/webstudio/blob/main/apps/builder/docs/test-cases.md)
document
- [ ] added tests
- [ ] if any new env variables are added, added them to `.env` file
2026-08-31 21:55:59 +02:00
Oleg Isonen f953d1be37 fix: Restore the login background gradient (#6286)
## Summary

Restores the original Webstudio login gradient after the color-system
migration added a dark scrim over it. Fixed Webstudio identity artwork
now belongs to the Design System, while generic surfaces, content,
translucency, and overlays use the semantic color system instead of a
Builder-local brand color bag.

## Architecture

- The Design System exports only the fixed Webstudio background
gradient, progress gradient, and progress shadow as brand artwork.
- Generic black, white, translucent panel, and scrim entries were
removed rather than moved.
- Login and error surfaces use semantic light/dark pairings.
- Project-card tags derive their local 30% scrim from the semantic
overlay color.

## Todo

- [x] Restore the original login gradient without a scheme-dependent
scrim.
- [x] Move fixed identity artwork into the Design System package.
- [x] Remove the Builder-local brand color registry.
- [x] Replace generic fixed colors with semantic colors or local
derivations.
- [x] Add explicit dark-mode Storybook coverage for the login screen.
- [x] Run Design System and Builder typechecks.
- [x] Run Design System tests, scoped lint, formatting, and
package-boundary validation.
- [x] Review documentation impact and document ownership in the Design
System color README.

## Verification

- Design System tests: 222 passed.
- Design System and Builder typechecks: passed.
- Scoped Oxlint and formatting: passed.
- Package-boundary validation: passed.
- Focused visual regression: 23 affected stories compared; the newly
added dark login story is the only difference.
- Fixture impact: no fixture inputs or generated outputs are affected.

Ref #3818
2026-08-31 21:16:26 +02:00
Oleg Isonen bc8630f413 fix: Gate Builder releases on the published CLI contract (#6282)
Closes #6280

## Summary

- Expose the deployed Builder's CLI-facing bundle contract through a
non-cached, read-only endpoint.
- Resolve and execute the exact `webstudio@latest` registry artifact,
observe the bundle version sent by its real `sync` request, and require
an exact match before assigning the release staging alias.
- Include expected and received bundle versions in runtime and
release-gate errors.

## Technical choices

- The existing generated `bundleVersion` remains the single
compatibility boundary. Builder-only changes outside that project-bundle
contract do not require a CLI release.
- The CLI sync probe runs against a local fixture API and temporary
directory. It reads the deployed runtime contract but never reads or
modifies a Cloud project.
- Verification runs after Vercel creates the exact production-built
deployment and before the release staging alias is assigned. A mismatch
therefore leaves production domains untouched.
- Registry resolution requires version and integrity metadata, then
executes the resolved immutable version rather than source from the
checkout.
- The gate requires the deployed Builder origin and cannot fall back to
the checkout's contract.

## Todo

1. [x] Add the deployed Builder contract endpoint.
2. [x] Probe the exact published CLI through its real sync request.
3. [x] Gate the release staging alias on an exact contract match.
4. [x] Report expected and received versions for compatibility failures.
5. [x] Add regression tests and verify the production Builder build.
6. [x] Review documentation and fixture impact.

## Verification

- `pnpm --filter @webstudio-is/builder exec vitest run
app/services/build-router.server.test.ts
app/services/cli-compatibility-route.node.test.ts` — 12 passed.
- `pnpm --filter webstudio exec vitest run
scripts/builder-contract-gate.test.ts
scripts/release-smoke-registry.test.ts` — 7 passed.
- Rebased onto `main` at `9ec4c820e1`.
- Builder and CLI typechecks passed.
- `pnpm lint` and changed-file formatting passed.
- `pnpm --filter @webstudio-is/builder build` passed and emitted
`/rest/cli-compatibility`.
- The changed GitHub Action parses as valid YAML.
- Real registry probe passed for `webstudio@0.293.0` against
`bundle-kzb45v`.
- Real registry probe correctly blocked current Builder contract
`bundle-1mym82p` and reported expected `bundle-1mym82p`, received
`bundle-kzb45v`.
- Missing staged Builder origin fails closed before registry execution.
- GitHub CI passed all four workflows, including all six Builder E2E
shards.
- The formerly failing empty-MDX insertion workflow passed 8 repeated
runs with 4 workers locally, then passed in Builder E2E shard 4 in CI.
- Full browser-based release smoke was not run, per the request not to
use Chrome. Agent evaluations were not run because no evaluation
approval was requested or received.
- Documentation: no user-facing documentation changes are required.
- Fixtures/generated outputs: no fixture inputs or generated outputs are
affected.

## Operational boundary

The check needs the exact deployed runtime, so Vercel creates an
unaliased `--skip-domain` deployment before verification. A failed check
cannot affect production domains or the normal release alias. Repository
automation cannot prevent a Vercel administrator from manually promoting
an arbitrary deployment outside this release path.
2026-08-31 20:43:52 +02:00
Oleg Isonen 8718feb465 test: simplify browser testing infrastructure (#6271)
## Summary

Unifies frontend testing around three intentional boundaries:

- Vitest Node projects for pure and server tests
- Vitest Browser Mode with Playwright/Chromium for DOM and component
tests
- Playwright Test for Builder end-to-end workflows

The Builder no longer uses jsdom. Ordinary E2E workflows use an
automatically managed isolated `page` fixture; explicit contexts remain
only for simultaneous identities and suite-scoped setup.

## Technical choices

- Split Builder tests into one Node project and independent browser
projects so each Chromium/Vite process has a bounded workload.
- Added shared Browser Mode configuration for the affected SDK React
packages.
- Preserve the Builder's production top-window bridge ownership; Browser
Mode uses explicit test-only installation seams.
- Centralized Playwright context options and kept action/navigation
timeouts bounded.
- Validate Playwright filters before Docker, migrations, browser
installation, or Builder builds start.
- Preserve the first failed E2E attempt's report, traces, screenshots,
and videos when CI retries a shard.
- Split static checks, typechecks, CLI tests, core package tests,
browser package tests, and Builder projects into parallel CI jobs with
five-minute hard ceilings.
- Distribute Builder E2E tests across ten isolated shards with two
workers; parallel suites create unique per-worker setup data.
- Reuse color contrast DOM/canvas samples so the exhaustive theme sweep
takes about four seconds instead of timing out at 30 seconds.
- The removed cost is jsdom behavior drift, oversized serial check jobs,
and unnecessary E2E startup for empty selections. Real browser startup
and E2E environment setup remain.

## Todo

- [x] Split Builder pure/server tests from browser/component tests.
- [x] Migrate Builder DOM tests from jsdom to Vitest Browser Mode.
- [x] Migrate affected SDK React DOM tests to the shared Browser Mode
setup.
- [x] Remove jsdom annotations, dependencies, and compatibility setup.
- [x] Replace ordinary manual E2E contexts with the isolated `page`
fixture.
- [x] Keep explicit contexts only for concurrent identities and
`beforeAll` setup.
- [x] Preserve setup authentication isolation from workflow pages.
- [x] Add bounded Playwright action and navigation timeouts.
- [x] Preserve first-attempt E2E failure evidence across CI retry.
- [x] Reject empty E2E selections before expensive environment setup.
- [x] Parallelize repository checks into bounded CI shards.
- [x] Isolate parallel E2E setup data across workers.
- [x] Remove the color contrast sweep bottleneck.
- [x] Update E2E contributor documentation.
- [x] Review product documentation impact; no user-facing product docs
are affected.
- [x] Run the full repository tests and typechecks.
- [x] Run formatting, lint, package-boundary, generated-file, and
fixture checks.
- [x] Complete final correctness and simplification review.

## Verification

- `pnpm --filter @webstudio-is/builder test`
- `pnpm -r typecheck`
- `pnpm lint`
- `pnpm check:package-boundaries`
- `pnpm check:generated-api`
- `pnpm check:generated-docs`
- `pnpm fixtures`
- Design-system: 222 tests pass locally.
- Builder: all seven Vitest projects pass locally.
- The formerly slow E2E shard passes locally in 1m55s.
- Full database-backed Builder E2E execution passes in CI.
- All CI jobs pass; the slowest completed in 4m58s.
- No fixture inputs/outputs or generated files changed.

Ref #6270
2026-08-31 17:17:28 +02:00
Oleg Isonen f6c524572d feat: add Builder dark theme and rebuild colors
## Summary

Rebuilds Webstudio’s color system, migrates the entire Builder to it,
and introduces a complete dark theme.

A small set of theme colors and contrast controls now drives the
interface through relative CSS colors:

```text
Theme colors and contrast
    ↓
Light/dark derivation bounds
    ↓
Derived color families
    ↓
Reusable semantic colors
    ↓
Component composition
    ↓
Builder interface
```

CSS is the runtime source of truth. Light and dark modes share the same
theme inputs, so changing a theme color automatically updates its
surfaces, content, borders, states, and component presentation. The
refactor turns dark mode into a first-class Builder theme rather than a
separately maintained palette.

This is an atomic migration. Legacy color names and compatibility
aliases will not remain after all consumers have moved.

## Scope

- The color source, derivation model, semantic vocabulary, validation,
typing, and Storybook overview.
- Every design-system component.
- Builder, dashboard, authentication, shared UI, Query Builder, stories,
and tests that consume the legacy color scale.
- Removal of the legacy Stitches color scale after its final consumer is
migrated.
- A complete dark theme across application UI while keeping authored
canvas content independent.
- Complete light and dark visual verification.
- Unified browser-test infrastructure: Vitest Browser Mode for Design
System browser contracts and standard Playwright Test for all Builder
E2E workflows.

Literal colors remain only where color is the actual content or belongs
to a deliberately separate system, such as user-authored values,
external previews, brand artwork, data visualization, functional canvas
overlays, and source assets. Every remaining exception must have an
explicit owner.

## Architecture decisions

- Theme authors control six color families and three bounded contrast
controls.
- Relative CSS colors derive the rest of the system.
- Dark mode changes derivation bounds instead of maintaining a second
independent palette.
- Components consume a small reusable semantic vocabulary.
- Component states and exceptional presentation are composed inside
components.
- Builder-specific categorical meaning uses focused composite recipes,
not intent semantics or a larger global vocabulary.
- TypeScript validates public semantic CSS-variable names but does not
generate runtime colors.
- No token-manager dependency, compatibility aliases, or
component-specific public color tokens.
- A new semantic or theme variable is added only when existing semantics
and local composition cannot represent a reusable cross-feature
decision.

## Todo

### Color-system foundation

- [x] Establish direct CSS as the runtime source of truth.
- [x] Define bounded theme colors and contrast controls.
- [x] Derive light and dark modes from the same theme inputs.
- [x] Reduce the semantic inventory to reusable decisions and explicit
accessibility pairs.
- [x] Generate only TypeScript names for public semantic CSS variables.
- [x] Validate layers, references, cycles, consumption, naming,
generated types, and browser-computed contrast.
- [x] Add the Storybook color-system overview and theme controls.
- [x] Document the architecture and its relationship to the public Craft
specification.

### Design-system migration

- [x] Replace every active legacy color consumer in design-system
components and Storybook chrome.
- [x] Compose component states locally without component-specific public
tokens.
- [x] Preserve intentional preview and sample-content colors.
- [x] Add complete positive, negative, warning, informative, and accent
accessibility pairings.
- [x] Validate light and dark scheme-bound references independently.
- [x] Verify the design-system package with typecheck, lint, formatting,
Storybook, and 222 tests.

### Inventory and contract

- [x] Inventory all 319 legacy references across 107 Builder, Query
Builder, story, test, and design-system files.
- [x] Classify every reference as a direct semantic replacement, local
composite recipe, documented literal exception, or removable code.
- [x] Record the intentional authored-content, external-preview,
functional-preview, data-visualization, brand, and source-asset
exceptions.
- [x] Treat the public semantic vocabulary as closed by default and
justify any proposed addition by cross-feature reuse and accessibility
need.
- [x] Keep Builder code limited to typed public variables accepted by
`cssVar()`.

### Theme infrastructure

- [x] Add `system` (default), `light`, and `dark` application
preferences.
- [x] Persist the preference in existing client settings and resolve
`system` through `matchMedia`.
- [x] Apply the resolved scheme before paint and respond to
operating-system changes.
- [x] Expose the persisted theme control under **View → Color scheme**.
- [x] Keep authored canvas documents independent from the application
theme.
- [x] Ensure portals, overlays, embedded surfaces, and third-party
controls receive the correct interface scheme.

### Generic interface migration

- [x] Migrate shared dialogs, project settings, notifications, controls,
and Query Builder.
- [x] Migrate dashboard, authentication, publishing, and shared
application UI.
- [x] Migrate the Builder loading state, topbar, sidebars, navigator,
workspace, footer, settings, pages, alerts, and menus.
- [x] Replace fixed interface literals alongside their owning surfaces.
- [x] Remove the old scrollbar variable and hardcoded loading color.

### Style panel and style-source recipes

- [x] Migrate ordinary style-panel inputs, labels, layouts, spacing,
alignment, menus, property states, and value editors.
- [x] Model style-source provenance, kind, interaction, and error as
separate axes.
- [x] Compose categorical style-source colors from neutral and
accent-relative colors.
- [x] Use negative semantics only for actual errors, not overwritten
provenance.
- [x] Reuse one feature-owned recipe across style-source controls,
badges, menus, and values without adding global tokens.

### Canvas and editors

- [x] Migrate canvas selection, reusable outlines, grid guides, resize
handles, labels, badges, and overlays.
- [x] Keep collaborator colors as data visualization while guaranteeing
readable labels.
- [x] Prevent Builder theme values from leaking into authored content.
- [x] Migrate editor surfaces, selections, autocomplete, lint states,
and tooltips.
- [x] Derive syntax visualization from neutral and accent-relative
colors; reserve intent colors for diagnostics.

### Explicit color domains

- [x] Isolate external search and social previews from the application
scheme.
- [x] Preserve user-authored CSS values, functional color previews, and
checkerboards.
- [x] Review brand surfaces independently in both schemes.
- [x] Document every retained literal in the exception ledger.

### Stories, tests, and legacy removal

- [x] Migrate all affected Builder stories and tests.
- [x] Replace the design-system test that intentionally references the
legacy scale.
- [x] Add theme-preference and scheme-resolution behavior tests.
- [x] Remove the legacy `design-tokens.color` registry.
- [x] Remove the Stitches `colors` scale and `rawTheme.colors`.
- [x] Remove color-name conversion code that exists only for the legacy
scale.
- [x] Add a focused repository check that rejects legacy references.
- [x] Confirm no compatibility mappings or deprecated aliases remain.

### Browser-test infrastructure

- [x] Run pure Design System tests in Node and browser-dependent tests
in Vitest Browser Mode with Playwright Chromium.
- [x] Migrate all 79 Builder E2E workflows from the custom harness to
standard Playwright Test.
- [x] Replace filename-based shard discovery with standard Playwright
sharding.
- [x] Preserve clean-backend shard retries and upload Playwright failure
artifacts in CI.
- [x] Remove the custom runner, registry, and timeout infrastructure.

### Verification and documentation

- [x] Compare light-mode visual regressions directly with `main`; review
every difference rather than accepting snapshots wholesale.
- [x] Add representative dark coverage for dashboard, Builder shell,
style panel, dialogs, editors, canvas tools, and status states.
- [x] Test default and extreme custom-theme presets.
- [x] Verify semantic and categorical-recipe contrast.
- [x] Test first paint, persistence, system changes, portals, and canvas
isolation.
- [x] Run affected tests, typechecks, lint, formatting, and Storybook
checks.
- [x] Review fixture impact; no fixture inputs or generated outputs are
affected.
- [x] Review authoritative `docs/` content and update it where needed.
- [x] Review the final diff and make this checklist reflect delivered
scope.

## Current verification

- Design-system typecheck and generated-type freshness: passed.
- Design-system tests: 222 passed, including the full theme-parameter
contrast sweep and browser component coverage.
- Builder typecheck and production build: passed.
- Theme preference and scheme-resolution tests: 10 passed.
- Scoped Oxlint, formatting, and diff checks: passed.
- Design-system Storybook build and representative light/dark visual
review: passed.
- Builder E2E: 80/80 Playwright entries passed (setup plus 79
workflows).

Ref #3818
Closes #6267
2026-08-30 03:24:56 +01:00
Oleg Isonen f9681dc30f feat: MDX-backed Content Blocks (#6234)
## Summary

Supersede #6182 with a clean implementation of MDX-backed Content Blocks
on top of the unchanged `main` Content Block editing model. A connected
`.mdx` Asset changes where authored children are loaded and saved; it
must not change how Content mode inserts, edits, selects, moves, copies,
or deletes instances.

The previous implementation remains available in
`agent/mdx-content-block-6124` and
`agent/mdx-content-block-6124-review`. Reuse its independently tested
parsers, converters, schemas, Asset repository, template resolution,
publication, MCP, and UI work where those pieces fit the corrected
architecture. Do not port its per-operation storage routing, projected
editing stores, MDX undo/history, or atomic multi-root machinery.

Ref #6124
Ref #6182
Closes #6261

## Locked behavior

- `.md` keeps its existing Markdown behavior; `.mdx` enables MDX.
- Standard Markdown structures are stored as Markdown. JSX is used only
for structures Markdown cannot represent losslessly.
- Generic elements use `<ws.element ws:tag="…">`; template instances use
`<ws.element ws:name="…">`.
- Invalid, unsafe, or unsupported MDX never prevents editing the file or
publishing the project. Builder and publication use the same recovery
result: recoverable nodes are skipped with source-located warnings,
while an unrecoverable document renders no authored file content in
either environment.
- Connecting a source never serializes existing Content Block children
into the file. **Connect** removes ordinary persisted children,
preserves Templates, sets `src`, and uses file content.
- Disconnecting resets `src`, discards derived instances, leaves the
Content Block empty, and never changes the Asset.
- While connected, normal Content Block mutations update in-memory
instances synchronously. Asset persistence happens afterward and never
blocks rendering.
- Genuine external revision conflicts use the standard reload-required
flow. Rapid local edits are ordered/coalesced and must never conflict
with each other.
- Repeated scopes use Content Block ID plus Collection item identity.
- Multiple Content Blocks may intentionally share one MDX Asset. They
share one revisioned document session and edits propagate to every
connected occurrence.
- Missing templates show warnings/placeholders only in Builder and are
skipped on published sites.

## Reuse strategy

- [x] Audit all 62 original implementation commits and 5 later
review/fix commits
- [x] Reuse the shared Content Engine Markdown/MDX AST, parser,
serializer, diagnostics, reference discovery, and tests
- [x] Reuse SDK source schemas, instance-name utilities, unique template
naming, and source-integrity validation
- [x] Reuse template resolution/materialization and authored-tree
conversion after removing storage-operation coupling
- [x] Reuse revisioned Asset content repository, authorization, limits,
and browser/server transport
- [x] Reuse publication, document-graph, CLI, MCP, source-control UI,
frontmatter UI, and E2E work where contracts remain valid
- [x] Reuse tests as behavioral specifications; rewrite tests that
assert the rejected projection/routing architecture
- [x] Do not port per-operation MDX routing, alternate projected
mutation stores, semantic reconciliation after each command, MDX Builder
history/undo, atomic multi-file rollback, or canvas loading/saving UI


## Old-branch porting map — do not rewrite

Before implementing any checklist batch, inspect the named
implementation and tests on `agent/mdx-content-block-6124-review`. Move
the implementation and its tests first; change only the boundary that
conflicts with the rebuilt architecture. Do not create a second
implementation under a new name. When a test encodes the rejected
projected-store architecture, retain its behavioral assertion and
replace only its setup.

### Already ported

- `parseMarkdownAst`, `createMdxDocumentFromMarkdown`,
`parseMdxDocument`, `serializeMdxDocument`, `preferMarkdownSyntax`,
`discoverMdxBodyAssetReferences`, `discoverMdxAssetReferences`, and
`previewMarkdownToMdxConversion`
- Asset-reference, byte-stream, document-graph, Markdown, and MDX
helpers included in commit `76bc388ba9`
- Tests: the corresponding `packages/content-engine/src/**/*.test.ts`
files already on this branch

### Port with their existing tests

| Area | Functions to move or adapt | Tests to move with them |
| --- | --- | --- |
| Source contract and integrity | `parseContentBlockSourceProp`,
`getContentBlockSource`, `isEqualContentBlockSource`,
`formatContentBlockSourceIntegrityIssue`,
`getContentBlockSourceIntegrityIssues`,
`allocateUniqueContentBlockTemplateName` |
`packages/sdk/src/content-block.test.ts`,
`packages/sdk/src/schema/content-block.test.ts` |
| Existing instance/name utilities | `findChildReferenceIndex`,
`findParentInstanceReference`, `getInstanceName` |
`packages/sdk/src/instances-utils.test.tsx` |
| Template naming in mutations |
`assignUniqueBlockTemplateNamesMutable`,
`findBlockTemplateNameCollision`, `getSourceBackedBlockTemplateContext`,
`getBlockTemplateNameConfirmation`, `getBlockTemplateInsertionIndex` |
`packages/project-build/src/runtime/block.test.ts` |
| Content-mode property permissions | `getContentModePropEligibility`;
preserve its distinction between editable, design-only, incompatible,
and unknown props |
`packages/project-build/src/runtime/content-mode-permissions.test.ts` |
| Template resolution | `resolveMdxTemplates` |
`packages/project-build/src/runtime/mdx-template-resolution.test.ts` |
| Template materialization | `createMdxScopeIdGenerator`,
`materializeMdxTemplates` |
`packages/project-build/src/runtime/mdx-materialization.test.ts` |
| MDX → instances and instances → MDX |
`isMaterializedMdxAuthoredContentRoot`, `preserveMdxAuthoredContentIds`,
`materializeMdxAuthoredContent`, `reconcileMdxAuthoredContent`,
`omitTransientEmptyParagraphs`, `serializeMdxTemplateInsertion` |
`packages/project-build/src/runtime/mdx-authored-content.test.ts`;
retain the pure serialization cases from `mdx-storage-adapter.test.ts` |
| Revisioned Asset I/O | `createAssetContentRevision`,
`readAssetContentBytes`, the package-owned
`createHttpAssetContentRepository`, the thin Builder
`createBuilderHttpAssetContentRepository`, `createAssetContentBridge`,
`initAssetContentBridge`, `getAssetContentBridge`; keep one repository
implementation rather than copying the old Builder duplicate |
`packages/asset-uploader/src/content-repository.test.ts`,
`apps/builder/app/builder/shared/assets/mdx-content-repository.test.ts`,
`apps/builder/app/shared/asset-content-bridge.client.test.ts` |
| Source lifecycle planning | `createContentBlockBodyRemoval`,
`prepareContentBlockConnect`, `prepareContentBlockDisconnect`,
`prepareContentBlockSwitch`, `ContentBlockSourceRevisionConflictError` |
`packages/project-build/src/runtime/content-block-source-lifecycle.test.ts`
|
| Per-Asset revision/session behavior | `getContentBlockSessionSource`,
`isContentBlockSessionSourceCommitted`; reuse the loading,
authorization, revision, queue, conflict, retry, cancellation, and
source-replacement internals of `createMdxAssetEditingSession`, but key
the rebuilt session by Asset rather than Content Block/render root |
Port the applicable cases from
`packages/project-build/src/runtime/mdx-asset-session.test.ts`; replace
root-projection setup with in-memory snapshot setup |
| Template migrations | `validateMdxTemplateMigrationConfirmation`,
`planMdxTemplateMigration` |
`packages/project-build/src/runtime/mdx-template-migration.test.ts` |
| Publication | `createPublishedMdxMaterializationCache`,
`materializePublishedMdx`, `getPublishedMdxContentDatabaseMaxBytes`,
`getDynamicPublishedMdxSourceBlockIds`, `hasDynamicPublishedMdxSources`,
`createPublishedBuildContentCompilationPlan`,
`resolvePublishedMdxDependencyClosure`,
`resolvePublishedMdxAssetCandidates` |
`packages/project-build/src/runtime/published-mdx.test.ts`,
`packages/project-build/src/content-database.test.ts` |
| Build/import integrity | `assertContentBlockSourceIntegrity` and the
Content Block cases in
`getBuildIntegrityIssues`/`formatBuildIntegrityIssue` |
`packages/project-build/src/build-integrity.test.ts` |
| MDX paste/MCP insertion | `insertMdxText` and its input/result
schemas; retain parsing, confirmation, template-resolution, and
insertion-index logic, then invoke the normal mutation path |
`packages/project-build/src/runtime/mdx-paste.test.ts` |
| Builder source control | `createContentBlockSourceController`,
`createBuilderContentBlockSourceController` and the existing
source-control components | `content-block-source-controller.test.ts`,
`content-block-source.test.tsx` |
| Diagnostics | `formatContentBlockDiagnostic`,
`deduplicateContentBlockDiagnostics`, `takeNewContentBlockDiagnostics` |
Port only their focused cases from
`apps/builder/app/shared/content-block-content.test.ts` |

### Explicitly do not port

- `projectContentStorageChanges`, `createContentStorageProjection`,
`createContentStorageSelectorProjection`,
`executeContentStorageMutation`, `executeContentStorageTextReplacement`,
`executeContentStoragePropMutation`, and
`executeContentStorageStructuralMutation`
- `applyMdxContentStorageChanges` and `prepareMdxContentStorageWrites`;
replace them with one post-mutation snapshot serializer built from the
reusable pure `reconcileMdxAuthoredContent` converter
- `createContentBlockApplicationOperations` and the persistence-plan
wrappers that route individual editing commands
- Builder `$runtime*` projected stores, materialized mutation functions,
alternate selector/tree helpers, pending projected-change state, and
MDX-specific mutation sequences from `content-block-content.ts`
- Canvas loading/saving/open-file presentation state, MDX history/undo,
and atomic rollback machinery

## Implementation checklist

### 1. Preserve the `main` editing architecture

- [x] Keep normal synchronous insert, text, Enter, slash menu, property,
delete, move, wrap, copy/paste, selection, and focus mutations unchanged
- [x] Materialize connected content through the same runtime instance
interfaces used by ordinary Content Blocks
- [x] Keep connected authored children in memory and exclude them from
persisted build data
- [x] Route persistence only after a synchronous mutation has updated
the canvas
- [x] Never wait for Asset loading, conversion, or saving before
rendering an interaction
- [x] Add no MDX-specific implementation to individual editing commands

### 2. Shared Markdown and MDX conversion

- [x] Parse Markdown and the Markdown portion of MDX through one shared
AST and plugin configuration
- [x] Implement one shared MDX-to-instances converter and one shared
instances-to-MDX converter
- [x] Serialize headings, paragraphs, links, images, lists, tables, task
lists, blockquotes, thematic breaks, code, emphasis, strong,
strikethrough, and other supported GFM structures as Markdown
- [x] Serialize only non-lossless/custom structures as Webstudio JSX
- [x] Preserve nested Markdown in MDX elements, frontmatter, comments,
tight/loose list semantics, code whitespace, reference links, and Asset
references
- [x] Omit transient empty draft paragraphs instead of emitting
`<ws.element ws:tag="p" />`
- [x] Preserve unsupported source text and authored metadata whenever it
cannot be converted safely
- [x] Add deterministic round-trip and canonical-output coverage for
every supported Markdown structure

### 3. Invalid and unsafe MDX

- [x] Preserve file source exactly; never silently repair or rewrite
invalid source
- [x] Ignore imports, exports, expressions, executable JavaScript,
invalid properties, and other unsupported nodes when they can be
isolated
- [x] Continue rendering valid siblings and report every skipped subtree
once with filename, line, and column
- [x] Use the same recovery pipeline in Builder and publication so both
render the same authored result for the current file revision
- [x] When structural syntax prevents recovery, render no authored file
content in Builder or publication instead of retaining a stale
materialization
- [x] Skip an unrecoverable Content Block on published sites and
continue the build with a warning
- [x] Keep invalid and unsafe files editable and reconnectable
- [x] Enforce UTF-8, byte-size, depth, node-count, property-count, and
generated-output limits with source-located diagnostics where possible

### 4. File formats and Asset creation

- [x] Keep `.md` parsing and raw-HTML behavior unchanged
- [x] Support creating, opening, editing, deleting, and recreating
`.mdx` files through the normal text-file UI
- [x] Open `.mdx` in the same editor experience as `.md`
- [x] Always create an independent empty MDX Asset even when identical
empty files exist
- [x] Allow renaming `.md` to `.mdx` without converting or rewriting its
contents; after rename, handle invalid contents through the normal MDX
diagnostics and recovery pipeline
- [x] Update an already-open MDX editor immediately after canvas
persistence
- [x] Bound read/write buffering and verify the returned Asset identity
and revision

### 5. Source contracts and lifecycle

- [x] Support direct Asset bindings and dynamic expression bindings
- [x] Keep source mutation controls available only in Design mode; show
the connected filename and **Open** action read-only in Content mode
- [x] Reject duplicate source props, unsupported prop types, missing
Assets, non-MDX Assets, and unauthorized Assets
- [x] Analyze selected file diagnostics before confirmation without
modifying the block or file; MDX syntax diagnostics do not block
connection
- [x] For a non-empty block, show **Abort** and **Connect** and explain
that ordinary children will be replaced
- [x] On connect, remove every non-template child, preserve Templates,
set `src`, and materialize file content
- [x] Replace disconnect handoff with normal `src` reset; discard
derived content and leave the block empty
- [x] Remove disconnect confirmation and conversion; resetting a
repeated binding leaves every occurrence empty
- [x] Switching sources validates/loads the target before replacing the
usable binding and leaves both files unchanged
- [x] Revalidate Asset revision and project version when confirmation is
submitted
- [x] Make repeated connect/disconnect operations idempotent
- [x] Prevent disposed, stale, or out-of-order loads from replacing the
newest source
- [x] Keep loading, saving, conflict, empty-file, and open-file actions
off canvas

### 6. Asynchronous persistence and conflicts

- [x] Snapshot the current in-memory authored root after normal
mutations
- [x] Serialize/coalesce rapid edits per resolved Asset and always
prepare against the latest local snapshot
- [x] Allow independent Assets to save concurrently without scope
leakage
- [x] Use one revisioned document session and one ordered save queue per
Asset, even when multiple Content Blocks or render scopes reference it
- [x] After a shared Asset changes, rematerialize every connected
occurrence without persisting their generated instances to project data
- [x] Pin the resolved Asset and exact loaded revision for each write
- [x] Recheck authorization immediately before storage
- [x] Ensure local queued edits never produce stale-revision conflicts
with each other
- [x] On a genuine external revision conflict, preserve local content,
stop writes, and enter the standard reload-required state
- [x] Keep failed non-conflicting writes retryable without discarding
local content
- [x] Finish already accepted persistence writes after a Content Block
unmounts or switches source
- [x] Cancel obsolete loads, materializations, and UI updates after
unmount, reload, or source switch
- [x] Dispose project-scoped roots, queues, parse caches, failure state,
generations, and session subscriptions when the Asset session is
replaced
- [x] Invalidate Asset resources and synchronize open file editors after
successful writes
- [x] Keep multi-root persistence ordered, serial, and non-atomic;
report partial completion without rollback
- [x] Do not add Asset-history undo/redo; native text-editor undo
remains local to the open editor

### 7. Content mode parity

- [x] Empty connected blocks remain selectable and expose the normal
Content-mode `+` affordance
- [x] First insertion renders immediately
- [x] Enter creates and focuses the next paragraph immediately
- [x] Slash commands work in newly created empty paragraphs
- [x] Deleting one selected instance deletes exactly that instance
- [x] Mouse and keyboard moves use the same operation and permissions
- [x] Preserve sibling reorder, nested reparenting, and moves between
editable Content Blocks where `main` permits them
- [x] Preserve content-editable props such as Link `href`
- [x] Preserve copy, paste, cut, multi-cut, wrapping, unwrapping, grid
insertion, selection, Navigator order, and canvas order
- [x] Cover mutation routing centrally, retain the full unconnected
Builder suite, and exercise representative connected interactions in
real Builder E2E

### 8. Template names and permissions

- [x] Resolve only exact user-facing names from the direct flat
Templates list
- [x] Enforce unique names within each Templates list
- [x] Reject duplicate names during rename with inline validation
- [x] Allocate unique names during insert, paste, duplicate, move, wrap,
and unwrap
- [x] Apply valid template properties using the same permissions as
Content mode
- [x] Preserve and warn about ignored design-only, invalid, or stale
properties
- [x] Preserve template shell provenance without serializing expanded
template internals
- [x] Generate deterministic materialized IDs from source identity,
render scope, and authored usage path so focus/selection survives saves
- [x] Warn before renaming or deleting referenced templates; files
remain unchanged
- [x] Provide shared AST-based rename/remove migration operations for
MCP-assisted multi-file cleanup

### 9. Scope, frontmatter, and diagnostics

- [x] Scope materialized content by Content Block ID plus exact
Collection-item/render context
- [x] Prevent repeated instances and dynamic candidates from leaking
generated IDs, template resolution, or diagnostics across scopes while
sharing the underlying Asset source and revision where applicable
- [x] Remove frontmatter editing from Settings; edit the exact YAML
through the MDX Asset file editor
- [x] Preserve the exact frontmatter source byte-for-byte during canvas
body saves
- [x] Route canvas body changes and complete-file editor saves through
one revisioned per-Asset coordinator
- [x] Show a source warning indicator in Settings and precise
source-located diagnostics in the Asset editor
- [x] Deduplicate repeated diagnostics without losing distinct locations
- [x] Keep unresolved-template placeholders selectable and accessible
only in Builder

### 10. Asset references, transfer, and integrity

- [x] Discover and rewrite Asset references in frontmatter, Markdown
links/images, and MDX properties
- [x] Preserve Asset references while editing unrelated content
- [x] Include referenced Asset and template revisions in
dependency/cache identity
- [x] Route referenced Assets through published URL rewriting
- [x] Validate Content Block source integrity during project import,
fragment/page transfer, copy/paste, build integrity, and pre-publish
audit
- [x] Allow multiple Content Blocks and dynamic render scopes to
reference the same MDX Asset without treating the connection as an
integrity error
- [x] Preserve Templates when copying a connected Content Block
- [x] Preserve direct and dynamic Content Block source bindings when
copying or pasting within the same project
- [x] When copying only one rendered Collection item, resolve that
item’s current MDX Asset and replace the copied Content Block’s dynamic
source with a direct binding to that same Asset
- [x] When copying an entire Collection, preserve the Collection, its
instances, and its dynamic source bindings
- [x] Preserve the complete MDX source and frontmatter by reference;
copying a connected block must not rewrite the shared file
- [x] During cross-project transfer, copy every discoverable distinct
bound MDX Asset and rewrite transferred bindings to the destination
Assets
- [x] If some cross-project dynamic candidates cannot be discovered or
copied, continue with successful copies, preserve what can be
represented safely, and warn about skipped candidates
- [x] Revalidate source revisions and the destination project before
applying a cross-project transfer
- [x] If cross-project Asset creation or project insertion fails, leave
the source project unchanged and clean up any newly reserved destination
Asset
- [x] Use the same transfer operation through Builder and MCP

### 11. Dynamic sources and publication

- [x] Resolve dynamic bindings once per render/save scope
- [x] Require finite, discoverable candidate sets for publication and
load no unrelated MDX
- [x] Warn and skip unbounded, missing, unreadable, malformed, or unsafe
sources without failing the complete build
- [x] Materialize only rendered Content Blocks; ignore Templates
definitions and `src` on non-Content-Block instances
- [x] Skip unresolved template subtrees while keeping valid siblings
- [x] Include selected template styles, fonts, resources, unresolved
names, and referenced Asset revisions in generated dependency output
- [x] Keep draft-only MDX Assets out of publication retention

### 12. Builder, MCP, CLI, and shared operations

- [x] Use the same converters, source lifecycle, revision checks,
persistence service, diagnostics, and template migrations in Builder and
MCP
- [x] Keep frontmatter editing file-based; retain whole-frontmatter
runtime operations only where compatibility requires them
- [x] Avoid Builder-only or MCP-only mutation/conversion implementations
- [x] Regenerate runtime/API contracts from their source definitions
- [x] Update CLI Content Engine reference and generated MCP
documentation

### 13. Verification and delivery

- [x] Add regression tests that reproduce failures from the previous
implementation, including double deletion and blocked rendering
- [x] Cover two Content Blocks sharing one Asset: edits from either
block serialize once, update both canvases, preserve scope-specific
Templates, and cannot overwrite a newer local snapshot
- [x] Verify new tests fail against the broken implementation and pass
with the corrected behavior
- [x] Run SDK, Content Engine, Asset Uploader, Project Build, Builder,
React SDK, CLI, Protocol, and HTTP Client affected suites and typechecks
- [x] Run real Builder E2E for source lifecycle, live file refresh,
empty insertion, Enter/slash focus, Link props, delete, keyboard
reorder, switching, disconnect, conflicts, unresolved templates, dynamic
sources, and repeated scopes
- [x] Regenerate shared project fixture bundles and verify a second
generation leaves the tree clean
- [x] Run lint, package boundaries, `pnpm oxfmt --check`, and `git diff
--check`
- [x] Review and update authoritative `docs/` content and navigation
- [ ] Run the complete agent evaluation suite — not run because it
requires separate explicit approval

### 14. Content-mode parity and disconnect handoff

- [x] Allow keyboard reordering in Content mode through the normal move
command while keeping the editable Content Block boundary
- [x] Let already accepted Asset writes drain independently before
resetting the source; disconnect does not load, flush, or convert the
file
- [x] Remove MDX-to-instance copying from disconnect
- [x] Reset `src`, remove the derived tree, and leave the ordinary
Content Block empty
- [x] Preserve automatic text-editor focus after inserting editable
content from the template menu
- [x] Remove Builder frontmatter-save UI and report complete-file save
failures through the Asset editor
- [x] Add regression coverage for keyboard movement, disconnect
teardown, source switching, insertion focus, and paragraph deletion
focus restoration
- [x] Run the complete six-scenario MDX Content Block Builder E2E suite

### 15. Final architecture review fixes

- [x] Keep one canonical ordered pending document per Asset so shared
Content Block occurrences cannot conflict with one another
- [x] Merge ordered local edits from different occurrences while
preserving text changes, insertions, deletions, and sibling reordering;
keep external revisions on the strict reload-required path
- [x] Centralize typed render-scope parsing, repeated-occurrence
detection, scoped variable lookup, and dynamic Asset resolution across
Canvas, Settings, source lifecycle, and copy/paste
- [x] Capture the owning Asset session when a save is accepted so normal
unmount/source-switch teardown cannot redirect or lose it
- [x] Dispose project-owned roots, queues, caches, generations, failure
state, and subscriptions when replacing the project Asset session
- [x] Add regression coverage for same-Asset edits from two occurrences,
same-node last-write ordering, structural reorder, insertion
preservation, scoped source resolution, and project cleanup
- [x] Re-run affected full unit suites, typechecks, production build,
static checks, and all six MDX Content Block Builder E2E scenarios


### 16. Final persistence and transfer hardening

- [x] Drain every accepted per-Asset edit before project-session
teardown while retaining the owning authorization context
- [x] Drain canvas serialization queues and revisioned Asset writes
before pre-publish audit and publication
- [x] Block publication on a queued serialization failure or Asset
revision conflict
- [x] Copy actual Asset bytes during cross-project paste, preserve MDX
reference names, rewrite direct and Collection-backed Asset IDs, and
clean up newly created Assets when insertion fails
- [x] Include every resolved dynamic MDX source when copying an entire
Collection and warn while preserving successful copies when individual
Assets cannot be transferred
- [x] Keep MDX editor save failures visible with retry and route
conflicts through the standard reload-required flow
- [x] Give keyboard nested reparenting the same editable Content Block
boundary used by pointer movement
- [x] Add regression coverage and rerun the complete Content Engine and
Builder unit suites plus type, lint, formatting, package-boundary, and
diff checks

## Current rebuild status

- The connected Content Block now owns one complete MDX document:
frontmatter feeds designed-shell bindings and the explicit Body outlet
owns the authored MDX body.
- Builder and published output resolve the same frontmatter document
graph, including nested document references and Asset references.
- Direct frontmatter text/property edits use the existing ordered
per-Asset session; referenced-document values remain file-owned.
- Repeated Collection occurrences keep isolated runtime shell/Body
identities and occurrence-specific document values.
- The local blog article layout has been upgraded to the document/Body
model and its bindings validate cleanly.
- Full affected package suites and typechecks pass; every new regression
was demonstrated fail/pass.
- `pnpm lint`, package boundaries, `pnpm oxfmt --check`, generated
API/docs checks, fixture builds, and `git diff --check` pass.
- Full fixture synchronization is blocked by the development API
rejecting this local CLI version before fixture generation; existing
fixture bundles build successfully.
- Complete agent evaluations remain pending explicit approval.

### 17. Treat Content Block source as a property

- [x] Declare Content Block `src` in component metadata as a Design-mode
initial property labeled **Source**
- [x] Add the short property description: “Create an .mdx file in
Assets, then select or bind it here.”
- [x] Accept only a direct Asset or an expression resolving to an Asset
ID; reject URL/string sources, missing Assets, and non-MDX Assets
- [x] Extract and reuse the Image-style Asset picker and binding
presentation without duplicating source-control UI
- [x] Render Source through the normal properties section and remove the
separate source-section placement and special `src` filtering
- [x] Route Source changes through Content Block connect, switch, and
disconnect lifecycle operations instead of generic prop updates
- [x] Keep connect confirmation, Open, diagnostics, and persistence
state attached to Source; remove frontmatter and disconnect UI
- [x] Add regression coverage for direct Assets, dynamic Asset bindings,
invalid resolved values, lifecycle operations, and Design/Content mode
visibility
- [x] Re-review authoritative `docs/` content for the Source-property UI
change and update it if required

### 18. Source property UX

- [x] Show one full-width bindable Connect .mdx file button while
disconnected
- [x] Show equal-width filename and Open buttons while connected
- [x] Switch files from the filename button through the source lifecycle
- [x] Override PropertyLabel reset and Alt-click with the disconnect
lifecycle
- [x] Preserve confirmation, pending, failure, repeated-scope, and
dynamic-source behavior
- [x] Add regression coverage for connect, switch, binding, reset, and
disconnect
- [x] Update Content Block documentation
- [x] Run affected tests, typecheck, lint, formatting, package
boundaries, and diff checks


### 19. Reduced file-owned frontmatter follow-up

This checklist supersedes the earlier structured-frontmatter and
disconnect-copy behavior. Frontmatter remains file-owned and is edited
only in the MDX Asset editor.

#### A. Remove structured frontmatter UI

- [x] Remove the JSON frontmatter editor and unused Builder
controller/state
- [x] Keep source mutation Design-mode-only; show connected Source
read-only in Content mode and allow authorized editors to open the
complete file
- [x] Retain runtime frontmatter APIs only where compatibility requires
them

#### B. Preserve source and separate validation

- [x] Preserve the exact frontmatter envelope during every canvas body
save without parsing/stringifying YAML
- [x] Preserve comments, ordering, quoting, whitespace, BOM, newline
style, delimiters, and invalid but closed YAML
- [x] Keep the existing unsupported-node/property MDX recovery; do not
add an ad hoc partial parser
- [x] Parse body and frontmatter independently so either valid half
remains usable
- [x] Keep bounded Asset-query frontmatter extraction unchanged
- [x] Treat structurally malformed MDX as having no safe body tree

#### C. Share Asset state with the raw editor

- [x] Route canvas and complete-file changes through one ordered,
non-blocking per-Asset coordinator
- [x] Update canvas and clean raw editors immediately from shared
in-memory source
- [x] Reject stale dirty-editor saves, preserve unsaved text, and
require reload; never force-overwrite
- [x] Drain accepted writes after source replacement/disconnect and
report background failures globally
- [x] Dispose sessions only after they have no consumers and no queued
work

#### D. Connect, replace, and disconnect

- [x] Load and diagnose before connect; block only
unreadable/unauthorized/non-MDX Assets
- [x] Show **Abort / Connect** for non-empty blocks, including
diagnostics and the recoverable-content warning
- [x] Set `src` and delete persisted children through one runtime
mutation
- [x] Switch to a loaded source without waiting for the previous Asset's
network save
- [x] Remove disconnect confirmation and conversion
- [x] Reset `src` immediately, discard the derived tree, leave the block
empty, and preserve the Asset
- [x] Resetting a bound source leaves every repeated occurrence empty

#### E. Dynamic and shared sources

- [x] Keep one source/revision state per Asset and a separate derived
instances tree per occurrence
- [x] Resolve Templates independently per Content Block and preserve
Builder-only missing-template placeholders
- [x] Resolve bound `src` from the selected Collection occurrence
- [x] Make **Open** use the occurrence's resolved Asset; update the
filename and disable Open when unresolved
- [x] Add direct/bound tests including Collection item A opening `a.mdx`
and item B opening `b.mdx`

#### F. Diagnostics, MCP, and publication

- [x] Show an accessible warning icon beside Source with the first
diagnostic, line/column, and remaining count
- [x] Show precise YAML/MDX diagnostics in the Asset editor without
repetitive canvas/toast UI
- [x] Reuse parser/diagnostic/revision contracts in Builder, build,
publication, and MCP
- [x] Keep MCP frontmatter editing file-based and return structured
diagnostics for complete-source writes
- [x] Emit build warnings; published sites skip invalid/unsupported
content without diagnostic UI

#### G. Verification and documentation

- [x] Add fail/pass regressions for source preservation, independent
validation, stale raw saves, lifecycle, dynamic Open, shared Assets, and
cleanup
- [x] Run affected tests, typechecks, lint, formatting, package
boundaries, fixtures, and diff checks
- [x] Open Markdown and MDX editors at twice the default dialog size
with the right-side preview visible initially
- [x] Document canvas body editing, file-owned frontmatter, Content-mode
Asset access, and cloning an MDX Asset for a new post
- [x] Perform a final correctness, data-loss, DRY, simplification,
accessibility, and performance review
- [x] Keep this checklist synchronized with implementation status

### 20. Content-mode component properties

- [x] Show a connected Content Block Source read-only in Content mode
with an active **Open** action
- [x] Keep source switching, binding, reset, and disconnect available
only in Design mode
- [x] Expose HTML Embed code and preserve Code Text's code-editor
metadata on authored Text Content
- [x] Audit every registered component and expose authored payload while
keeping design, structure, and behavior controls in Design mode
- [x] Keep media dimensions and Code Text theme Design-only while
preserving adapter-owned intrinsic Image metadata during MDX round trips
- [x] Add exact component-permission and regression coverage
- [x] Update authoritative component documentation
- [x] Run affected full suites, typechecks, formatting, lint, package
boundaries, and generated contract/documentation checks


### 21. Designed document shell and Body outlet

- [x] Add one structural **Content Block Body** outlet and keep legacy
Content Blocks without it compatible
- [x] Materialize and persist only `document.body` children through the
Body outlet while preserving the surrounding designed shell and
Templates
- [x] Expose the connected document frontmatter through a Content Block
`document` parameter for shell text and property bindings
- [x] Write direct frontmatter-bound text and properties back through
the same ordered per-Asset session without blocking canvas mutations
- [x] Resolve document `$ref` dependencies and Asset references
consistently in Builder and published output
- [x] Keep referenced-document values read-only on canvas and direct
editors to the referenced file
- [x] Isolate repeated Collection occurrences while retaining
occurrence-specific source, frontmatter, shell, and Body content
- [x] Render the same designed shell, frontmatter values, and Body
substitution in generated/published output
- [x] Upgrade the local blog article layout to bind title, excerpt,
dates, author data, and images from frontmatter and render MDX through
Body
- [x] Add fail/pass regressions for nested Body discovery, lifecycle,
permissions, repeated values, document references, and generated shell
rendering
- [x] Update authoritative Content Block documentation
- [x] Run affected tests and typechecks, formatting, lint, package
boundaries, generated API/docs checks, and fixture builds


### 22. Final nested references and frontmatter editing

- [x] Keep direct frontmatter-bound text and property controls editable
in Content mode without exposing or replacing their bindings
- [x] Keep referenced-document values read-only and preserve legacy
instance-property name normalization
- [x] Render direct frontmatter text bindings through the plain-text
editing path
- [x] Resolve nested legacy and structured Asset references from
referenced Markdown/MDX frontmatter
- [x] Preserve missing Asset references, emit structured
`ASSET_NOT_FOUND` diagnostics, and keep them out of the document graph
- [x] Add fail/pass regressions for the real Settings control and
root/nested missing Asset-reference cases
- [x] Fix exact Content Block selection after the Body node appears in
Navigator
- [x] Run full affected suites/typechecks, all six MDX Content Block E2E
scenarios, deterministic fixture builds, generated checks, lint,
formatting, package boundaries, and diff checks

### Before merge

- [x] Resolve #6261: Nested Asset references in referenced Markdown
frontmatter work consistently in Assets queries, previews, publication,
and static export


### 23. Explicit writable expression bindings

- [x] Add an explicit `readwrite` mode to expression bindings; existing
expressions remain read-only by default
- [x] Accept `readwrite` only for direct static member paths and
centralize their parsing and validation
- [x] Require the expression root to provide a writable data source;
initially support the connected Content Block document frontmatter
- [x] Update Content Block permissions, canvas text editing, and
property controls to require a valid writable binding
- [x] Persist direct frontmatter edits through the existing ordered
per-Asset session
- [x] Create new direct frontmatter bindings with `readwrite` mode and
migrate existing compatible bindings
- [x] Preserve writable mode through schemas, serialization, loading,
copy/paste, transfer, and export
- [x] Add fail/pass regressions for valid paths, derived expressions,
unsupported sources, permissions, persistence, and compatibility
- [x] Review authoritative `docs/` content and update it if the
persisted binding contract affects user-facing documentation
- [x] Reject unsafe frontmatter paths and reject `readwrite` bindings
outside a connected Content Block document
- [x] Preserve expression binding mode through the public HTTP client
and document the MCP authoring contract
- [x] Limit frontmatter value write-back to Content mode so Design mode
retains normal binding replacement/reset behavior
- [x] Keep bindings inside Templates and across nested Content Block
ownership boundaries read-only
- [x] Upgrade compatible legacy bindings even when the Content Block is
disconnected during migration
- [x] Run affected tests, typechecks, formatting, lint, package
boundaries, fixture checks, and `git diff --check`

Verification: full SDK (567), Project Build (2,277), and Builder (2,695)
suites pass, along with affected Expression, Migration, Template, HTTP
Client, and MCP suites; typechecks, lint, formatting, package
boundaries, and diff checks pass. Generated contracts are refreshed.
Fixture synchronization remains blocked before generation because the
development API rejects this local CLI version as incompatible. The
checked-in bundles pass the current Protocol suite and every fixture
build with the current bundle version.
2026-08-29 20:15:20 +02:00
Oleg Isonen 7e7c14868a fix: Preserve read-only guides and publish targets (#6266)
## Summary

- Route explicit read-only `meta.guide` requests to focused discovery
tools and exclude mutations, side-effecting session tools, broad design
context, and visual verification.
- Require explicit task scope, specialized workflow, authored-fragment
routing, and design-system reuse instead of inferring behavior from
brief prose.
- Persist the requested staging or production target in new SaaS
deployment records.
- Return the same target from publish list and job status, with
backward-compatible inference for historical records.

## Todo

- [x] Reproduce the read-only custom-code audit misrouting from #6262.
- [x] Add failing regressions and implement strict read-only routing.
- [x] Remove behavior-affecting prose inference from CLI/MCP guide
routing.
- [x] Reproduce the single-domain production target mismatch from #6263.
- [x] Add create-to-list/status regressions and persist the explicit
target.
- [x] Cover historical deployment records that predate the stored
target.
- [x] Verify production create → list → get-job through the staging
deployment.
- [x] Regenerate and verify project fixtures against the changed bundle
contract.
- [x] Review documentation impact and update the generated MCP manual.
- [x] Review the complete diff for correctness, compatibility,
duplication, and unnecessary complexity.

## Verification

- Real staging publish for #6263 — passed; create, list, and get-job
consistently reported `production` for a one-domain publish. The
supplied project has no custom domains, so the custom-domain variant was
not available. The job remained `pending` during this check.
- Real local CLI/MCP verification for #6262 — passed; no mutation or
side-effecting tools leaked.
- `pnpm --filter @webstudio-is/protocol test -- src/fixtures.test.ts` —
17 passed
- `pnpm -r fixtures:build` — passed for all eight fixtures
- `pnpm --filter @webstudio-is/project-build test` — 2,134 passed
- `pnpm --filter webstudio test` — 1,037 passed; the one payload-size
regression was fixed and its targeted test passed
- `pnpm --filter @webstudio-is/domain test` — 24 passed
- `pnpm --filter @webstudio-is/sdk test` — 519 passed
- Builder API router test — 30 passed
- Relevant package typechecks — passed
- `pnpm lint`
- `pnpm check:package-boundaries`
- `pnpm check:generated-api`
- `pnpm check:generated-docs`
- Regression tests were demonstrated failing against the previous
behavior and passing with the fixes.
- Agent evaluations were not run because they require separate explicit
approval.

Closes #6262
Closes #6263
2026-08-29 18:54:05 +02:00
Oleg Isonen 471f504087 feat: Select unused assets before deleting (#6245)
Closes #6243

## Summary

- Add checked-by-default controls for every asset in the **Delete unused
assets** dialog.
- Add a footer **Select all** control that reflects the complete
selection and toggles all assets.
- Delete only selected assets that remain unused and disable deletion
when the selection is empty.
- Keep the Assets documentation aligned with the selective deletion
workflow.

## Implementation

The dialog owns a set of selected asset IDs initialized from the
unused-assets result. Individual checkboxes update that set, while
**Select all** replaces it with either every currently unused ID or an
empty set.

Asset usage inputs remain subscribed while the dialog is open. The
deletion payload is intersected with the current unused-assets list, and
this cleanup path does not force deletion. If an asset becomes
referenced before the mutation executes, the runtime rejects its
deletion instead of removing a now-used asset.

## Todo

- [x] Add per-asset selection controls.
- [x] Add and position the **Select all** footer control.
- [x] Limit deletion to selected asset IDs that remain unused.
- [x] Protect against assets becoming referenced while the dialog is
open.
- [x] Add regression tests for individual selection, select-all
behavior, empty-selection protection, selective deletion, and live usage
changes.
- [x] Review documentation impact and update the Assets guides.
- [x] Verify formatting, lint, types, and Asset Manager/assets tests.

## Verification

- `pnpm --filter @webstudio-is/builder exec vitest run
app/builder/shared/asset-manager app/builder/shared/assets` — 26 files,
221 tests passed.
- `pnpm --filter @webstudio-is/builder typecheck` — passed.
- `pnpm exec oxlint --deny-warnings
apps/builder/app/builder/shared/assets/delete-assets.ts
apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx`
— passed.
- `pnpm exec oxfmt --check
apps/builder/app/builder/shared/assets/delete-assets.ts
apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx`
— passed.
- Both regression tests were confirmed failing before their respective
implementations and passing afterward.

## Compatibility and follow-ups

No data migrations, public API changes, fixture changes, or known
follow-ups.
2026-08-26 12:14:06 +02:00
Oleg Isonen db2175f333 fix: transfer pasted assets across deployments (#6228)
Closes #6227

## What changed

Cross-deployment copy/paste now transfers referenced assets into the
destination project before inserting instances, pages, templates, or
folders.

- Add optional source deployment metadata to the existing v0.1 clipboard
formats.
- Keep old v0.1 payloads readable and keep new payloads readable by
older builders, which ignore the additive field.
- Reuse the existing asset upload-by-URL flow for images, fonts, videos,
and files.
- Preserve source video dimensions through the existing upload route.
- Replace source asset IDs and font-family references with destination
values before runtime insertion.
- Include and remap page social images and marketplace thumbnails.
- Reject current clipboard payloads whose page metadata references
omitted assets.
- Leave the public `pageTransfer.insert` runtime input unchanged.
- Abort insertion with a paste error when an asset cannot be imported.

No clipboard version increase, custom network fetcher, address
blocklist, rollback framework, or global paste wrapper is introduced. If
a multi-asset import partially uploads before a later upload fails, the
completed uploads may remain unused.

## Checklist

- [x] Rebased onto `main`
- [x] Preserve the existing v0.1 clipboard format
- [x] Transfer and remap instance assets
- [x] Transfer and remap page, template, and folder assets
- [x] Preserve video metadata
- [x] Keep runtime page-transfer API compatible
- [x] Add regression coverage
- [x] Review documentation impact and update page-copy documentation
- [x] Run Builder tests and typecheck
- [x] Run project-build tests and typecheck
- [x] Run lint, package-boundary, and generated-API checks

## Verification

- Builder full suite: 219 files, 2,552 tests passed
- Project-build full suite: 78 files, 2,129 tests passed
- Final affected suite: 84 tests passed
- New regressions were confirmed failing before the fixes and passing
afterward
- Builder and project-build typechecks passed
- `pnpm lint` passed
- `pnpm check:package-boundaries` passed
- `pnpm check:generated-api` passed
- Fixture inputs and generated fixture bundles are unaffected
2026-08-25 16:44:38 +02:00
Oleg Isonen 130d371759 perf: Skip resources in statically hidden subtrees (#6233)
## Summary

- Skip read-time resources scoped to an instance with literal
`show=false` or any descendant of that instance.
- Use the same static reachability rule in the Builder client preloader
and CLI-generated published resource map.
- Keep dynamic `show` expressions on the existing loading path because
their result may depend on resource data.

## Data path and performance

In the Builder, the client-side resource request set now excludes
statically hidden subtrees before requests enter the preloader.

For generated sites, the CLI still scans project instances and props
during build, but removes statically hidden subtrees from the page build
data. Their read resources therefore never enter the generated
server-side resource map and no corresponding resource network request
runs during page rendering.

This removes request and server/network cost for literal-`false`
subtrees. It does not remove build-time project scanning, and resources
under dynamic conditions still load.

## Compatibility

- No project schema or persisted data changes.
- No migrations.
- Action-bound resources retain their existing explicit-trigger
behavior.
- Dynamic `show` expressions retain current behavior.

## Checklist

- [x] Add shared static-subtree reachability logic.
- [x] Apply it to Builder preview resource preloading.
- [x] Apply it to generated/published resource collection.
- [x] Add Builder and generated-output regressions for direct,
descendant, visible, and dynamic cases.
- [x] Demonstrate the new regressions fail against the previous behavior
and pass with the implementation.
- [x] Review authoritative `docs/` content; no documentation update is
required because the UI and authoring workflow are unchanged.
- [x] Review fixture inputs and outputs; no fixture contains this
resource/show combination, so fixture regeneration is not required.

## Verification

- `pnpm --filter @webstudio-is/sdk test`
- `pnpm --filter @webstudio-is/react-sdk test`
- `pnpm --filter @webstudio-is/builder exec vitest run
app/shared/nano-states/props.test.tsx`
- `pnpm --filter webstudio build:content-runtime`
- `pnpm --filter webstudio exec vitest run src/prebuild.test.ts`
- Typechecks for SDK, React SDK, Builder, and CLI
- Targeted `oxlint --deny-warnings`
- `git diff --check`

Agent evaluations were not run because they require separate explicit
approval.

Closes #6232
2026-08-24 18:45:46 +02:00
Oleg Isonen df3601c26a fix: Capture preview failure diagnostics (#6206)
## Summary

- Give invalid project bundles a stable `PROJECT_BUNDLE_INVALID` error
code and structured validation issues.
- Remember the latest failed MCP tool call and attach sanitized
diagnostics to automatic issue reports.
- Render the tool, error code, bundle contract, and invalid schema paths
in a dedicated issue section.

## Scope and issue assessment

This PR improves diagnostics; it does not change which asset shapes
`preview.start` accepts.

Issue #6198 came from CLI 0.290.0 and did not include the rejected
field, value, or bundle contract, so its exact root cause cannot be
established. Node 22 is not implicated by the available evidence.
Canonical video assets were added separately in #6189, which may explain
an old-CLI schema mismatch, but that relationship is an inference rather
than a confirmed reproduction.

Per project triage policy, this PR closes #6198 despite being
diagnostics-only. If the failure still exists on a current CLI, the
enriched report will provide enough evidence to reopen or file a new
actionable issue.

## Implementation

Bundle validation exposes structured paths such as `assets.0.type`. The
MCP host records the latest failure and injects it into CLI-owned
runtime metadata when `report-issue` is called.

The MCP registry supplies either a canonical known tool name or
`unknown`. Stable error codes are validated once by the CLI error-code
boundary. Detailed paths are included only for `PROJECT_BUNDLE_INVALID`,
capped at 30 issues, and omit received values, error messages, examples,
filenames, IDs, details, and stack traces. The bundle-contract field
remains optional so reports from older CLI versions still validate.

CLI-owned runtime metadata is not advertised as model-authored MCP
input, keeping the handshake compact and making ownership explicit.

## Checklist

- [x] Add structured bundle validation diagnostics.
- [x] Capture the latest MCP failure in issue-report runtime metadata.
- [x] Render deterministic diagnostics in GitHub issue bodies.
- [x] Add fail/pass regression coverage and privacy constraints.
- [x] Keep CLI-owned runtime fields out of the model-facing MCP schema.
- [x] Regenerate the server-only API contract.
- [x] Review documentation impact — no product documentation changes are
required; this only enriches internal anonymous issue reports.
- [ ] Run agent evaluations — not run because repository policy requires
explicit approval.

## Verification

- Real Node 22.22.1 stdio MCP run with an isolated malformed local
bundle returned `PROJECT_BUNDLE_INVALID`, path `assets.0.type`, code
`invalid_value`, and constraint `one_of:["image"]`.
- The following real `report-issue` call was accepted by the server and
deduplicated to existing issue #6198; it created no duplicate issue and
changed no linked project.
- Project-build: 2,115 tests passed.
- CLI: all 1,005 unaffected tests passed; one unrelated
process-supervisor timing test failed once and its exact two
owner-disconnect cases passed on immediate rerun.
- Project-build and CLI typechecks passed.
- Formatter and diff checks passed.
- All latest GitHub workflows passed, including both test/typecheck
matrices, visual regression, size and generated checks, packaged SSG,
and all six Builder E2E shards.

Closes #6198
2026-08-20 11:58:17 +02:00
Oleg Isonen 0760d6cfec fix: upload videos from Builder and MCP (#6189)
## Summary

Video uploads failed because file detection returned `video` while the
canonical Asset schema accepted only `font | image | file`. The mismatch
was introduced when video detection was added in #5539; the recent JSON
work only exposed the adjacent contract gap and did not cause it.

This makes `video` a first-class `Asset["type"]` across Builder, SDK,
storage formatting, project bundles, HTTP uploads, and MCP. There is no
separate upload-only type and no conversion from `video` to `file`.

## Implementation

- Add the canonical `video` Asset variant with width/height metadata.
- Make Builder UI reservations and optimistic assets preserve `video`.
- Make MCP and HTTP upload schemas derive their enum from the canonical
SDK `assetType`.
- Preserve video metadata through S3 and filesystem upload paths.
- Include canonical video assets in project/canvas bundles.
- Keep legacy video records without dimension metadata readable as
generic `file` assets.
- Fall back to a labeled file preview when the browser cannot decode a
video format such as AVI; browser-supported formats continue to render
video thumbnails.
- Regenerate runtime operation contracts and sync fixtures from the PR
deployment.

## Contract protection

- Assert every detected upload category parses as a canonical Asset
type.
- Exercise Builder reservations for every value in `assetType.options`.
- Assert MCP's upload enum exactly equals `assetType.options`.
- Exercise direct HTTP video upload metadata and URL construction.
- Cover canonical video formatting, legacy fallback, preview assets, and
canvas serialization.
- Verify a video decode error replaces the blank media element with a
visible format-labeled fallback.
- Store canonical WebM and MP4 records with dimensions in the
`webstudio-features` fixture and verify generated runtime metadata.

## Checklist

- [x] Make video a canonical Asset type
- [x] Verify Builder UI upload flow
- [x] Verify MCP and direct HTTP upload contracts
- [x] Add fail/pass regression coverage for the broken paths
- [x] Add an Assets panel fallback for browser-unsupported video formats
- [x] Regenerate runtime contracts
- [x] Sync and build fixtures against the PR deployment
- [x] Run affected package tests, typechecks, lint, package-boundary,
generated API, and generated docs checks
- [x] Review documentation impact — existing Assets documentation
already lists supported video formats and upload behavior; no
user-facing documentation change is required

## Verification

- Builder: 2,543 tests passed
- Builder asset thumbnail regression: 14 tests passed
- Project build/MCP runtime: 2,111 tests passed
- CLI: 999 tests passed
- SDK: 516 tests passed
- Asset uploader: 199 tests passed
- Protocol: 92 tests passed
- HTTP client: 38 tests passed
- Typechecks passed for Builder, SDK, asset uploader, project build,
protocol, HTTP client, and CLI
- Lint and package-boundary checks passed
- Generated API and documentation checks passed
- Fixture sync completed against
`fix-video-up-be4d8a0.development.webstudio.is`
- All fixture builds passed after synchronization

Closes #6186
2026-08-19 00:21:11 +02:00
Oleg Isonen 5a57234c75 revert: Store Content Block content in MDX assets
Revert the accidental merge of #6125 so the implementation can continue in draft PR #6181.
2026-08-18 13:23:32 +01:00
Oleg Isonen 5ec3547d36 fix: Support JSON content files in Builder (#6168)
## Summary

- make the complete asset filename editable in Asset settings
- convert existing editable text assets when their extension changes
while preserving the asset ID
- accept every JSON root type and normalize JSON-compatible syntax into
formatted strict JSON
- expose the same optional extension change through MCP/API
`update-asset-content`
- initialize new JSON files and empty text-to-JSON conversions with a
valid empty object
- distinguish browser URL imports from JSON file uploads so JSON objects
with a root `url` field remain file content
- update the Assets and Content Engine documentation

## Root cause

Asset settings rendered the extension as a fixed suffix outside the name
input. The metadata rename mutation could only change the display
basename, while content revisions always inherited the current storage
extension. As a result, changing `.md` to `.json` was impossible in the
UI and unavailable through the shared MCP/API revision command.

Asset settings now edits the complete filename. Ordinary renames keep
using the metadata mutation. A text-extension change loads the current
content, validates it for the target format, and writes a new immutable
revision through the existing conflict-safe content endpoint. The
existing Acorn-backed `parseJsonExpression` utility accepts
JSON-compatible syntax without evaluating code and serializes it as
strict JSON. Objects, arrays, strings, numbers, booleans, and `null` are
all accepted.

## Checklist

- [x] Create JSON files by entering a `.json` filename
- [x] Edit the complete filename in Asset settings
- [x] Convert editable text-file extensions while preserving the asset
ID
- [x] Expose extension conversion through `update-asset-content`
- [x] Create JSON files and convert empty text files with a valid empty
object
- [x] Normalize safe JSON-compatible syntax to strict JSON
- [x] Accept objects, arrays, and scalar JSON roots
- [x] Reject executable or incomplete content
- [x] Preserve browser-uploaded JSON object shapes
- [x] Review and update authoritative Builder documentation
- [x] Add focused UI, revision, HTTP-client, CLI/MCP, protocol, and
upload regression tests
- [x] Run affected typechecks, lint, documentation checks, and the
Builder production build
- [ ] Manually verify create, edit, rename `.md` to `.json`, reload
persistence, and Content Engine query in a browser
- [ ] Run the complete local agent evaluation suite if approved

## Verification

- 217 focused tests passed across Builder, asset revisions, HTTP client,
CLI/MCP, and protocol
- Builder, asset-uploader, HTTP-client, protocol, CLI, and project-build
typechecks passed
- Builder production build passed
- MCP and Content Engine documentation checks passed
- `oxlint` on changed TypeScript files passed
- `git diff --check` passed
- Regression tests were demonstrated failing before the implementation
and passing afterward

A disposable E2E database and PostgREST stack bootstrapped successfully
in the earlier real-path test, but UI automation remained blocked
because no controllable browser was available. Fixture inputs and
generated fixture outputs are not affected. Agent evaluations were not
run because approval is required and was not requested.

Closes #6167
2026-08-18 11:39:01 +02:00
Oleg Isonen 86b6310fff feat: Store Content Block content in MDX assets 2026-08-17 15:22:20 +01:00
Oleg Isonen ab5717c9cf feat: Support CSS properties of every status (#6166)
## Summary

- Make every CSS property in the current MDN dataset available in the
Advanced style workflow, regardless of standards status.
- Mark experimental, nonstandard, and obsolete properties with a yellow
warning icon, status-specific tooltip, and MDN link.
- Add complete CSS anchor-positioning property and value support.
- Update `mdn-data` from 2.28.0 to 2.33.0 and `css-tree` from 3.1.0 to
3.2.1.

## Root cause

Webstudio generated its supported property list from MDN data but
filtered by status and then manually allowed a few experimental and
nonstandard entries. A property could therefore exist in the installed
MDN package without being exposed by the Builder.

Runtime validation had a separate grammar gap. CSS-tree 3.2.1 now
includes the anchor functions and alignment values, but its bundled data
predates the current `position-anchor: normal | match-parent` additions.

## Implementation

- Remove status-based property filtering and the nonstandard-property
allowlist.
- Generate one property-to-status map for 486 standard, 40 experimental,
119 nonstandard, and 15 obsolete properties.
- Show status-specific browser-compatibility guidance for every
non-standard status. Active declarations keep the warning after the
value with 3px left spacing.
- Infer MDN links from existing property metadata and fall back to MDN
search for entries without a direct URL.
- Preserve known vendor prefixes from the generated property inventory
instead of maintaining a prefix allowlist.
- Generate WebKit text fill/stroke longhands directly from MDN instead
of preserving them through parser exceptions.
- Preserve unsupported initial-value shapes as unparsed CSS rather than
excluding their properties.
- Use CSS-tree 3.2.1's native anchor-function and alignment grammars.
Keep one narrow extension for the current `position-anchor` keywords
missing from its bundled MDN data.
- Generate recursively flattened shorthand longhands and initial values
from MDN.
- Expand syntax-defined shorthands generically from CSS-tree's matched
property captures, including function-valued components.
- Decline generic expansion when CSS-tree and MDN disagree about the
longhand set or a longhand repeats.
- Update the font grammar reference and CSS math validation for CSS-tree
3.2.1 compatibility.
- Regenerate CSS metadata and property-variable fixtures.

## Checklist

- [x] Include MDN properties regardless of status.
- [x] Generate status metadata for standard, experimental, nonstandard,
and obsolete properties.
- [x] Show warning icons in Add styles results and active declarations.
- [x] Add status-specific consequences and MDN links.
- [x] Preserve generated vendor-prefixed properties during CSS import.
- [x] Generate WebKit text fill/stroke longhands without parser
exceptions.
- [x] Support `anchor()`, `anchor-size()`, and `anchor-center`.
- [x] Support current `position-anchor` keywords.
- [x] Expand syntax-compatible shorthands through generic MDN metadata
and CSS-tree captures.
- [x] Cover ordered optional, unordered, slash-separated,
function-valued, omitted, CSS-wide, variable, invalid, and
incompatible-data cases.
- [x] Verify new status, warning, prefix, and shorthand tests fail
without their implementations and pass when restored.
- [x] Update to CSS-tree 3.2.1.
- [x] Regenerate CSS metadata and property-variable fixtures.
- [x] Review documentation impact; no authoritative Builder
documentation lists individual supported CSS properties, so no update is
needed.
- [x] Review fixture impact; 668 fixtures and 2,030 valid cases were
regenerated with zero unsupported.

## Verification

- `pnpm --filter @webstudio-is/css-data test` — 4,618 passed, 1 skipped.
- Builder CSS editor and property-status tests — 25 passed.
- CSS data, CSS engine, Project Build, and Builder typechecks passed.
- Lint, formatting, repeated regeneration, and diff checks passed.

## Known limitation

This change covers CSS declarations and values. It does not add a
dedicated Builder editor for the `@position-try` at-rule.

Closes #6162
2026-08-17 14:54:11 +02:00
Oleg Isonen a836f29a69 fix: Explain asset count limits (#6149)
## Summary

Return a specific, safe error when a project reaches its plan's
asset-count limit instead of reporting an internal Assets API failure.

## Root cause

The uploader enforced `maxAssetsPerProject` by throwing a plain `Error`.
The REST boundary correctly treated unknown errors as internal failures,
returned HTTP 500, and redacted the useful limit explanation. The
Builder then displayed that generic response.

## Technical choices

- Represent the expected quota condition with
`AssetUploadCountLimitError`.
- Map that domain error to HTTP 409 while preserving its existing
message.
- Keep the generic HTTP 500 response and server logging for unexpected
failures.
- Reuse the Builder's existing API-error handling; it already displays
the returned `errors` value in the upload toast.

## Checklist

- [x] Reproduce the generic uploader and REST error behavior
- [x] Add regressions and verify they fail before the behavior change
- [x] Throw a typed error when the asset-count limit is reached
- [x] Return the safe limit explanation through the Assets API
- [x] Verify unexpected internal errors remain redacted
- [x] Review documentation impact — no documentation change is needed
for this error-message correction
- [x] Review fixture impact — no fixture inputs or generated outputs are
affected
- [x] Review the final diff for unrelated changes and duplicated logic

## Verification

- `pnpm --filter @webstudio-is/asset-uploader test` — 196 tests passed
- Asset uploader typecheck passed
- Targeted Builder Assets API and upload client tests — 37 tests passed
- Builder typecheck passed
- `pnpm lint`

Closes #6148
2026-08-14 23:32:07 +02:00
Oleg Isonen cb51d477e1 fix: Refresh resource diagnostics metadata (#6113)
## Summary

Follow up on #6095 so explicit Diagnostics refreshes update both
diagnostic and performance metadata, stale refreshes are cancelled
during invalidation, and Assets batch measurements are labeled
consistently in the Builder.

Ref #6092

## Technical choices

- Cache response diagnostics and performance metadata through one shared
path.
- Attach an AbortController to each explicit diagnostics request and
reject stale results after invalidation.
- Accept additive performance fields from newer servers.
- Clarify that Assets timings and counters cover the combined batch.
- Reuse the measured view-authorization path across repository entry
points.

## Implementation checklist

- [x] Refresh performance metadata with explicit diagnostics.
- [x] Cancel and ignore stale diagnostics requests.
- [x] Keep performance parsing forward-compatible with additive fields.
- [x] Clarify Assets batch labels and descriptions.
- [x] Add regression coverage for refresh, invalidation, and parsing
behavior.
- [x] Review documentation impact — authoritative `docs/` does not cover
this internal Diagnostics tooling, so no update is required.
- [ ] Run affected Builder and asset-uploader typechecks.
- [ ] Confirm GitHub checks pass.

## Verification

- Builder diagnostics/resource tests: 27 passed.
- Asset repository tests: 39 passed.
- `git diff --check origin/main...HEAD` — passed.
2026-08-12 11:46:58 +02:00
Oleg Isonen db2d092268 ci: replace Lost Pixel with self-hosted visual regression (#6086)
## Summary

Replace the defunct Lost Pixel service and the interim Chromatic
workflow with a fast, self-hosted visual comparison pipeline.

The workflow indexes the existing CSF stories without building
Storybook, builds and serves a lightweight browser app with Vite,
renders the merge base and current revision through Webstudio's shared
browser tooling, and compares screenshots with Webstudio's pixel-diff
and OCR engine. It uses GitHub Actions cache and artifacts only—no R2
bucket or external visual-testing service.

Closes #6064

## Implementation

- [x] Remove the Lost Pixel workflow, configuration, acknowledgement,
and global two-second wait.
- [x] Remove the interim Chromatic workflow and settings.
- [x] Extract source-agnostic capture, diff, OCR, audit, cache, and
report tooling into `@webstudio-is/vision`; rename the
Webstudio-specific preview boundary to
`@webstudio-is/project-build/preview`.
- [x] Expose the reusable browser capture session through the shared
vision boundary.
- [x] Make OCR and diff-artifact generation conditional on detected
pixel changes.
- [x] Render existing CSF stories through a typed, lightweight browser
harness built with Vite.
- [x] Replace the embedded HTML and handwritten HTTP/MIME server with a
real HTML entry, Vite production build, and Vite preview server; isolate
declarative build configuration in `story-build.ts`.
- [x] Apply Storybook preview annotations, decorators, global CSS,
backgrounds, and story metadata.
- [x] Store story scopes as shared data and load each revision's own
configuration.
- [x] Discover changed, added, and removed stories from both revisions.
- [x] Populate private story sources symmetrically in the baseline
worktree.
- [x] Isolate every story with a fresh React root and deterministic
time, randomness, intervals, focus, animation, and layout readiness.
- [x] Preserve story-owned visual options for masking, settling, and
interval control.
- [x] Reuse Vite preview servers, one Chromium process, grouped browser
pages, production bundles, and a bounded CPU worker pool for image
comparison.
- [x] Recheck initial pixel differences with serial captures, then
recapture persistent baseline/current pairs on the same browser page so
renderer variance cannot create false failures.
- [x] Report individual story render failures without discarding
successful captures.
- [x] Enforce a 0.1 per-pixel threshold and 0.001% total mismatch
tolerance.
- [x] Run OCR only for changed comparisons and include text-change
evidence.
- [x] Move the generic report model, writer, static viewer, and opener
into the shared Vision package for reuse by CI and future CLI
comparisons.
- [x] Bundle report HTML, styling, and browser behavior as static Vision
assets without runtime source-file lookups.
- [x] Copy external screenshot inputs into self-contained report
artifacts for CLI reuse.
- [x] Handle cached removed-only comparisons without rendering the
removed story on the current server.
- [x] Support focused local reproduction and opening the report with one
command.
- [x] Pin CI to the lockfile's Playwright Chromium, cache complete
revision screenshots with matching restore/save paths and automatically
derived runtime invalidation, and render both revisions on a miss.
- [x] Keep cache archives bounded to one revision instead of
accumulating the cache history.
- [x] Run the complete visual suite in one CI job and upload one report
as a 14-day artifact.
- [x] Fail PR checks on visual differences, empty runs, missing
screenshots, missing or empty report artifacts, and infrastructure
failures.
- [x] Rerun fork checks when `safe-to-deploy` is added.
- [x] Allow reviewed visual-only differences through
`visual-change-approved` and invalidate approval after new commits.
- [x] Keep capture, pixel diff, OCR, and report generation
source-agnostic for future draft-versus-published project comparisons.
- [x] Use Vite for the complete story HTML, module, asset,
production-build, and preview-server lifecycle; inline the selected
stories and skip ineffective tree-shaking to keep the cached run under
one minute.
- [x] Review Builder product documentation impact: no user-facing
Builder documentation is affected; contributor usage is documented in
`scripts/visual-regression/README.md`.
- [x] Review fixture impact: no fixture inputs or generated fixture
outputs are affected.

## Verification

- [x] Project-build Vision tests, including the reusable report test,
and entrypoint contract tests pass.
- [x] CLI screenshot, preview, and browser-session tests pass.
- [x] Project-build, CLI, Builder, design-system, and visual-runner
typechecks pass.
- [x] Visual runner tests pass (10), and the complete Vision package
passes (79), including demonstrated fail-before/pass-after coverage.
- [x] Full Storybook production build passes.
- [x] Full local Vite run completes all 238 stories in 69.9s cold and
50.3s with a cached baseline plus two same-page serial verifications,
with zero differences; identical-image comparison remains sub-second.
- [x] The report writer passes a bundled-output smoke test and
materializes external screenshot assets.
- [x] The generated report validates all 238 entries and referenced
images.
- [x] Hosted cached-baseline comparison completes all 238 stories in
52.9s with zero differences; the cache-miss fallback completes in
101.3s.
- [x] Cache-miss fallback renders both Git revisions on demand.
- [x] Visual differences produce baseline, current, diff, OCR, JSON, and
HTML evidence and fail without approval.
- [x] Hosted single-job visual workflow restores both the pinned browser
and baseline cache, validates all 238 public and private stories with
zero differences, and uploads the report.
- [x] The final Vite production build renders all 238 stories without
dependency invalidation or duplicate React runtimes, and restores
`NODE_ENV` so cached serial fallback installs the baseline's dev
dependencies.
- [x] Root lint, package-boundary validation, and relevant formatting
checks pass.
- [x] Workflow YAML parses successfully.
- [x] `git diff --check`, staged-diff review, and final worktree review
pass.

## Usage

Run the complete local comparison and open the visual report:

```sh
pnpm visual-regression:ui
```

Focus one component while iterating:

```sh
pnpm visual-regression:ui -- --grep "Design system/Button"
```

Reopen the latest report without rerunning:

```sh
pnpm visual-regression:report
```

The CI report is available as the `visual-regression-report` artifact.

## Tradeoffs

- Baseline screenshots are a disposable acceleration cache, not source
of truth. A missing or invalid cache renders the merge base directly
from Git.
- GitHub artifact storage provides downloadable one-click reports;
permanently hosted browser links would require another hosting surface.
- OCR runs after pixel triage because invoking Tesseract for every
unchanged story would make the common path unnecessarily slow.
- Vite production builds add Rollup's module graph and HTML/asset
pipeline. The runner emits one bundle because every selected story is
rendered, and skips tree-shaking because it removed little while
increasing build time.
- The verified local path is 50.3s cached and 69.9s cold. The hosted
path is 52.9s cached and 101.3s cold. A new browser/runtime cache must
render its baseline once; the pinned browser keeps later runners on the
reusable path.
- The complete suite stays in one Actions job; browser-page concurrency
is internal and bounded.
2026-08-12 10:55:52 +02:00
Oleg Isonen 11d76eb43d perf: Diagnose and reduce Assets resource latency (#6095)
## Summary

Adds Builder-only resource performance metrics to grouped Diagnostics
tables, removes duplicate object-store reads from the Assets query path,
scopes compiled-artifact reuse to one repository request, and compiles
unpinned Builder previews from their concrete query values instead of
hydrating the complete saved dynamic deployment plan. Nothing is
precomputed or retained in a warm serverless process after the request
finishes.

Ref #6092

## Technical choices

- Keep `__performance__` as internal response metadata and strip it
before resource values enter expression-visible caches.
- Record Builder round-trip, server duration, response size, Assets
phases, document work, completed storage reads, and cumulative
compiler/document-graph storage-read durations.
- Present Diagnostics as collapsible sections ordered Database and
sizes, Timing, Query work, then detailed database/result inspectors.
Open only the first available section by default. Every metric keeps an
explanatory tooltip, with info icons revealed only when the label cell
is hovered or keyboard-focused.
- Add a copy action to every section header. It copies that section's
raw structured data as formatted JSON without opening a collapsed
section.
- Keep Index preparation as an inclusive parent duration and explain
that relationship in Diagnostics.
- Compile ordinary unpinned Builder preview requests from a union of
their concrete query values. A detail route therefore hydrates only
documents that can satisfy that request.
- Continue using the saved artifact-producing plan for revision-pinned
requests.
- Keep publication and prepublication preparation unchanged.
- Load only `props`, `dataSources`, and `resources` when constructing
the single-query Builder preview plan, matching the already-narrow batch
path instead of downloading and parsing the complete dev Build row.
- Build the deployment-wide saved plan only when detailed Diagnostics
requests its Published database statistics. Report that work as the
separate inclusive `Published diagnostics` timing and exclude its child
phases and fetch counters from the normal query measurements.
- Reuse successfully read content bytes across compiler preparation,
document graph construction, and runtime resolution within one query or
batch. Graph-fetched bytes are size-validated before entering the
revision-keyed request map, and graph additions stop when the request
cache reaches the 2 MiB hydrated-content limit.
- Before repairing canonical metadata, load candidate metadata once and
prove its revision, base document, and prepared metadata tier match the
open source snapshot. Skip synchronization when it is already current;
retain recovery and repair for stale, missing, insufficient-tier, or
inconsistent rows.
- Key request-local bytes by content reference and revision so
source-change retries cannot reuse stale data.
- Instantiate compiled-artifact reuse per `PostgresAssetRepository`;
repeated preparations inside one request can reuse or coalesce work, but
later requests and other serverless instances cannot.
- Remove the module-level 32-entry compiled-artifact cache introduced in
#5946.
- Introduce no precomputed, persisted, process-local, or cross-request
content cache.

## Findings and measurements

The supplied production post resource was bimodal before removing the
process cache:

- Warm process: approximately 1.0–1.5 seconds.
- Cold process: approximately 5.7–6.7 seconds.
- Ordinary response: approximately 4.6 kB.

The earlier development capture was a process-cache hit: 542.6 ms server
time and 932.5 ms Builder round trip. A later hit measured 491.5 ms
server time and 739.1 ms round trip. Those results demonstrated the old
module cache's nondeterministic serverless behavior rather than
cold-path performance.

After request-scoped reuse replaced the process cache, the supplied cold
capture measured 3,848.5 ms server time. Index preparation was 3,259.7
ms. The saved dynamic plan caused 25 compiler content fetches and 301 kB
of compiler input even though the concrete post query resolved only two
documents. The published database contained 28 documents and used 45.4
kB bounded / 512 kB unbounded.

Tracing compilation also exposed duplicate request-time I/O: selected
Markdown was fetched for compiler input, document graph construction,
and runtime document resolution. Request-local byte reuse changes that
representative path from three object-store reads to one.

The remaining dominant issue was therefore query breadth, not response
serialization or runtime result resolution. The Builder was compiling
the deployment-wide dynamic plan to answer a concrete post request. The
new preview path compiles the concrete values; regression coverage
demonstrates that a saved two-post dynamic plan reads only `post-a` when
previewing `post-a`.

The next cold capture confirmed that change: Builder round trip fell
from 4,391.4 ms to 2,245.2 ms, server duration from 3,848.5 ms to
1,601.8 ms, and index preparation from 3,259.7 ms to 1,044.9 ms.
Compiler content fetches fell from 25 to 1 and document-graph content
fetches from 3 to 1. Canonical metadata remained 239.2 ms because an
unchanged request still performed a repair synchronization round and
then loaded the same stored metadata again. The new fast path reduces
that normal case to one recovery-safe candidate metadata read.

A subsequent capture confirmed the canonical metadata fast path: server
duration fell from 1,601.8 ms to 1,401.0 ms, index preparation from
1,044.9 ms to 684.8 ms, and canonical metadata from 239.2 ms to 74.7 ms.
The post query remained narrow at one compiler fetch and one
document-graph fetch. Builder round trip rose from 2,245.2 ms to 2,411.1
ms while the server improved, so that difference is outside the measured
server work and is consistent with
browser/network/development-environment variance.

At that point `buildPlan` was the largest remaining isolated phase at
242.8 ms. Single-query preview was still loading every dev Build column
and parsing pages, styles, instances, deployment data, and other fields
that are not inputs to the Assets compilation plan. The narrow loader
now requests and parses only the three content-engine fields used by
plan construction.

The next capture confirmed that optimization: build plan fell from 242.8
ms to 99.0 ms, server duration from 1,401.0 ms to 1,056.8 ms, and the
concrete post query remained at one compiler fetch and one
document-graph fetch. Index preparation stayed effectively flat at 679.7
ms, making compiler entries (142.3 ms), source snapshot (119.2 ms),
source validation (119.1 ms), and document graph (114.0 ms) the next
candidates. The new child timings separate cumulative storage waiting
from the remaining compiler/document-graph work before choosing another
behavioral optimization.

The storage timing capture then showed that I/O dominated the remaining
compiler and graph phases: compiler storage was 114.6 ms of 125.9 ms,
while document-graph storage was 114.0 ms of 147.6 ms. The graph path
consulted compiler-cached bytes but did not retain newly fetched graph
documents, so runtime reference resolution fetched the same two-document
chain again. Retaining validated graph bytes in the same request reduces
the regression fixture from four physical object-store reads to two
without changing its resolved result.

Final three-run measurements after same-request graph-byte reuse were
stable: median Builder round trip was 926.2 ms, median server duration
was 681.9 ms, median index preparation was 407.9 ms, and median document
resolution was 3.7 ms. Compared with the uncached 3,848.5 ms server /
3,259.7 ms index baseline, that is approximately 82% less server time
and 87% less index-preparation time for this post query.

A final DRY/correctness review centralized request-local byte-cache
keying and its 2 MiB accounting, removed repeated Diagnostics size rows
and SDK metadata assembly, typed phase keys, and corrected response-size
measurement so internal performance metadata is excluded as the UI
promises.

The module cache was also only bounded for completed entries. Many
simultaneous unique-project compilations in one process could exceed 32
pending entries until they settled. Scoping reuse to one repository
request removes cross-user retention and tenant cache competition while
preserving duplicate-work elimination inside the request.

## Todo

- [x] Add generic resource timing and response-size metrics.
- [x] Add Assets phase, document graph, source validation, storage-read
count/byte metrics, and compiler/document-graph storage-read durations.
- [x] Render ordered collapsible Diagnostics sections with only the
first open by default, per-metric explanations, interaction-only info
icons, and per-section JSON copy actions.
- [x] Reuse compiler and document-graph content bytes through runtime
resolution within the current request, without precomputation.
- [x] Remove cross-request process caching and retain request-scoped
compilation reuse.
- [x] Compile unpinned previews from concrete query values.
- [x] Separate deployment-wide diagnostic preparation from normal query
phase counters.
- [x] Skip redundant canonical metadata synchronization when stored
candidates already match the source snapshot and requested tier.
- [x] Narrow single-query Build reads to the three fields required by
Assets plan construction.
- [x] Expose cumulative compiler and document-graph storage-read timing
as explained child rows.
- [x] Add regression coverage, including red/green verification.
- [x] Review the final diff for correctness, duplication, and
unnecessary complexity.
- [x] Verify concrete-query compilation against the supplied post
resource: compiler fetches fell from 25 to 1.
- [x] Remeasure the canonical metadata fast path: canonical metadata
fell from 239.2 ms to 74.7 ms and index preparation from 1,044.9 ms to
684.8 ms.
- [x] Review documentation impact: no authoritative `docs/` page covers
this internal Diagnostics tooling, so no documentation update is
required.
- [x] Run focused tests, affected package typechecks, lint, formatting,
and the fixture pipeline.

## Verification

- Content engine tests: 23 passed.
- Asset uploader tests: 195 passed, including repository, canonical
synchronization, request-cache, and storage-timing coverage.
- Builder focused Diagnostics tests: 10 passed in the latest
storage-timing pass; 15 passed in the preceding final pass and 35 across
the earlier instrumentation scope. The collapsible view test verifies
section order, default state, and deferred content interaction.
- Project tests: 84 passed, including 5 focused preview tests. The
focused regression failed against the full-Build loader and passed after
switching the single-query path to the narrow content-engine loader.
- SDK resource loader tests: 24 passed.
- Current canonical metadata regressions failed under the old
always-synchronize expectations and pass with one metadata load and no
synchronization; stale metadata still exercises and passes the repair
fallback.
- The Timing clipboard test failed with an empty payload and passed with
the complete raw duration/phase JSON; copying a collapsed section is
also verified not to open it.
- The collapsible default-state test failed when Timing was temporarily
opened alongside Database and sizes, then passed after restoring the
first-section-only behavior.
- The concrete-preview regression failed before the optimization by
reading both `post-a` and `post-b`, then passed by reading only
`post-a`.
- A repository-reuse regression failed without the request cache and
passed when reuse became the repository default.
- The content-read regression failed before the original compiler reuse
optimization with three storage calls and passed afterward with one.
- The two-document graph regression failed with four physical storage
calls and passed with two after graph reads populated the request-local
runtime cache.
- The response-size regression failed at 127 bytes when internal
performance metadata was included and passed at the actual 66-byte
payload after separating that metadata.
- Builder, content engine, asset uploader, project, and SDK typechecks
passed.
- Oxfmt, oxlint, and `git diff --check` passed.
- The full fixture link/sync/build pipeline passed with no tracked
fixture changes after each runtime change.

## Known limitations

- Detailed Diagnostics intentionally prepares both the concrete query
database and the deployment-wide Published database. `Published
diagnostics` reports the latter separately; normal resource loads do not
perform it.
- Builder round-trip and server duration cover the complete resource
batch and therefore include Published diagnostics when the detailed view
requests it.
- Phase durations are aggregated when a batch contains multiple Assets
queries.
- Compiler and document-graph storage-read timings sum completed fetch
durations. They exclude request-local byte-cache hits and can exceed
wall-clock parent phases when reads run concurrently.
- Content-read counters report completed normal-query reads;
deployment-wide diagnostic reads are excluded, and failed storage reads
are represented by the enclosing phase timing and error.
- Request-local byte reuse retains selected content only until the
current query or batch finishes. Document-graph additions are capped by
the existing 2 MiB hydrated-content limit; content beyond the cap is
still streamed and can be fetched again at runtime.
- Source snapshot and final source validation remain separate reads. The
metadata fast path removes redundant repair work without weakening that
concurrent-change check.

## Measurement gate

PR deployments use the development backend. The supplied production
project returns 500 on both the branch deployment and
`main.development.webstudio.is`, while the production host returns 200.
Final phase timings for the exact project require its corresponding
development project/session or an explicitly authorized
production-backed deployment. An unrelated fixture will not be used to
claim the production improvement.
2026-08-11 12:31:23 +02:00
Oleg Isonen db3b11970f fix: Optimize images in Markdown Embed (#6089)
## Summary

Markdown Embed now renders image tags with the same optimized attributes
and canvas behavior as the SDK Image component.

The implementation shares the complete attribute-resolution path without
rendering React inside the Markdown pipeline:

- `@webstudio-is/image` exposes one framework-independent
`getImageAttributes` function for optimization, placeholder fallback,
loading, decoding, dimensions, alternative text, and responsive sources.
- React-only element props such as `className`, `style`, handlers,
context, and refs stay in React callers.
- The SDK Image component and Markdown renderer both use
`getSdkImageProps` for canvas-specific loading, decoding, asset
identity, and incomplete-upload handling.
- Markdown retains only the necessary HTML attribute-name conversion,
sanitization, and Safari-safe `sizes` / `srcset` / `src` ordering.
- The redundant low-level React Image primitive was removed. Its callers
now render native `img` elements, and the image package no longer has
React runtime or peer dependencies.

## Compatibility and tradeoffs

- The SDK Image component remains the public React component because it
owns React context and ref forwarding.
- The removed low-level `@webstudio-is/image` Image export is replaced
by the pure attribute function for internal callers.
- No data migration or schema change is required.
- Loader output is sanitized after transformation, while unsafe input
URLs are sanitized before reaching the loader.

## Todo

- [x] Share image attribute resolution between native, SDK, and Markdown
images.
- [x] Preserve SDK canvas behavior for Markdown images.
- [x] Preserve safe URL sanitization and Safari-safe responsive
attribute ordering.
- [x] Remove the redundant low-level React image primitive and migrate
its callers.
- [x] Remove the overlapping `getImageProps` abstraction.
- [x] Add regression coverage comparing Markdown, SDK Image, and native
attribute output.
- [x] Review documentation impact and update the Markdown Embed
documentation.
- [x] Run targeted tests, typechecks, builds, lint, formatting,
package-boundary checks, and fixture generation.

## Verification

- `pnpm --filter @webstudio-is/image test`
- `pnpm --filter @webstudio-is/image typecheck`
- `pnpm --filter @webstudio-is/image build`
- `pnpm --filter @webstudio-is/image dts`
- `pnpm --filter @webstudio-is/sdk-components-react test`
- `pnpm --filter @webstudio-is/sdk-components-react typecheck`
- `pnpm --filter @webstudio-is/sdk-components-react build`
- `pnpm --filter @webstudio-is/sdk-components-react dts`
- `pnpm --filter @webstudio-is/builder typecheck`
- `pnpm --filter @webstudio-is/design-system typecheck`
- Targeted Oxlint and Oxfmt checks
- `pnpm check:package-boundaries`
- `pnpm fixtures` (no fixture diff)

Ref #6014
2026-08-10 18:21:45 +02:00
Oleg Isonen 41c8283a70 fix: Allow removal of invalid audited selectors (#6074)
## Summary

Allow all targeted style-deletion paths to remove an invalid state
selector that already exists, including Builder UI deletion of local and
token declarations and CLI/MCP design-token remediation. Creation and
update validation remain strict.

## Root cause

The style audit reads legacy declarations directly and can report
selectors that the current selector validator rejects. Deletion reused
the creation/update validator, so the system could identify an invalid
stored declaration but could not represent its coordinates for targeted
removal. The first fix addressed only design-token deletion, leaving
Builder UI and the generic style APIs inconsistent.

## Implementation

- [x] Give style deletions a shared deletion-only state-selector
contract.
- [x] Accept an invalid selector only when the exact target, breakpoint,
property, and state already exist.
- [x] Reject arbitrary invalid selectors that do not identify an
existing declaration.
- [x] Reuse one matcher for local, selected/token, and design-token
deletions.
- [x] Keep creation and update selector validation strict.
- [x] Add Builder UI regression coverage for token and local declaration
deletion.
- [x] Add an audit regression that deletes the reported design-token
selector, applies the patch, and confirms the warning is cleared.
- [x] Regenerate the public runtime operation contract.
- [x] Complete the DRY review: deletion matching, validation, key
deduplication, and stored-style scanning are centralized.
- [x] Review documentation impact: no authored documentation changes are
required; generated operation contracts describe the behavior.
- [x] Review fixture impact: no fixture inputs or generated fixture
bundles are affected.
- [x] Run relevant tests, typechecks, lint, formatting,
package-boundary, generated-API, and generated-documentation checks.
- [ ] Agent evaluations — not run because repository policy requires
separate explicit approval.

## Verification

- The two Builder UI regression tests failed with `Operation input is
invalid` before the shared fix and passed afterward.
- Project-build suite: 82 files, 2,097 tests passed.
- CLI suite: 60 files, 968 tests passed.
- Builder style-data target: 7 tests passed.
- Audit and styles targets: 195 tests passed.
- Project-build, Builder, and CLI typechecks passed.
- Full repository lint passed.
- Package-boundary, generated-API, and generated-documentation checks
passed.
- Formatting and `git diff --check` passed.

Closes #6062
2026-08-09 01:46:42 +02:00
Oleg Isonen d5b3f3ab80 fix: Improve MCP authoring reliability (#6056)
## Summary

This consolidates the reported MCP reliability fixes into one delivery.

- validate all inserted fragment expressions with the shared runtime
rules and reject text/expression children when component content models
require elements
- return an actionable error for unsupported existing-resource
references in JSX
- preserve siblings rendered before expression children
- accept unresolved CSS-variable shorthand expansion and eliminate
dynamic-alt/`htmlFor` audit false positives
- resolve exposed underscore MCP names during focused discovery
- omit unavailable stopped-preview fields and restart stale iterative
previews for external clients
- bound single and responsive screenshot capture, return
`SCREENSHOT_TIMEOUT`, and discard failed reusable browser sessions
- dispose previews when shared MCP runs fail or stdio clients
disconnect, including complete Windows process-tree cleanup
- resolve generated route templates from the CLI-managed preview
workspace during responsive verification
- retry a browser that exits during rendered-audit startup and report
sanitized exit diagnostics with a concrete browser-path recovery action
- materialize complete current session data before preview generation so
route order and project styles cannot collapse from missing lazy
namespaces
- always include CLI and Node.js version fields in generated issue
reports, with explicit legacy-client fallbacks
- document the updated preview and screenshot contracts and regenerate
the CLI manual

The current branch also retains the protections already present on
`main` for dry-run isolation, CSS rewrite truncation metadata,
stderr-only progress, shortcut argument forwarding, strict MCP schemas,
and refreshed conflict diagnostics.

## Technical choices

- MCP command orchestration stays in `mcp.ts`; preview port/retry
behavior lives with `mcp-preview`, and persisted checkpoint storage
lives in `mcp-checkpoint`. Each module owns its matching tests.
- Expression validation lives on the shared fragment input schema,
reuses `listFragmentExpressions`, and emits the same structured
validation issues as prop bindings, so JSX-derived and structured
fragments follow one contract across fragment, collection, and runtime
UI insertion.
- Element-child requirements come from component registry content models
during fragment insertion; no component names are hardcoded in the JSX
parser. `CollapsibleTrigger` metadata now matches its enforced `asChild`
implementation.
- Stopped preview status returns only `running: false`; unavailable
`url`, `pid`, and `mode` fields are optional and omitted from JSON.
- Explicit `preview.start` restarts a stale compatible iterative
preview; managed screenshots keep their optimized refresh path.
- Screenshot operations share one timeout utility. A single capture or
complete responsive batch is bounded after preview readiness;
lower-level CDP deadlines use the same stable error code.
- Failed managed captures close and forget their browser session. A
closed browser session cannot restart itself while cancellation is in
progress, which prevents orphaned Chromium processes.
- One ownership helper disposes one-shot and multi-project MCP hosts on
success or failure. Shared `mcp run` hosts dispose in one `finally`
boundary, long-running MCP hosts dispose on connection close, and
Windows uses `taskkill /T /F` instead of killing only the npm wrapper.
- Framework template readers receive the absolute template directory
captured from the build root, so later async work cannot redirect them
to the linked project's cwd. The same option drives cleanup for React
Router, Remix, and Vike.
- Browser startup gets one bounded retry before a rendered capture batch
fails. Persistent failures report only the exit code, signal, or spawn
error code plus the supported `WEBSTUDIO_BROWSER_PATH` recovery action;
local paths and raw browser output are not exposed.
- CLI and MCP preview share one session materializer that ensures the
canonical Builder namespace set before writing `.webstudio/data.json`.
Serialization rejects incomplete snapshots instead of converting missing
style/instance namespaces into valid-looking empty arrays, and preview
freshness records the post-materialization project version.
- The CLI injects its package version and `process.versions.node`; issue
formatting now keeps both fields visible even for legacy reports that
omit runtime metadata.

## Checklist

- [x] Add regression coverage for every changed behavior
- [x] Demonstrate new regression tests fail without the corresponding
fixes and pass with them
- [x] Run affected package test suites and typechecks
- [x] Run lint, package-boundary, and generated API checks
- [x] Review fixture impact — no fixture inputs or outputs are affected
- [x] Review documentation impact and update the authoritative MCP CLI
manual source/generated output
- [x] Run the complete local agent evaluation suite

## Verification

- `@webstudio-is/project-build`: 2,090 tests passed
- MCP asset query result modes are preserved across create, read, and
update serialization
- complete local agent evaluation suite: all 5 fixtures passed,
1,308,276 aggregate tokens
- `@webstudio-is/react-sdk`: 140 tests passed
- `@webstudio-is/template`: 43 tests passed
- `webstudio` CLI: 956 tests passed
- issue reporter: 5 targeted tests passed
- MCP host disposal regression was demonstrated failing without the
shared ownership boundary and passing with it
- relevant package typechecks passed
- `pnpm lint` passed
- `pnpm check:package-boundaries` passed
- `pnpm check:generated-api` passed
- generated-doc tests, typecheck, sync, and regeneration passed; the
aggregate clean-tree command reports the intentionally changed generated
CLI manual
- stalled single capture, stalled four-viewport capture, startup retry
across a four-viewport batch, sanitized browser-exit diagnostics,
complete preview materialization, post-refresh version tracking,
closed-session restart, Windows process-tree cleanup, and
preview-workspace regressions were demonstrated failing without their
fixes and passing with them

## Known limitations

- External `baseUrl` screenshots remain caller-owned and intentionally
do not regenerate, restart, or stop that external server.

Closes #6034
Closes #6035
Closes #6038
Closes #6042
Closes #6043
Closes #6044
Closes #6045
Closes #6046
Closes #6047
Closes #6048
Closes #6049
Closes #6050
Closes #6051
Closes #6052
Closes #6059
Closes #6060
2026-08-08 22:22:25 +02:00