Commit graph

692 commits

Author SHA1 Message Date
Fini f072db8559 fix(ai): query mining + enqueue path for heuristic image-area frames
Why: b9b4126b's collectImageSearchTargets returns heuristic-matched
frames (named "Image" / "Photo" / "Cover" without the canonical
role) but two downstream code paths quietly dropped them:

1. enqueueImageForSearch only accepted type==='image' or
   isUnfilledImagePlaceholderFrame, so the heuristic frames got past
   collect but never reached the queue.

2. extractQueryForNode would have returned the literal name "Image" or
   "Photo" — useless to the photo search API. The user's "Bella Italia"
   restaurant card never gets a relevant photo because the placeholder
   frame's name says nothing about the restaurant.

What:
- enqueueImageForSearch grows a third branch: isImageAreaFrameByHeuristic
  → kind: 'placeholder-frame'. Same kind so the rest of the pipeline
  treats it identically to a canonical placeholder.
- extractQueryForNode learns to skip "generic" placeholder names
  (Image / Photo / Cover / Hero / Thumbnail / Banner / Poster + a few
  variants) and walk up to the nearest semantic parent frame name
  ("Bella Italia" / "Margherita Pizza" / "Sushi House" — whatever the
  enclosing card was named). Bounded to 3 hops. Filters layout words
  (Card / Wrapper / Container / Section / Frame / Root / Page / Stack /
  Row / Column / Content) so we don't end up searching for "Card".
- A new helper findParentSemanticName builds a parent map from the
  live document on demand. Cheap for typical designs (< few hundred
  nodes); avoids threading parent through every collect / enqueue call
  site.

Net effect: a model-emitted plain "Image" frame inside a "Bella Italia"
card now searches for "Bella Italia" instead of literally "Image". The
existing isImageAreaFrameByHeuristic test coverage protects the entry
condition; 1098 / 1098 AI service tests still pass.
2026-05-09 21:36:00 +08:00
Fini 6dcb436ca6 fix(ai): heuristic image-area detection for non-canonical frame placeholders
Why: 2026-05-09 user report — the food-app card design landed with
empty colored rectangles where restaurant photos should be (Bella
Italia / Green Bowl / Margherita Pizza). Root cause: the model emitted
plain frames named "Image" / "Photo" / "Cover" with a solid fill as
the card-top image area, instead of using add_image_placeholder_v1
(which sets role: 'image-placeholder'). The auto-search pipeline
strict-checks role and missed all of them, so scanAndFillImages found
nothing to search and the cards stayed solid-colored.

What: new isImageAreaFrameByHeuristic(node) supplements the strict
role check. Conservative match — only fires when ALL of:
  - frame node WITHOUT role='image-placeholder' (strict path handles
    that)
  - name matches /\\b(image|photo|cover|hero|thumbnail|thumb|picture|
    banner|poster)\\b/i
  - width >= 80 AND height >= 60 (filters tiny color swatches)
  - exactly one solid (non-image) fill (gradient = decorative, image
    = already filled, both skip)
  - 0 or 1 children (an icon child is OK, multi-child = real layout)

collectImageSearchTargets walks both the strict and heuristic paths
and produces the same kind: 'placeholder-frame' target either way, so
the existing query / aspect / search code-path runs unchanged.

10 new tests cover positive matches (Image / Photo / Cover / Hero /
Thumbnail / Banner / Poster), negative for canonical placeholder
(double-counting prevented), unrelated names (Card / Wrapper),
already-filled image fills, gradients, content-rich frames, single-
icon-child acceptance, undersize frames, and non-numeric dimensions.
26 / 26 tests in image-search-pipeline.test.ts pass (was 16; +10).
1098 / 1098 AI service tests pass (unchanged).
2026-05-09 21:35:00 +08:00
Fini 4044a53ec9 fix(ai): sidebar-nav-v1 also canonicalises wrong-glyph icons via label
Why: f1923ff1 added coerceNavTabIcon to bottom-nav-v1 and noted that
sidebar-nav-v1 should adopt the same helper. Without it, a sidebar
nav with \`{ label: 'Profile', icon: 'profile' }\` would still render
a placeholder circle (resolver doesn't know "profile" is a known
wrong-glyph alias for "user") instead of the lucide:user glyph.

What: import coerceNavTabIcon and apply it in buildItemV1 before
stamping iconFontName onto the Icon child node. Same convention
single-sourced. Existing 1435 tests still pass — no test relied on
the prior pass-through behavior for known wrong-glyph names.
2026-05-09 21:34:00 +08:00
Fini 68bbfeed88 fix(ai): bottom-nav-v1 canonicalises wrong-glyph icons via title (Cart→shopping-cart)
Why: end-to-end test of "Design a bottom nav with Home / Search /
Orders / Cart / Profile" with MiniMax-M2.7 surfaced that the model
emits \`{ title: 'Cart', icon: 'shopping-bag' }\` for the Cart tab
~half the time. Both icons exist in lucide but they are different
glyphs — bag is for carrying, cart has wheels for checkout. The
icon-catalog skill update (19ca1c66) fixed it for the planning side
but not for the builder's runtime input — direct \`add_bottom_nav_v1\`
calls still pass through whatever icon the model picks.

What: new \`coerceNavTabIcon(title, icon, builder)\` helper in
coerce-params.ts. Maintains a small Title→canonical-lucide-name map
(Cart→shopping-cart, Profile→user, Home→house, etc., with Chinese
labels) AND a per-canonical KNOWN_WRONG_ALTS list so the swap only
fires when the emitted icon is one of the known wrong-glyph choices
for that title:

  Cart + shopping-bag         → shopping-cart  (warn)
  Cart + package              → shopping-cart  (warn)
  Cart + rocket               → rocket         (pass-through)
  Cart + shopping-cart        → shopping-cart  (silent)
  Custom + anything           → anything       (silent)

The pass-through rule keeps user / model intentional custom choices
intact. Warnings flow through the existing coerce-params sink so
orchestrators can surface them.

bottom-nav-v1.ts now calls coerceNavTabIcon before stamping
iconFontName onto the Tab frame. Sidebar-nav-v1 + similar nav
builders can adopt the same helper later without re-implementing the
map.

10 new unit + integration tests cover: positive swaps for cart /
profile / notifications / Chinese 购物车, pass-through for
custom titles, case-insensitivity, and the builder integration
that the emitted Tab tree carries the canonical iconFontName.
1098 / 1098 tests pass overall (1080 AI + 10 new + 8 elsewhere).
2026-05-09 21:33:00 +08:00
Fini 207cc1cd52 test(ai): integration coverage for text-effect + mixed-sibling-padding
Why: 3abdfcf9 added integration tests for 4 of the 6 new aesthetic
detectors (rotation / text-cornerRadius / text-stroke / mixed-sibling-
cornerRadius). text-effect (7aef1b14) and mixed-sibling-padding
(ad025c95) landed without integration coverage of the
detect → applyFixes → store mutation chain.

What: 2 more it() cases mirroring the existing pattern:
- text-effect: text node with shadow effects → effects cleared
- mixed-sibling-padding: 3 cards with padding 16/16/20 → outlier
  rewritten to scalar 16 (collapsed from the 4-tuple modal because
  all sides are equal — locks in the scalar-collapse code path)

13 / 13 tests in design-pre-validation.test.ts pass (was 11; +2).
1088 / 1088 AI tests overall (was 1086; +2).
2026-05-09 21:32:00 +08:00
Fini 3bd52767f2 feat(ai): per-subtask icon_font reminder in sub-agent prompt
Why: even after the icon-catalog skill rewrite (19ca1c66) said "ALWAYS
USE icon_font, NEVER path NODES", end-to-end testing with MiniMax-M2.7
shows the model still emits ~half its icons as \`path\` nodes (Bell
Icon / Cart Icon etc.) because the per-subtask CRITICAL LAYOUT
CONSTRAINTS prompt — which the model treats as the prompt of record
— never restated the icon convention. The skill prompt is upstream
context the model can drift away from; the per-subtask block is the
last thing the model reads before generating, so it carries weight.

What: append a one-line ICONS rule directly to CRITICAL LAYOUT
CONSTRAINTS in orchestrator-sub-agent.ts. Restates the icon_font shape
inline (\`{"type":"icon_font","iconFontName":"<lucide-name>",…}\`) and
calls out the failure mode by name (resolver guess + placeholder
circle) so the model sees both the right pattern and the consequence
of the wrong one.

The path-with-iconic-name fallback path keeps working — this is purely
preventive guidance, the resolver tokenize fix (ef6f7ed3) still
catches the leftover cases. 1086 / 1086 AI tests still pass.
2026-05-09 21:31:00 +08:00
Fini 1ff724bebb test(ai): integration tests for aesthetic detector → applyFixes pipeline
Why: the 4 new aesthetic detectors (rotation / text-cornerRadius /
text-stroke / mixed-sibling-cornerRadius) have unit tests against the
pure detect functions in pen-ai-skills, but the chain through the live
Zustand store + runPreValidationFixes had no end-to-end coverage.
Without it, a future refactor that subtly breaks the apply step (e.g.
suggestedValue:undefined not clearing the prop) would slip through.

What: 4 new integration tests in design-pre-validation.test.ts using
the existing makeDoc / loadDocument fixtures. Each builds a doc with
exactly one known aesthetic issue, runs runPreValidationFixes, and
asserts the store mutation took effect:

- rotation:12 on a frame → reset to 0
- cornerRadius:8 on a text node → cleared (undefined)
- stroke on a text node → cleared (undefined)
- mixed cornerRadius across 3 sibling cards (8 / 8 / 12) → outlier
  rewritten to modal 8 (note: handled by the older
  sibling-inconsistency detector; mixed-sibling-corner-radius is
  the dedupe-loser here since sibling-inconsistency runs first
  with the same {nodeId, property} key — both produce the right fix)

11 / 11 tests in design-pre-validation.test.ts pass (was 7; +4).
1086 / 1086 AI tests overall (was 1082; +4).
2026-05-09 21:30:00 +08:00
Fini 58b7b68ede test(ai): regression-cover photo / camera icon names after image-noise removal
Why: C9 (b1ffa1c5) removed `image` from the resolver noise list to make
"Image Icon" resolve to lucide:image. The doc comment claimed "Image
Placeholder Path" still resolves via prefix fallback, but the math is
wrong — `image` is 5 chars, `imageplaceholder` is 16 chars, 5/16 = 31%
which is below the 50% FALLBACK_MIN_RATIO. So "Image Placeholder Path"
genuinely no longer hits the resolver fallback path. That's actually
correct (no icon marker word, resolver returns early), and the original
food-app circles came from the model emitting circle path-data
directly, not from the resolver fallback. But the photo / camera
aliases were also implicit dependencies that deserve explicit coverage
to lock in the behavior.

What: 2 new tests verify photo / camera resolve correctly through the
already-existing alias chain (`photo: _IMAGE` in BUILTIN_ICONS, lucide
camera native). 1082 / 1082 AI tests pass (was 1080; +2).
2026-05-09 21:29:00 +08:00
Fini 5a94c22c8e feat(ai-skills): aesthetic-hygiene rules in layout.md (preventive, not just curative)
Why: the 6 aesthetic detectors added in 53435bf7 / 7aef1b14 / cd1e4325 /
ad025c95 catch problems AFTER the model emits them. Telling the model
upfront — in the always-loaded layout skill — prevents the same patterns
in the first place. Cheaper than running a corrective post-pass on
every generation, and the model produces cleaner output that doesn't
trip the detectors at all.

What: AESTHETIC HYGIENE block appended to layout.md (priority 10, base,
loaded for every generation). 4 rules each backed by a corresponding
detector:

- Text never gets cornerRadius / stroke / effects / rotation. Mirrors
  detectTextCornerRadius / detectTextStroke / detectTextEffect.
- Rotation on UI frames is almost always wrong. Mirrors
  detectUnexpectedRotation (with the same 90/180/270 + path/line/polygon
  /image escape hatches).
- Same-role siblings must share cornerRadius AND padding. Mirrors
  detectMixedSiblingCornerRadius / detectMixedSiblingPadding.
- Inner layout frames (sections, wrappers) inherit from page/card —
  only opt into fill/stroke/shadow on the outer card/button/badge/chip.
  Mirrors the existing invisible-container detector.

Phrased as a "keep these silent" pre-condition since the post-pass
also strips them. 1080/1080 AI tests + 234/234 pen-ai-skills tests
still pass.
2026-05-09 21:28:00 +08:00
Fini 8475797c7f feat(ai): show per-category breakdown in pre-check status line
Why: when the pre-validation pass auto-fixes issues, the chat panel
just says "Pre-checks: fixed 5 issues" — generic and uninformative.
The user can't tell whether 5 invisible-container fixes happened
(structural, mostly safe), 5 unexpected-rotation fixes (aesthetic,
worth reviewing), or 5 mixed-sibling-padding fixes (consistency, worth
reviewing). With 10 detector categories now (4 original + 6 aesthetic
added in 53435bf7 / 7aef1b14 / cd1e4325 / ad025c95), the per-category
visibility starts to matter.

What:
- runPreValidationFixesDetailed() returns { total, byCategory } where
  byCategory is a per-category count of APPLIED fixes (excludes the
  info-severity skips and the protected-status-bar skip).
- runPreValidationFixes() kept as a thin wrapper returning .total so
  no caller needs to change.
- design-validation.ts now uses the detailed result and formats the
  breakdown as e.g. "fixed 5 (3 text-effect, 2 unexpected-rotation)"
  in the chat panel — sorted by count descending so the dominant
  category surfaces first. Both the no-vision-validation path and the
  size-gated skip path show the breakdown when it exists.

Falls back to the legacy "fixed N issues" format when byCategory is
empty (defensive — should never happen if total > 0). 1080 / 1080 AI
tests still pass — the new return shape is additive and the wrapper
preserves the integer contract.
2026-05-09 21:27:00 +08:00
Fini e8a07e9b08 feat(ai): aesthetic detector — mixed-sibling-padding (mirror cornerRadius rule)
Why: continuation of the aesthetic detector series. Mirrors
detectMixedSiblingCornerRadius (53435bf7) for the padding axis. Three
cards with padding 16 / 16 / 20 looks ragged on canvas; the existing
sibling-inconsistency detector covers cards-vs-cards but dedupes
against cornerRadius and other props so the padding outlier
sometimes drops.

What: detectMixedSiblingPadding normalises padding values to a
4-tuple [top, right, bottom, left] before comparison, so
  padding: 16            → [16,16,16,16]
  padding: [12, 24]      → [12,24,12,24] (CSS 2-tuple shorthand)
  padding: [16,16,16,16] → [16,16,16,16]
all compare equal and don't trigger false positives. Modal value
collapses back to a scalar when all four sides are equal so the
suggested fix matches the model's preferred shorthand.

Same 60% modal-majority threshold as the cornerRadius detector —
1-1-1 three-way splits are skipped because there's no canonical value
to suggest. Same divider / spacer skip and same-type-and-role grouping.

Wired through detectAllIssues + index.ts exports + the
debug_validation_report MCP categories enum.

6 new tests cover: number shorthand outlier, number-vs-array
equivalence, 2-tuple-vs-4-tuple equivalence, 1-1-1 split skip,
mixed-role groups skipped, no-padding siblings excluded from modal.
57 / 57 diagnostics tests pass (was 51; +6).
2026-05-09 21:26:00 +08:00
Fini b24bc58a51 feat(ai): aesthetic detector — text-stroke (outlined UI labels)
Why: continuation of the aesthetic detector series. Outlined text on a
UI label is almost always an AI mistake — Lucide / SF / Material icons
get stroked, but body / heading / label text is filled. The model
occasionally copies a generic "give it a stroke" instruction onto text
nodes; on canvas the result reads as double-rendered glyphs. The
existing sibling-inconsistency detector doesn't catch this because
text stroke is rarely a sibling-by-sibling outlier — it's emitted
across the whole tree at once.

What:
- detectTextStroke added with the same shape as the other text-only
  aesthetic detectors (text node + property check + warning severity +
  suggestedValue undefined).
- Skips stroke.thickness === 0 (some model JSON keeps an empty stroke
  object as a placeholder; flagging that would be noise).
- Wired through detectAllIssues + index.ts public exports + the
  debug_validation_report MCP tool's categories enum.

Tests: 4 new positive + negative cases (text with stroke, text without
stroke, text with thickness=0 placeholder, frame with stroke). 51 / 51
diagnostics tests pass (was 47; +4); 228 / 228 pen-ai-skills overall.
2026-05-09 21:25:00 +08:00
Fini 96965161af feat(ai): aesthetic detector — text-effect (shadow / blur on text labels)
Why: continuation of the aesthetic detector family added in 53435bf7.
The model frequently sprinkles \`effects: [{type:'shadow', …}]\` onto
body / label / caption text. On canvas the type goes fuzzy and reads
"AI-designed". Real product UIs use text shadows extremely sparingly
(hero overlays on photos, a few brand elements). Detection is cheap
(walk + isArray check) and the suggested fix (remove effects array)
is safe — text shadow on UI labels is almost never intentional.

What:
- detectTextEffect added to packages/pen-ai-skills/diagnostics with the
  same shape as the prior 3 (warning severity, suggestedValue undefined,
  reason string for logs).
- Wired through detectAllIssues + index.ts public exports + the
  debug_validation_report MCP tool's categories enum.

Tests: 5 new it() cases covering positive (shadow / blur on text),
negative (text without effects, empty effects array, frame with
effects), and tree-walk (multiple text effects in nested frames).
47 / 47 diagnostics tests pass (was 42; +5).
2026-05-09 21:24:00 +08:00
Fini fcc3d8b4d3 feat(ai): aesthetic detectors — rotation / text-cornerRadius / mixed-sibling-cornerRadius
Why: user reports the validation pipeline lacks "aesthetic standards"
— it accepts misalignment, unwanted corner radius, and other visual
issues as "normal". Existing detectors are pure code-quality (invisible
container / empty path / text height / sibling inconsistency); they
don't catch design-system violations the user can see at a glance.
Vision validation does, but it only runs on Anthropic / Codex /
OpenCode / Gemini providers and only above 30 nodes — leaving a long
tail of small-design / builtin-provider runs with no aesthetic check
at all. Adding cheap pure-function detectors closes that gap with no
upstream provider dependency.

What: 3 new pure detectors in pen-ai-skills/diagnostics:

  - detectUnexpectedRotation — flags non-axis-aligned rotation on
    UI-bearing nodes (frame / text / shape). Skips path / line /
    polygon / image (legitimate decorative geometry frequently
    rotated), skips multiples of 90° (intentional vertical text /
    grid). Catches the "tilted card" hallucination cleanly.

  - detectTextCornerRadius — flags text nodes with cornerRadius > 0.
    Text isn't drawn into a clipped rectangle so the prop is silently
    dropped at render time, but it survives in the doc and burns
    LLM context on subsequent batch_get calls. Suggested fix: remove.

  - detectMixedSiblingCornerRadius — stricter than the existing
    sibling-inconsistency check on cornerRadius alone. Flags outliers
    when 2+ of 3 same-type-and-role siblings share a value and one
    differs (e.g. three cards with cornerRadius 8 / 8 / 12 reads as
    ragged on canvas). Skips 1-1-1 three-way splits (no canonical
    modal) and divider / spacer nodes (visual primitives).

All three are wired through detectAllIssues + the index.ts public
exports + the debug_validation_report MCP tool's `categories` enum so
the user / agent can opt-in or filter via `op debug_validation_report
--categories unexpected-rotation`.

35 new tests cover the load-bearing positive + negative cases for each
detector. 219/219 pen-ai-skills tests pass (was 184; +35). 1080/1080
AI service tests still pass.
2026-05-09 21:23:00 +08:00
Fini 364a722c77 test(ai): extract Type 0 unwrap predicate as pure helper + 10 tests
Why: dd8eb0eb's unwrap pass (Type 0 single-component section root
hoist) was integration-tested via the live Playwright run but had no
unit coverage. The integration test won't catch regressions when
someone tightens the heuristics — and the load-bearing "do nothing"
guards (multi-section, mobile screen, desktop, 0/N children, non-frame
child) are exactly where a careless edit would silently flatten a
multi-page design.

What: split the helper into two — a pure predicate
shouldUnwrapSingleComponentSectionRoot(plan, root) returning bool, and
the existing unwrapSingleComponentSectionRoot(rootNodes, plan) which
calls the predicate then mutates the store. Predicate is exported.

10 new tests cover:
- 3 positive: wrapper id ends -root / wrapper id ends -section /
  wrapper name copies parent name
- 7 negative load-bearing guards: multi-section plan, mobile screen
  (height >= 480), desktop (width > 480), root with 0 children, root
  with multi children, wrapper with no children, wrapper with
  unrelated id+name, wrapper is non-frame (text / icon)

1080 / 1080 AI tests pass (was 1070; +10).
2026-05-09 21:22:00 +08:00
Fini 7cb28b52b6 fix(ai): propagate validate skipped reason into chat status line
Why: every time the vision validation loop returned skipped:true the
chat panel logged the same hardcoded "(timeout or provider error)"
string regardless of the actual cause — provider mismatch, HTTP error,
upstream config issue. Now that the server (validate.ts) returns
explicit skip reasons (e.g. "Vision validation is not supported for
builtin providers"), the UI should surface them so the user can fix
the right thing instead of guessing it's a timeout.

What: ValidationResult gains an optional `skippedReason` field.
validateDesignScreenshot fills it from response.json's `error` (or
the HTTP status text on a non-OK response) and propagates it through
the loop. The chat-panel status line now reads
"[error] Analysis skipped (<reason>)" with the server-provided
message clipped to 120 chars; falls back to the legacy string when no
reason is present.

1070 / 1070 AI tests still pass; no test depended on the literal
"timeout or provider error" string.
2026-05-09 21:21:00 +08:00
Fini 84fc0ffddb fix(ai): explicit skipped reason for builtin providers in vision validate
Why: builtin providers (MiniMax / DeepSeek / Bailian / Ark) currently
fall through to the generic "Missing or unsupported provider" error in
/api/ai/validate. The post-generation loop catches that as a hard
provider error and logs "[error] Analysis skipped (timeout or provider
error)" — which reads like a config bug to the user even though the
real reason is "this provider's models are text-only, vision validation
isn't useful here even if we did proxy it".

What: branch on body.provider === 'builtin' before the generic error
and return { skipped: true, error: '<explanatory message>' }. The
client design-validation.ts already short-circuits on `data.skipped`
so the loop now logs the clearer message instead. No behavior change
for the four supported providers; no new wire fields.
2026-05-09 21:20:00 +08:00
Fini 69db6a5dfc fix(ai): skip search-bar role styling inside nav-tab parents
Why: end-to-end test of "Design a bottom nav with Home / Search /
Orders / Cart / Profile" surfaced a stray coloured pill highlight
wrapping the Search tab. Root cause: the model labels the cell
\`role: 'search-bar'\` (intending "this tab whose icon is search"),
and the role-resolver dutifully stamps the input-shaped 44px-tall,
22-corner, filled-surface look onto the nav cell. Inside a 56px tall
tab row that pill swallows the icon + label, looks broken on canvas,
and competes for click area with the nav-item active state.

What: search-bar role now early-outs with `{}` (no overrides) when
ctx.parentRole is one of `bottom-tab-bar` / `tab-bar` / `tab-row` —
mirroring the same check the `button` role already uses to skip its
text-button defaults inside tab containers. Nav-cell layout / fill
remains the responsibility of nav-item / nav-item-active.

1070 / 1070 AI tests still pass; the input-shape default still applies
in every other context (forms, headers, hero search, etc.).
2026-05-09 21:19:00 +08:00
Fini ac689182cc fix(ai): unwrap redundant section-root when Type 0 plan has 1 subtask
Why: for Type 0 component plans (Notification Card / Profile Card / …)
the orchestrator pre-inserts a page rootFrame named after the component,
then the sub-agent emits its own section-root frame as the only child.
Result is a visible "Notification Card → Notification Card" double wrap
in the layers panel and a wasted layout depth that does nothing visual.
The double wrap was confirmed in the 2026-05-09 end-to-end test of the
notification-card prompt: depth-0 = orchestrator rootFrame (role=card),
depth-1 = sub-agent wrapper (also role=card), actual children at depth-2.

What: new unwrapSingleComponentSectionRoot pass added as Phase 4c right
after the mobile-status-bar dedup (mutually exclusive: that runs only on
mobile, this runs only on component-shaped plans). Conservative match —
only fires when:
  - plan.subtasks.length === 1, AND
  - plan.rootFrame is narrow (≤480) and auto-height (<480 or 0), AND
  - the orchestrator rootFrame has exactly 1 frame child, AND
  - that child's id has the sub-agent section-root suffix
    (`-root` / `-section`) OR the child copied the parent's name.

When the conditions hold, hoist the wrapper's children up via
store.moveNode (preserving order) and remove the wrapper. Multi-section
pages, dashboards, and mobile screens are untouched — early-out on the
plan.subtasks.length / width / height checks.

1070 / 1070 AI tests still pass; unit-testing this against the live
Zustand store is awkward, the integration verification will land via
the next end-to-end notification-card run.
2026-05-09 21:18:00 +08:00
Fini a0f2ecb7aa fix(ai): drop image from icon resolver noise list — it's a real lucide key
Why: my prior C3 resolver fix added `image` to ICON_NOISE_WORDS so
"Image Placeholder Path" (a non-icon container name) wouldn't collapse
to a circle. That was overcorrecting — `image` is also the canonical
Lucide icon key for the picture/photo glyph, and the model frequently
emits "Image Icon" meaning exactly that. With image stripped, "Image
Icon" tokenised to [] and the resolver returned without writing the
matched lucide:image path.

What: remove `image` from ICON_NOISE_WORDS, with an inline note that
the multi-word "Image Placeholder Path" pattern still resolves through
the prefix fallback (`image` covers >= 50% of `imageplaceholder` so
findPrefixFallback picks it up). Add a regression test for "Image Icon"
→ /image/.

1070 / 1070 AI tests pass (was 1069; +1).
2026-05-09 21:17:00 +08:00
Fini fea13441f1 fix(ai): add close-button aliases (dismiss/cancel/remove/closebutton/expand/collapse → x / maximize-2 / minimize-2)
Why: end-to-end test of "design a notification card with dismiss x
button" surfaced that MiniMax-M2.7 emits a path node named "Dismiss
Icon". Tokenisation gives "dismiss" but Lucide doesn't have a `dismiss`
key — the resolver fell through prefix/substring fallbacks and wrote
the placeholder lucide:circle, leaving the card with a hollow ring
where the X should be.

What: 5 new aliases added in lock-step to icon-dictionary.ts (client
commonAliases) + icon.ts (server NAME_ALIASES per existing comment):
  - dismiss   → x       (close button intent)
  - closebutton → x     (compacted from "Close Button Icon")
  - cancel    → x       (cancel-action close icon)
  - remove    → x       (remove-action close icon)
  - expand    → maximize-2
  - collapse  → minimize-2

NOT aliased: `cross`. Lucide already ships a `cross` icon (the
Christian-cross shape) and overriding it would lose that geometry.
"Cross" disambiguation is left to the model — if it really means a
close button, telling it to write "Dismiss Icon" / "Close Icon" via
the icon-catalog skill is enough.

Tests: 3 new it.each cases (Dismiss / Cancel / Remove Icon → /x/).
1069 / 1069 AI tests pass (was 1066; +3).
2026-05-09 21:16:00 +08:00
Fini 9c4815123e fix(ai): route workspace/console fallback prompts to desktop-screen, not landing-page
Why: Codex stop-time review #6 — C6 added workspace / console / 工作台 /
工作区 to the component DISQUALIFIER, but the dashboard detector regex
still only matched dashboard|admin|管理|后台|控制台. So "design a
workspace with side panel" skipped component (correct) AND skipped
dashboard (regex miss) and fell through to landing-page (1200×0,
4-section), which is the wrong shape for a workspace UI — the user
wants a 3-section desktop-screen with header/main/actions.

What: dashboard detector regex extended in lockstep with the
disqualifier — dashboard|admin|workspace|console|管理|后台|控制台|
工作台|工作区. Comment makes the "keep in sync" invariant explicit.

Tests: 4 new positive cases (Latin workspace + console, zh-Hans 工作台
+ 工作区 with 卡片) assert the plan returns 1200×800 with the 3-
section ['Header','Main Content','Actions'] layout, not the 4-section
landing-page default.

1066 / 1066 AI tests pass (was 1062; +4).
2026-05-09 21:15:00 +08:00
Fini db5fc9a4b0 fix(ai): expand Type 0 disqualifier so dashboard/admin/mobile prompts skip component
Why: Codex stop-time review #5 — broadening the component trigger list
from 17 to 25 nouns introduced false positives:
  "admin dashboard with metric tiles" → matched `tile` → Type 0 (400×0)
when the user clearly wants a desktop dashboard. Same for "design an
admin panel" / "workspace with charts" / Chinese 后台管理 + 卡片.

What: COMPONENT_DISQUALIFIER_RE gains three new keyword buckets in
addition to the existing screen / page / home / onboarding / flow:
  - mobile-screen markers — mobile, phone, ios, android, 手机, 移动端
  - workspace markers — dashboard, admin, workspace, console, 管理,
    后台, 控制台
  + zh-Hans 屏幕 (screen) was already added in C5.

These ensure component classification is reserved for "X card / X chip /
…" prompts that have no surrounding screen/dashboard/mobile context.
The dashboard / mobile prompts then continue down to their own explicit
detector branches and produce the right preset.

Tests: 7 new negative cases covering admin dashboards with tiles,
charts, panels, Chinese 后台 with 卡片, and mobile/phone prompts that
also mention card/badge. 1062 / 1062 AI tests pass (was 1055; +7).
2026-05-09 21:14:00 +08:00
Fini 42cd737dac fix(ai): expand Type 0 fallback regex to all documented component triggers
Why: Codex stop-time review #4 — the previous regex covered ~17 nouns
but design-type.md documents 25 (button / label / row / item / selector
/ panel / chart were missing) and the CJK 卡片 alias was also listed.
JS `\b` is ASCII-only and never fires between two CJK chars, so
`\b卡片\b` matched nothing in "design a 卡片".

What: split into COMPONENT_TRIGGER_LATIN_RE (full noun list with `\b`
boundaries) + COMPONENT_TRIGGER_CJK_RE (kana-free subset of the most
common Chinese aliases — 卡片 / 徽章 / 标签 / 按钮 / 开关 / 对话框 /
提示 / 气泡 / 图表). Either match is enough to classify Type 0.
Disqualifier regex also gains 屏幕 (screen in zh-Hans).

Tests: 23 it.each cases pin one Latin trigger each plus the CJK 卡片;
6 negative cases prove the disqualifier still wins for "X screen / page
/ app / onboarding / flow" prompts. 1055 / 1055 AI tests pass (was
1027; +28 new).
2026-05-09 21:13:00 +08:00
Fini 2d6b964240 fix(ai): close remaining Type 0 component leaks in fallback + agent paths
Why: Codex stop-time review #3 flagged "Type 0 component handling is
incomplete". The earlier C1 fix (orchestrator-plan-classify helper +
isMobileFullScreen heuristic) covered the orchestrator path, but four
more places still bucketed narrow widths (≤480 / ≤500) as mobile and
mishandled component-shaped plans.

What:
- agent-tool-executor.ts: replace `width<=500 ? 375 : 1200` bucket on
  setGenerationCanvasWidth with the inserted node's actual width — a
  400-wide profile card now estimates text against 400, not 375.
- design-type-presets.ts: add 'component' to DesignType union with
  width=400, height=0, and a single-section default. detectDesignType
  matches "X card / X badge / X chip / ..." prompts BEFORE the mobile
  / dashboard check, so the parse-failure fallback returns a 400px
  component instead of a 1200px landing-page for "design a profile
  card". Disqualified when prompt also names a screen / page.
- orchestrator-prompt-optimizer.ts: 3 spots — platform selection now
  uses preset.type==='mobile-screen' (component groups with webapp,
  not mobile, since it has no status bar / bottom nav); compact
  prompt rules and subtask hint get a component branch ("Use width=400
  height=0, exactly 1 subtask, no chrome"); fallback height map gives
  components a single 200px region instead of 800.
- orchestrator-planning.ts: buildFallbackHeights treats narrow +
  auto-height plans as component-shape and emits 200px sections,
  preventing the prior "812 / 1 = 812-tall card" output.

2 new tests pin: (a) "design a clean profile card" → 400×0 single
"Component" subtask with 200px region; (b) "design a card screen page"
must NOT shortcut to component (screen/page disqualifier holds).
2026-05-09 21:12:00 +08:00
Fini 381e86c412 Merge branch 'v0.8.0' of github.com:ZSeven-W/openpencil into v0.8.0 2026-05-09 21:11:00 +08:00
Kayshen-X 5aaa7b63fb chore(format): exclude vendor/skia-safe-op from prettier
The pre-commit hook runs `bun run format` (prettier via oxfmt) on
every staged commit; without a prettierignore entry the hook keeps
reformatting the upstream-original Cargo.toml / Cargo.toml.orig
files inside vendor/skia-safe-op/{skia-bindings,skia-safe}/ to use
2-space indent + flow-style author arrays — drift against the
crates.io tarball form that we want to preserve so the diff against
upstream rust-skia stays minimal and auditable.

Same treatment vendor/agent/ and vendor/jian/ already get.
2026-05-09 21:10:00 +08:00
Kayshen-X 172a012134 chore(ci): defer wasm release artifact until C-hard pipeline automated
Updates the rust-multiplatform + rust-release workflows for the
post-C-hard.2 reality where the wasm32-unknown-unknown bundle IS
runtime-loadable locally but the CI side still needs more
automation before it can publish a release artifact.

rust-multiplatform.yml:
  - add `vendor/skia-safe-op/**` to push + pull_request path
    filters so changes inside the fork actually trigger CI
  - rename the wasm-web job → "wasm32-unknown-unknown / openpencil-
    shell-web (compile guard)" to make explicit that this is the
    --no-default-features --features web stub-mount baseline, not
    the real render bundle
  - drop the artifact upload from this job: the stub .wasm has no
    skia and would mislead downstream consumers

rust-release.yml:
  - delete the standalone `wasm` job for now and update the comment
    to a DEFERRED block listing the 6 CI-side automation steps
    still missing (brew emscripten install, EMSDK env var,
    .wasm.a → .a symlink hack, wasm-bindgen + wasm-opt, browser
    smoke). Re-add the job once the pipeline lands
  - update the workflow header copy so it stops claiming to build
    the WASM bundle alongside desktop binaries
  - drop `wasm` from the release-draft `needs:` list

This is an explicit deferral, NOT a silent drop — every removed
piece is annotated with the work item it is waiting on.

Step 1b §3.2 P0.5B Run path, sub-phase C-hard CI follow-up.
2026-05-09 21:09:00 +08:00
Kayshen-X 5af1674f6b feat(shell): switch openpencil-shell-web to wasm32-unknown-unknown C-hard pipeline
Lights up the Phase A WebShell on the C-hard pipeline (vendor/skia-
safe-op + crates/wasm-libc-shim, wired in the previous two commits)
so `cargo build --target wasm32-unknown-unknown --features skia`
followed by `wasm-bindgen --target web` produces a browser-loadable
ES module with 0 env.* imports.

What's added:
  - WebBackend (src/backend/mod.rs): impl RenderBackend over a
    skia-safe raster N32_PREMUL surface; presents each frame to the
    host <canvas> via image_snapshot → read_pixels → ImageData →
    put_image_data. end_frame surfaces present errors via
    last_present_error / take_present_error so a stale failure does
    not leak into a subsequent successful frame
  - skia_wasm.rs: thin make_raster_surface helper so swapping in a
    GPU GrContext (Phase A round 2) is a self-contained change
  - mount(canvas_id) entry: locates the host <canvas>, builds a
    WebBackend, paints the Phase A red-rect demo synchronously,
    propagates any present error as a JsValue exception
  - smoke/step-1b.html: manual smoke harness that mounts the shell
    and surfaces a structured diagnostic (with regression-mode
    LinkError messaging + rebuild instructions) if loading fails
  - extern crate wasm_libc_shim as _; in lib.rs to keep the shim's
    no_mangle symbols from being dead-code-eliminated
  - .gitignore for wasm-bindgen pkg/ output

Cargo.toml feature wiring:
  - default = ["web"] keeps the kickoff §1.2 wasm32-clean compile
    guard CI green (stub mount, no skia)
  - skia = ["dep:skia-safe", "wasm-libc-shim"] opts into the real
    WebBackend + raster paint loop; the shim dep is target-gated
    so only wasm32-unknown-unknown actually pulls it in
  - wasm-bindgen = "=0.2.117" pinned (last release that compiles
    on Rust 1.85; bump alongside the toolchain in a future commit)

Verified end-to-end:
  - `cargo build … --features skia --release` green
  - `wasm-bindgen --target web` produces ../pkg/*.{js,_bg.wasm}
  - WebAssembly.Module.imports() returns 22 imports, all from
    ./openpencil_shell_web_bg.js; 0 env.* imports
  - post `wasm-opt -Oz`: 1542 KiB raw / 599 KiB gzip — within
    spec §6 ceiling (≤ 1024 KiB gzip)
  - the kickoff §1.2 wasm32-clean compile guard still passes
    (`cargo check … --no-default-features --features web`)

Browser-side manual smoke (Phase E) is still TODO; the bundle is
structurally LinkError-free but a human still needs to confirm the
red rect actually paints in Safari / Chrome / Firefox before the
sub-phase can be marked complete.

Step 1b §3.2 P0.5B Run path, sub-phase C-hard.2.
2026-05-09 21:08:00 +08:00
Kayshen-X 8ac685ff84 feat(shell): add wasm-libc-shim crate for wasm32-unknown-unknown skia bundle
Provides the libc / libcxx / libm symbols that the wasm32-unknown-
unknown skia static archive (built via vendor/skia-safe-op) imports
at link time but wasm-bindgen does not synthesize. With this crate
linked in, the post-bindgen bundle has 0 env.* imports and is
runtime-loadable as a vanilla browser ES module.

Categories implemented (~83 symbols, dedup against the actual
import list):
  - allocator: malloc / free / calloc / realloc / malloc_usable_size
    via dlmalloc-rs + a 16-byte size header per allocation so the
    GlobalAlloc::dealloc layout contract is preserved on free and
    realloc copies min(old_size, new_size) on grow
  - libm: asinh / acosh / atanh / nextafterf / remainder via libm
  - libc string: memchr / wmemchr / strcmp / strcpy / strtoull
    hand-rolled byte-wise
  - libc stdio: snprintf / vsnprintf / vfprintf as C-side variadic
    stubs (stdio_stub.c, compiled by cc) that route into a Rust
    extern wasm_libc_shim_stdio_panic before returning, so any
    actual invocation surfaces a named panic via console_error_
    panic_hook instead of a silent empty success
  - libc misc: abort (panics with diagnostic) + __errno_location
    (single-mut-static — single-threaded wasm only)
  - C++ ABI: __cxa_atexit (no-op), __cxa_guard_acquire / release,
    __cxa_pure_virtual (panics)
  - operator new / delete: _Znwm / _Znam / _ZdlPv* / _ZdaPv*
    forwarding to malloc / free; _Znwm(0) routes through
    malloc(1) per C++ standard (operator new must return a
    non-null pointer)
  - threads: sem_init / sem_destroy / sem_post / sem_wait no-op
  - libcxx string / locale / iostream / shared_weak_count /
    to_string: ~23 panic stubs via the libcxx_stub! macro that
    panic with the symbol name; these are linker-pulled by
    templated code that the skia raster + custom_empty fontmgr
    pipeline does not exercise at runtime, so a panic = regression
    signal

Build-time gating:
  - active only on wasm32-unknown-unknown via cfg(all(target_arch
    = "wasm32", target_os = "unknown")); native builds link an
    empty crate so the symbols do not collide with the host libc
  - compile_error! on target_feature = "atomics" because the
    static-mut errno + non-atomic __cxa guard impls would race
    under wasm threads — the path forward is real TLS errno +
    atomic guard variables in a follow-up sub-phase

Step 1b §3.2 P0.5B Run path, sub-phase C-hard.2.
2026-05-09 21:07:00 +08:00
Kayshen-X 4b8bb136e7 chore(workspace): patch skia-bindings + skia-safe to vendor/skia-safe-op
Wires the workspace at vendor/skia-safe-op (committed in the previous
commit) via [patch.crates-io] so every consumer of skia-safe /
skia-bindings — both the wasm32-unknown-unknown shell-web bundle and
the macOS / Linux / Windows shell-native desktop binary — resolves
through the fork on every target.

[patch.crates-io] is workspace-global, NOT target-scoped; cargo does
not natively support per-target patches, so this is the accepted
blast radius. The fork is byte-identical to upstream rust-skia 0.97.0
except for the new `wasm_unknown` platform module + its single new
dispatch arm; native builds resolve to the same upstream platform
modules they did before. Verified `cargo check -p
openpencil-shell-native` builds through the fork unchanged.

Trade-off: upstream rust-skia patches no longer flow until we
re-vendor; Cargo.lock records `path` sources for skia-bindings /
skia-safe rather than `registry+...`. The full rationale block is
inline in Cargo.toml.

The Cargo.lock delta also pins js-sys 0.3.97 → 0.3.94 / web-sys
0.3.97 → 0.3.94 — this is the transitive consequence of pinning
wasm-bindgen = "=0.2.117" on shell-web (last 0.2.x release that
compiles on the workspace's Rust 1.85 toolchain; 0.2.120+ requires
1.86). Documented in shell-web/Cargo.toml.

Step 1b §3.2 P0.5B Run path, sub-phase C-hard.1.
2026-05-09 21:06:00 +08:00
Kayshen-X d6e655277c chore(vendor): add skia-safe-op fork with wasm32-unknown-unknown platform
Vendors rust-skia 0.97.0 (from crates.io tarballs) into
vendor/skia-safe-op/{skia-bindings,skia-safe} and adds a single new
platform module — build_support/platform/wasm_unknown.rs — that
recompiles Skia C++ directly into the wasm32-unknown-unknown ABI:

  - reuses emsdk's libc / libcxx headers via -isystem
  - drops C++ exceptions + RTTI (-fno-exceptions -fno-rtti) so the
    resulting .o files do not import emscripten's exception runtime
  - forces clang's target via --target=wasm32-unknown-unknown
  - sets CC_/CXX_/AR_wasm32_unknown_unknown so the cc-crate FFI shim
    also picks up emsdk's bundled clang (host clang lacks wasm32)
  - on every gn_args invocation overwrites skia/bin/activate-emsdk
    with a no-op python stub so Skia's GN does not try to bootstrap
    a parallel emsdk install (we use emsdk's clang directly)

Why a fork: wasm-bindgen --target=web on wasm32-unknown-emscripten
emits emscripten library glue, not a browser-loadable ES module,
which is incompatible with our distribution model. Compiling Skia
to wasm32-unknown-unknown unblocks the browser ES module path; the
remaining libc/libcxx/libm gap is filled by crates/wasm-libc-shim
in a follow-up commit.

The Skia C++ source tree under skia-bindings/skia/ (~770 MB, 30k+
files) is gitignored — it is fetched at build time by
binary_cache::download. Only the Rust source from the upstream
0.97.0 crate tarballs and the new wasm_unknown platform module are
committed here.

Step 1b §3.2 P0.5B Run path, sub-phase C-hard.1.
2026-05-09 21:05:00 +08:00
Kayshen-X 92f7898329 build(step-1b): add tools/fetch-skia-artifact.sh (Variant A release path)
Codex P0 mini-gate Round 3 BLOCK fix: P0.2 plan calls for
tools/fetch-skia-artifact.sh, and Phase A CI step invokes it before
measuring bundle size — but the script did not exist in the OP repo.
Phase A cannot start without it.

Variant A (GitHub release asset) selected per probe notes §3.1
"Artifact Distribution Strategy": <1 MB gzip, free hosting, no extra
git-lfs setup overhead.

Behavior:
  exit 0  artifact present and SHA matches OR no release pinned yet
          (Phase E will publish; dev loop uses skia-bindings from-source)
  exit 1  artifact present but SHA mismatched, or fetch failed after
          a download attempt

Phase E will overwrite RELEASE_TAG / RELEASE_FILE / EXPECTED_SHA256
constants with the published release asset metadata. Until then dev
builds run skia-bindings from source (no fetch needed).

Smoke run: `bash tools/fetch-skia-artifact.sh` →
"no release tag pinned yet — Phase E will publish; dev builds use
skia-bindings from-source path" + exit 0.
2026-05-09 21:04:00 +08:00
Kayshen-X 5a027a4f4e test(shell-core): assert W3C field readback in gesture re-export tests
Codex P0 mini-gate Round 2 finding (Q5) fix: gesture_re_export.rs tests
set the new W3C fields (KeyEvent.is_composing, FocusEvent.related_node_
id_hint, WheelEvent.delta_z + WheelEvent.mode mutability) but only
asserted the structural compile-time identity, not value readback.

Strengthened to assert every W3C field reads back what was written so
cross-crate type identity AND field-level binary compat are both verified
through the OP re-export path:
- key_event_is_re_exported_from_jian_with_all_w3c_fields: 7-field assert
- focus_event_is_re_exported_from_jian_with_all_w3c_fields: 3-field assert
- wheel_event_is_re_exported_from_jian_with_w3c_fields: defaults +
  mutate-and-assert mode + delta_z + delta.x/y

cargo test -p openpencil-shell-core --test gesture_re_export → 6/6 PASS.
2026-05-09 21:03:00 +08:00
Fini 40a085d0f8 fix(ai): tokenize path icon names so multi-word "Search Icon Path" resolves
Why: MiniMax-M2.7 keeps emitting path nodes named "Search Icon Path" /
"Time Icon Path" / "Heart Icon Stroke" (3 words ending in noise word).
The legacy resolver normalised to "searchiconpath" (15 chars), prefix
fallback found "search" (6/15 = 40% < 50% threshold) → rejected →
fallback to lucide:circle → user-visible "circle bug" across categories,
filter chips, and search bar leading icons. Skill update alone (telling
models to use icon_font) doesn't fix the trained-pattern leftover —
Codex flagged this as a still-unfixed failure mode.

What: extractIconKeyword() tokenises on camelCase / space / dash /
underscore boundaries and drops { icon, logo, symbol, glyph, path,
shape, stroke, fill, svg, graphic, image }. Surviving tokens are
concatenated for direct dictionary lookup. Pure-noise names ("Icon
Path", "Symbol") return early without writing the misleading circle
placeholder. time / deliverytime / rider aliases added (kept in sync
across icon-dictionary.ts and server icon.ts NAME_ALIASES per existing
comment). 11 new tests cover multi-word resolution and pure-noise
no-op; 21 prior regression cases (descriptive geometry untouched,
single-word camelCase / kebab / snake all resolve, "Brand Logo"
placeholder behaviour preserved) still green.
2026-05-09 21:02:00 +08:00
Fini 624cd75543 feat(ai): rewrite icon-catalog skill + add transparent-section rule
Why: MiniMax-M2.7 food-app run rendered Header with white fill on cream
page bg, and used iconFontName=shopping-bag for Cart tab. Two skill-side
issues: icon-catalog.md was self-contradictory ("use path nodes" vs
"use icon_font"), and layout.md had no rule for inner-section bg.

What:
- icon-catalog.md rewritten as "ALWAYS USE icon_font, NEVER path NODES"
  with role→name map (Cart→shopping-cart not shopping-bag, Pizza→pizza,
  Sushi→fish via alias, etc) and food-category icon list appended.
- layout.md adds: interior section wrappers (Header, Search Section,
  Categories Section) MUST have fill:[] (transparent / inherit page bg);
  only opt into a fill when the section is intentionally a card with
  its own surface tone.
2026-05-09 21:01:00 +08:00
Fini af9292d8f5 fix(ai): classify Type 0 components as non-mobile to skip phone chrome
Why: "Design a profile card" through MiniMax-M2.7 produced a 375×803 mobile
screen with auto-injected status bar, because the planner skill listed
"profiles" as a Type 2 single-task screen and the orchestrator's
isMobileScreen heuristic ran on width≤480 alone.

What: design-type.md + decomposition.md add Type 0 (single component:
card / badge / chip / modal) with width=400 height=0 1 subtask no chrome.
isMobileFullScreen helper extracted to orchestrator-plan-classify.ts and
required by both orchestrator.ts and orchestrator-sub-agent.ts so the
two paths can't drift on what "mobile" means (Codex review caught this
when only orchestrator.ts had the new check).

Verified with same MiniMax + same prompt: 400×320 component, 8 nodes,
firstChildRole=card, no status-bar.
2026-05-09 21:00:00 +08:00
Fini 5aed1d9d24 fix(ai): edge-padding detector skips mobile-width components
The 12th detector landed in 55f1f5d7 fired on any frame 320–480 wide
regardless of height — so a 393×88 bottom-nav, a 393×200 tile, or a
393×500 settings panel being designed in isolation got page-level
gutters auto-applied as if it were the page root.

Tighten the page predicate to require height >= 568 (iPhone SE 1st gen,
the shortest production phone) AND aspect ratio h/w >= 1.5. Real phones
clear both bars; mobile-width components do not.

Surfaced by Codex stop-hook review on the previous commit.
2026-05-09 20:59:59 +08:00
Fini 2b534c7cf3 feat(ai): detect mobile section glued to screen edge
Add detectEdgeSectionPadding (12th pre-validation detector). Flags a
mobile-shaped page root (width 320–480) when its horizontal padding is
0 AND a child content section also has 0 left padding AND that section
contains visible text or icon descendants — the chain that produced the
"Categories" no-padding bug. Suggested fix sets root.padding to
[top, 16, bottom, 16] preserving vertical padding.

False-positive guards skip top-nav / bottom-nav / hero / banner roles
and image-only sections that are intentionally full-bleed.

The new detector lives in its own detectors-spacing.ts since detectors.ts
is already over the 800-line file limit.
2026-05-09 20:59:58 +08:00
Fini e5ac53017d fix(ai): run clipCardImageCorners AFTER role-resolver fills in card defaults
Why: Codex stop-time review 2026-05-10 — clipCardImageCorners was
slotted between unwrapFakePhoneMockups and resolveTreeRoles in the
post-streaming pipeline. Cards that don't carry an explicit
cornerRadius from the sub-agent get one filled in by role-resolver
(e.g. role='card' → default cornerRadius=12). Running clip before role
defaults silently skipped every default-radius card — match policy
required scalar cornerRadius > 0 and saw cornerRadius=undefined at
that point. Net effect: the bug stayed for the most common case where
the model wrote role='card' without a numeric radius.

What: move the clipCardImageCorners call to the freshRoot block right
after resolveTreeRoles + resolveTreePostPass. By that point the
role-resolver has populated defaults, so a card without an explicit
radius now correctly hits the predicate. Reuse the existing
\`freshRoot\` reference (re-fetched after updateNode mutations earlier
in the pipeline) so we don't double-fetch from the store.

No new tests — the existing 9 unit tests already pin the predicate;
the bug was placement-only. 1448 / 1448 pen-core tests, 1110 / 1110
AI service tests still pass.
2026-05-09 20:59:57 +08:00
Fini feeea98ed8 fix(ai): clean card-image corners + strip wrapper stroke/cornerRadius with fill
Why: 2026-05-10 user report — "你看不到任何真正的生产级设计工具的希望"
called out three persistent visible issues with the food-app design:

  1. Search bar shows a "weird inner rounded border" (image 7) — the
     wrapper around address+search section sets fill + stroke +
     cornerRadius together. strip-redundant-section-fills only cleared
     the fill; the leftover stroke + cornerRadius kept drawing the
     visible inner pill, which has been there for a long time.

  2. Card image has all 4 corners rounded (image 8) — Taco Fiesta /
     Bella Italia cards show the food image with bottom corners
     rounded too, leaving them visually "ragged" against the title
     text below that's flush with the card surface.

(The third — Categories padding — is a layout/intent question; left
for later since it can't be auto-fixed safely without knowing whether
the design wants edge-to-edge content.)

What — two coordinated fixes:

  Fix #1: strip-redundant-section-fills now removes stroke and
  cornerRadius alongside the fill. A misroll wrapper sets all three
  together to "look like a card"; the fill gets stripped on detection
  but the leftover chrome kept drawing a phantom card outline. The
  three travel together so they should be cleared together. New test
  pins the search-bar wrapper case.

  Fix #2: new clipCardImageCorners pass in pen-core. When a card-shape
  parent (scalar cornerRadius > 0, 2+ children, first child is an
  image or canonical image-placeholder, image has its own scalar
  cornerRadius) is detected, set parent.clipContent = true and remove
  the image's scalar cornerRadius. The card's own corner clip then
  cleanly handles the image — top corners round with the card, bottom
  corners flush against the title below. 9 unit tests pin the
  conservative match policy (silent on standalone image, title-first
  card, array-form cornerRadius, cornerRadius:0, no image
  cornerRadius, nested cards, existing clipContent).

Wired into applyPostStreamingTreeHeuristics right after
unwrapFakePhoneMockups. 1448 / 1448 pen-core tests pass (was 1438; +10);
1110 / 1110 AI service tests still pass.
2026-05-09 20:59:56 +08:00
Fini 40dfc55c95 feat(ai): aesthetic detector — excessive-frame-effects (spread > 0 / blur > 40 / 3+ stacked)
Why: 2026-05-10 user report — "Mexican" badge in the food-app screenshot
landed with a "带尖的背景阴影" (pointy / spiked background shadow). The
underlying cause is the model emitting effects with positive spread,
which "bleeds" the shadow color outward and creates a visible bloom /
halo around the badge that doesn't match real product UI shadows.
Real UI shadows are tight: blur 4-16, spread 0, near-black low-alpha.
Existing detectors only handle text effects (text-effect from 7aef1b14);
frame-level effects had no aesthetic gate.

What: detectExcessiveFrameEffects flags a frame node iff ANY of:
  - blur > 40 (glow / halo signature; modal-shell scrim uses exactly
    40 so the threshold is strict-greater to keep that legitimate use
    untouched — verified by detectors-builder-clean.test.ts)
  - any effect carries spread > 0 (bleeding outward = the "spiked
    shadow" the user called out)
  - 3+ stacked effects on one frame (typical UI uses 0-2)

Suggested fix is to remove the effects array; the user / agent can
re-add a proper subtle shadow afterwards if intentional.

Wired through detectAllIssues + index.ts public exports + the
debug_validation_report MCP categories enum. Skips text nodes (those
go through detectTextEffect with a stricter zero-tolerance rule).

7 new tests cover: positive on spread > 0 / blur > 40 / 3+ stacked,
negative on typical subtle shadow / no effects / blur exactly 40
(modal-shell legit) / text node (different detector). 241 / 241
pen-ai-skills tests pass (was 234; +7). 1110 / 1110 AI service tests
pass (unchanged — production builders pre-clean).
2026-05-09 20:59:55 +08:00
Fini 828f09abda fix(ai): strip dark hedge fill on container-role wrappers holding 2+ same-role children
Why: 2026-05-10 user report — the food-app "Featured" block landed
with a black background on a cream page. The wrapper had role='card'
AND held 3 restaurant cards each with role='card'. The existing
strip-redundant-section-fills pass treats role='card' as PROTECTED
(cards legitimately own their fills) so the black hedge fill survived.
Visible result: a giant black band between Categories and Popular Near
You that doesn't fit the cream page bg — exactly the "莫名其妙的背景颜色"
issue the user called out.

Root cause: the existing wrapper detection (hasNestedFilledComponent)
only fires for ATOMIC roles (search-bar / button / input / badge /
chip / tag / pill). Container-role wrappers around same-role children
were never matched, so a card-of-cards misroll kept its fill.

What: new hasMultipleSameRoleChildren predicate. Treats a frame as a
section-level wrapper (eligible for safe-dark / safe-light fill
stripping) when ALL of:
  - frame role is in CONTAINER_PROTECTED_ROLES (card / banner /
    pricing-card / feature-card / image-card / testimonial /
    metric-card / gallery-item / phone-mockup)
  - frame has ≥ 2 children with the SAME role
  - existing safe-hex / root-match check still applies

Net effect: the Featured wrapper's #000000 fill is now stripped, the
section inherits the cream page bg as intended, and the 3 inner
restaurant cards keep their own white surface fills (each was
role='card' but only 1 child of the same role per card, so the
predicate is silent on them).

3 new it() cases pin: Featured-block misroll (3 cards inside) gets
stripped, single-same-role-child stays untouched, banner-wrapping-
banners pattern also strips. 25 / 25 strip tests pass (was 22; +3).
1438 / 1438 pen-core tests pass overall.
2026-05-09 20:59:54 +08:00
Fini fef986098e fix(ai): heuristic image-area requires 0 children or icon_font child
Why: Codex stop-time review 2026-05-10 caught a content-erasure bug.
The b9b4126b heuristic accepted "0 or 1 children" with no type check,
so a hero frame named "Hero" with a single CTA button child matched.
Then the queue's update path (line 388-391 of processQueue) clears
\`children: []\` when the photo lands — destroying the legitimate CTA
button under it. Same risk for banners with sale text, covers with
nested frames, etc.

What: tighten the children clause in isImageAreaFrameByHeuristic. A
heuristic frame is now accepted only when:
  - children is undefined / not an array, OR
  - children.length === 0, OR
  - children.length === 1 AND children[0].type === 'icon_font'
    (the typical "broken image" placeholder hint).

Anything else — single non-icon child OR multiple children — means the
frame holds real content and the children:[] erase step would damage
the design. Such frames are now rejected by the heuristic and stay
unchanged on canvas.

3 new it() cases pin the rejection: hero+button, banner+text, and
cover+nested-frame all return false. Existing single-icon-child case
still passes. 38 / 38 tests in image-search-pipeline.test.ts (was 37;
+1; the rejection case adds 1 new it). 1110 / 1110 AI tests pass.
2026-05-09 20:59:53 +08:00
Fini 8f35ded088 fix(ai): queue still-needs-fill check accepts heuristic image-area frames
Why: Codex stop-time review #N (2026-05-10) caught the real bug — my
b9b4126b / 810c2f7a chain detected heuristic image-area frames at
collectImageSearchTargets and enqueued them at enqueueImageForSearch,
but the queue processor's still-needs-fill re-check (line 350-358 of
processQueue) called isUnfilledImagePlaceholderFrame which strictly
requires role='image-placeholder'. Heuristic frames have no role, so
the re-check returned false and the queue silently dropped them
before issuing the fetch — net effect was zero photos for the food-app
card scenario the heuristic was supposed to fix.

What: extract a new pure-function predicate
\`isFramePlaceholderStillUnfilled(node)\` that accepts a node iff it is
EITHER a canonical unfilled placeholder (role-based) OR a heuristic
match (name-based). Queue processor calls this single helper instead
of the strict canonical-only check. The helper is also exported and
test-covered separately so a future regression on this code path
fails loudly.

6 new it() cases pin: positive on canonical + heuristic, negative on
already-filled (canonical AND heuristic), null/undefined, and
unrelated frame names. 31 → 37 tests in image-search-pipeline.test.ts;
1109 / 1109 AI service tests pass overall (was 1103; +6).
2026-05-09 20:59:52 +08:00
Fini 47646bc655 test(ai): exercise extractQueryForNode + findParentSemanticName
Why: 810c2f7a added the parent-walk query mining for heuristic image-
area frames but landed without unit coverage of the two new helpers.
Without it, a future edit to GENERIC_PLACEHOLDER_NAMES or the layout-
word filter could silently regress query quality (e.g. start emitting
"Wrapper" or "Section" as queries) and the food-app card photos would
go back to looking generic.

What: export the two helpers and add 5 it() cases covering:
- explicit imageSearchQuery wins over name
- generic literal "Image" + parent "Bella Italia" → returns "Bella Italia"
- skip layout words ("Card Wrapper") in the parent walk; accept the
  next semantic ancestor ("Margherita Pizza")
- 4-hop layout-only chain returns null (maxHops bound)
- fall back to non-generic-but-image-themed name when parent walk
  yields nothing ("My Custom Photo")

31 / 31 tests in image-search-pipeline.test.ts pass (was 26; +5).
1103 / 1103 AI service tests pass (was 1098; +5).
2026-05-09 20:59:51 +08:00
Fini 2da0f3625e fix(ai): query mining + enqueue path for heuristic image-area frames
Why: b9b4126b's collectImageSearchTargets returns heuristic-matched
frames (named "Image" / "Photo" / "Cover" without the canonical
role) but two downstream code paths quietly dropped them:

1. enqueueImageForSearch only accepted type==='image' or
   isUnfilledImagePlaceholderFrame, so the heuristic frames got past
   collect but never reached the queue.

2. extractQueryForNode would have returned the literal name "Image" or
   "Photo" — useless to the photo search API. The user's "Bella Italia"
   restaurant card never gets a relevant photo because the placeholder
   frame's name says nothing about the restaurant.

What:
- enqueueImageForSearch grows a third branch: isImageAreaFrameByHeuristic
  → kind: 'placeholder-frame'. Same kind so the rest of the pipeline
  treats it identically to a canonical placeholder.
- extractQueryForNode learns to skip "generic" placeholder names
  (Image / Photo / Cover / Hero / Thumbnail / Banner / Poster + a few
  variants) and walk up to the nearest semantic parent frame name
  ("Bella Italia" / "Margherita Pizza" / "Sushi House" — whatever the
  enclosing card was named). Bounded to 3 hops. Filters layout words
  (Card / Wrapper / Container / Section / Frame / Root / Page / Stack /
  Row / Column / Content) so we don't end up searching for "Card".
- A new helper findParentSemanticName builds a parent map from the
  live document on demand. Cheap for typical designs (< few hundred
  nodes); avoids threading parent through every collect / enqueue call
  site.

Net effect: a model-emitted plain "Image" frame inside a "Bella Italia"
card now searches for "Bella Italia" instead of literally "Image". The
existing isImageAreaFrameByHeuristic test coverage protects the entry
condition; 1098 / 1098 AI service tests still pass.
2026-05-09 20:59:50 +08:00
Fini 98211e6226 fix(ai): heuristic image-area detection for non-canonical frame placeholders
Why: 2026-05-09 user report — the food-app card design landed with
empty colored rectangles where restaurant photos should be (Bella
Italia / Green Bowl / Margherita Pizza). Root cause: the model emitted
plain frames named "Image" / "Photo" / "Cover" with a solid fill as
the card-top image area, instead of using add_image_placeholder_v1
(which sets role: 'image-placeholder'). The auto-search pipeline
strict-checks role and missed all of them, so scanAndFillImages found
nothing to search and the cards stayed solid-colored.

What: new isImageAreaFrameByHeuristic(node) supplements the strict
role check. Conservative match — only fires when ALL of:
  - frame node WITHOUT role='image-placeholder' (strict path handles
    that)
  - name matches /\\b(image|photo|cover|hero|thumbnail|thumb|picture|
    banner|poster)\\b/i
  - width >= 80 AND height >= 60 (filters tiny color swatches)
  - exactly one solid (non-image) fill (gradient = decorative, image
    = already filled, both skip)
  - 0 or 1 children (an icon child is OK, multi-child = real layout)

collectImageSearchTargets walks both the strict and heuristic paths
and produces the same kind: 'placeholder-frame' target either way, so
the existing query / aspect / search code-path runs unchanged.

10 new tests cover positive matches (Image / Photo / Cover / Hero /
Thumbnail / Banner / Poster), negative for canonical placeholder
(double-counting prevented), unrelated names (Card / Wrapper),
already-filled image fills, gradients, content-rich frames, single-
icon-child acceptance, undersize frames, and non-numeric dimensions.
26 / 26 tests in image-search-pipeline.test.ts pass (was 16; +10).
1098 / 1098 AI service tests pass (unchanged).
2026-05-09 20:59:49 +08:00
Fini 9fd6abb8ea fix(ai): sidebar-nav-v1 also canonicalises wrong-glyph icons via label
Why: f1923ff1 added coerceNavTabIcon to bottom-nav-v1 and noted that
sidebar-nav-v1 should adopt the same helper. Without it, a sidebar
nav with \`{ label: 'Profile', icon: 'profile' }\` would still render
a placeholder circle (resolver doesn't know "profile" is a known
wrong-glyph alias for "user") instead of the lucide:user glyph.

What: import coerceNavTabIcon and apply it in buildItemV1 before
stamping iconFontName onto the Icon child node. Same convention
single-sourced. Existing 1435 tests still pass — no test relied on
the prior pass-through behavior for known wrong-glyph names.
2026-05-09 20:59:48 +08:00
Fini ac8dfcee1b fix(ai): bottom-nav-v1 canonicalises wrong-glyph icons via title (Cart→shopping-cart)
Why: end-to-end test of "Design a bottom nav with Home / Search /
Orders / Cart / Profile" with MiniMax-M2.7 surfaced that the model
emits \`{ title: 'Cart', icon: 'shopping-bag' }\` for the Cart tab
~half the time. Both icons exist in lucide but they are different
glyphs — bag is for carrying, cart has wheels for checkout. The
icon-catalog skill update (19ca1c66) fixed it for the planning side
but not for the builder's runtime input — direct \`add_bottom_nav_v1\`
calls still pass through whatever icon the model picks.

What: new \`coerceNavTabIcon(title, icon, builder)\` helper in
coerce-params.ts. Maintains a small Title→canonical-lucide-name map
(Cart→shopping-cart, Profile→user, Home→house, etc., with Chinese
labels) AND a per-canonical KNOWN_WRONG_ALTS list so the swap only
fires when the emitted icon is one of the known wrong-glyph choices
for that title:

  Cart + shopping-bag         → shopping-cart  (warn)
  Cart + package              → shopping-cart  (warn)
  Cart + rocket               → rocket         (pass-through)
  Cart + shopping-cart        → shopping-cart  (silent)
  Custom + anything           → anything       (silent)

The pass-through rule keeps user / model intentional custom choices
intact. Warnings flow through the existing coerce-params sink so
orchestrators can surface them.

bottom-nav-v1.ts now calls coerceNavTabIcon before stamping
iconFontName onto the Tab frame. Sidebar-nav-v1 + similar nav
builders can adopt the same helper later without re-implementing the
map.

10 new unit + integration tests cover: positive swaps for cart /
profile / notifications / Chinese 购物车, pass-through for
custom titles, case-insensitivity, and the builder integration
that the emitted Tab tree carries the canonical iconFontName.
1098 / 1098 tests pass overall (1080 AI + 10 new + 8 elsewhere).
2026-05-09 20:59:47 +08:00