mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 14:16:28 +03:00
* Improve Live polling responsiveness and reliability Restore foreground/background polling as the primary harness architecture, add progressive publication and framework-safe previews, and harden quality and regression coverage. The experimental app-server runtime is intentionally excluded.\n\nPrepared with AI assistance under maintainer direction. * Fix source-safety, detector, and lock defects in Live polling work Addresses the review findings on #371, plus several the bots did not catch. All fixes have regression coverage that fails on the prior code. Source corruption: - Vue accept dropped valueless root attrs (disabled, v-cloak) and, worse, rewrote @click="x" as a literal click="x" DOM attribute, because the attr parser was name-anchored and skipped the sigil. Tokenize the whole Vue attr grammar and normalize shorthands so accept round-trips directives. - --variant was interpolated unescaped into a RegExp, so --variant '.*' matched the original block first and reported a successful accept while silently restoring the original. Validate against the digits pattern the browser and the /events schema already enforce. - --id reached path.join unvalidated, so --id ../../../../etc/evil wrote and read receipts outside the project. Hoist the existing safeSessionId check into impeccable-paths and apply it at every id-to-path sink. Accept/lock correctness: - Plain HTML/JSX accept and discard did not catch SOURCE_LOCKED, so contention exited non-zero with empty stdout and the agent got no JSON to retry on. - Lock staleness was mtime-only and never read the pid it records: a holder whose critical section outran 60s had its live lock swept, admitting a second writer to the same file, while a crashed holder blocked accepts for a full 60s. Decide staleness by owner liveness, and release only our own lock. Detector: - isNeutralColor only parses computed color forms, so routing authored CSS through it reported inset 4px 0 0 #000 / black / #e5e7eb as chromatic side-tab stripes. Add an authored-color neutrality test covering hex and named neutrals; the fixture had no literal-color cases at all. - Rule line numbers were off by one for every rule after the first, and commented-out CSS was scanned as live rules. Server: - An error reply carries no sourceEventType, and inferSourceEventType returned undefined, which acknowledgePendingEvent treats as a wildcard: a stale generate worker's failure consumed the user's queued Accept, which then reached no agent and left the browser in SAVING forever. - The generate preflight spawned live-wrap.mjs synchronously inside the request handler, freezing the single-threaded server for the whole scaffold (~7.6s measured on this repo, 15s ceiling) and stalling Accept/Discard/SSE. Make it async, claiming the lease before the first await so no event double-delivers. - Every browser checkpoint was echoed back as variant_progress, so a Tune slider drag remounted the preview under the user's cursor and latched the *_reviewable phases from the wrong trigger. Gate on the reason. Cleanup: - Collapse four divergent benchmark argv parsers into scripts/lib/cli-args.mjs. Three silently misread flags: --iterations 20 benchmarked 5, --agent llm ran the fake agent, --median-target=0.4 used the default threshold. - Drop a snapshot cache this branch made write-only (it grew per session for the server's lifetime and was never read), a dead exported reconcile helper, and the unused deferReply branch. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Route the last two benchmark scripts through the shared argv parser Follow-up on review feedback. The previous commit consolidated four of the six Live benchmark parsers and left these two on their own hand-rolled `arg()`, which was the inconsistency the first pass was meant to remove. - benchmark-live-control.mjs and benchmark-live-init.mjs parsed --iterations with Number(), so a non-numeric value became NaN and `index < NaN` ran the benchmark zero times before failing on the metrics file. They also accepted only the space-separated form, so --iterations=20 silently measured the default. Both now use parseArgs + positiveIntFlag, which throws on a value that was clearly meant as a number. - benchmark-live-control.mjs read the metrics file with no handling for the case where the run produced nothing: a missing file surfaced as a raw ENOENT stack and a malformed line as a bare SyntaxError. Report both with a diagnostic naming the file and the env var that populates it. - summarize() now reports a `samples` count and nulls instead of letting percentile() read past an empty array, where the NaN serialized to null and a report of nothing measured looked like a real measurement. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Stop telling users a busy agent is disconnected The agent-poll indicator tracks whether a poll is parked, which is the right signal for "can steering reach the agent right now" and is why the flag itself is left alone. But it goes quiet for two different reasons, and both got the same copy: "Agent disconnected - run live-poll.mjs to connect". Under the one-shot foreground polling that live.md calls the primary contract, no poll is parked while the agent works, so the second reason is every normal generation. For its whole duration the bar told the user a healthy session was broken and advised them to start a poll loop that was already running. Pick the copy from the live state, which the browser already tracks: GENERATING and SAVING mean the agent holds work it was handed, so say it is working. Every other state with no parked poll keeps the original, actionable wording. The aria-label carries the same distinction, since the tooltip is mouse-only. The text is derived at read time rather than cached, because the live state moves between the 5s status polls and a finished generation would otherwise keep reading "Agent is working" until the next one landed. Deriving it also keeps the read out of setLiveState, which runs long before agentPollingConnected's declaration and would hit its temporal dead zone. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Scope design-system-font-size off the injected live overlay live-browser.js builds a self-contained UI that renders over arbitrary host pages, so its inline type scale is deliberately independent of DESIGN.md, which documents the impeccable website's ramp. The rule fired 32 times there and is the only rule that fires on that file. Suppress it as a file-scoped value wildcard rather than via ignoreFiles: an ignoreFiles glob would silence every rule for the file, and the overlay is real user-facing chrome where a future contrast or side-tab finding should still be heard. Scoped to this one file, so the rule keeps working everywhere else. Written by hand because hook-admin's ignore-value cannot emit the `files` array that detector.ignoreValues supports and existing entries already use. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Let hooks ignore-value scope a rule to files, and stop churning the config Fallout from suppressing the overlay's font-size findings: the narrowest exception detector.ignoreValues supports was unreachable from the path the hook tells the model to use, so the guidance steered to the blunt instrument instead. - hook-admin's ignore-value now takes --file / --files / --file= / --files=, matching `impeccable ignores add-value`, which already had them. Without it the only file-scoped option was ignore-file, which silences every rule for a path permanently, including rules not yet written. - A bare wildcard value is now refused with a message pointing at either --file or ignore-rule. Previously `ignore-value <rule> "*"` quietly wrote a project-wide suppression from a single file's finding. - ignore-value keyed entries on rule+value only, so a second scope for the same rule overwrote the first instead of coexisting. Key on the file scope too. - An unknown flag folded into the value: `ignore-value overused-font Inter --shard` stored "inter --shard", matched nothing, and reported success. Reject it, as the sibling command does. Config churn: normalizeIgnoreValueEntries runs on every write and emitted keys as rule, value, files, reason, createdAt while the config on disk uses createdAt before reason. Any edit therefore rewrote every untouched entry (35 churned lines for a one-line change). Pin the canonical order in both copies of the normalizer and in ignores.mjs, and add a test that the two copies cannot drift apart. Also point the hook's own footer and reference/hooks.md at the file-scoped form first, and say plainly what ignore-file costs. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Correct the prose-gate docs and write down the no-bump-in-a-PR rule CLAUDE.md said the prose validator "deliberately skips skill/", which is only half true and cost a build failure this week: validateProse skips it, but validateSkillProse then scans skill/**/*.md and fails the build on em dashes plus the phrases with no technical reading. Document both gates, which files each one reads, and the line that actually matters in practice: an em dash in skill/reference/*.md fails the build, one in a skill/scripts/*.mjs comment does not. Each claim was checked against a real `bun run build`. Also record that feature PRs do not bump manifest versions or add changelog entries. It was not written down anywhere: not CLAUDE.md, not AGENTS.md, not the PR template. CLAUDE.md's "Bump when: CLI code changes" reads as an instruction to bump inside the PR that touches cli/, so say plainly that it names which component a change belongs to rather than when to edit the manifest. Put the rule in AGENTS.md too. That is the guide the agents opening PRs here actually read, so a rule about PR hygiene living only in CLAUDE.md would not reach them. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Bring Live progressive delivery and the generator subagent to Claude Code Almost none of this branch's Live work was actually Codex-specific. The publisher, the fences, the source locks and the browser's partial-arrival UI are plain node and DOM with zero provider references, and the progressive E2E already passes on five frameworks driven by a non-Codex agent. The Codex-only part was policy prose and one frontmatter line, so Claude Code shipped the progressive browser UI it could never trigger. Progressive delivery, Codex and Claude Code: - Add a `live-progressive` capability tag and opt codex, agents, and claude-code in. A provider block takes one tag, so naming harnesses would have meant duplicating the recipe per tag; a capability reads better than a provider list anyway. Cursor and everyone else keep the atomic path until their poll loop is known not to stall on the extra publish calls. - Claude Code publishes variant 1 as soon as it validates rather than waiting to write the whole trio in one edit. Nothing about the arrival path needed changing: the publisher writes, framework HMR pushes, and the browser's MutationObserver counts variants. The parent conversation was never in that path, which is why Claude Code's lack of subagent progress streaming does not matter here. Generator subagent: - Drop `providers: codex` from impeccable-live-generator. The build already maps its frontmatter correctly for Claude Code, and impeccable-manual-edit-applier has shipped to .claude/agents/ this way all along. - The reason differs per harness, so the reference says so: Codex delegates to unblock a foreground poll, Claude Code delegates to keep a long session's screenshots and variant CSS out of the main context. Follows the existing manual-edit-applier convention: both agent names, and an inline fallback when native subagents are unavailable. Fixes found on the way: - The two publish commands hardcoded `.agents/skills/impeccable/scripts/` while the other thirteen commands in live.md use {{scripts_path}}. Correct only for the Codex repo-skills bundle; it would have pointed Claude Code at a directory its install never creates. The shipped .codex variant was already internally inconsistent. Now covered by a test. - `--agent=codex` resolved to the canned fake agent, because the flag parsed as `x === 'llm' ? 'llm' : 'fake'`. The private evals Live runner passes exactly that, so a real-harness run would have scored deterministic stub variants and reported them as Codex output. Unknown values for --agent, --scenario and --delivery now fail loudly. - live-reference tests now compile with each provider's real providerTags instead of hand-written lists, so a providers.js misconfiguration fails in tests rather than shipping. Verified: progressive E2E green on vite8-react-plain against a real Vite server and Chromium; every provider variant's publish and poll paths now agree; Cursor and Gemini still compile to atomic only. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Fix inset-order detection, the unlocked artifact discard, and stray boolean flags Three of the four open review findings. The fourth is declined below. - The inset-stripe scan only matched layers starting with `inset`, but the keyword is order-independent: `box-shadow: 4px 0 0 var(--brand-accent) inset` paints the same stripe and was silently missed. Strip the keyword wherever it sits, but only as a standalone token, so a color like var(--inset-accent) is not mangled into `var(-- -accent)` and quietly reclassified as neutral. The fixture now covers both orders plus that token, and a trailing-inset neutral still passes. - The source-artifact discard deleted the preview without the source lock, unlike every other discard path. Take the lock. Narrower than reported, though: the server journals `discard_requested` as a fenced phase before live-accept runs and the publisher checks it three times, so a publish could never land on a discarded session. What this actually prevents is deleting the artifact under a publisher mid-critical-section, turning a clean stale_generation_epoch into an ENOENT crash. - benchmark-live-providers.mjs still compared `--headed` and `--skip-cleanup-control` against a boolean sentinel, so the `=true` spelling silently did nothing. My gap: I introduced boolFlag and converted benchmark-live.mjs but not this one. skipCleanupControl is now read once rather than twice, so the two call sites cannot drift. Declined: tightening the selector guard that skips `active` / `current` / `selected` tokens. It does cause false negatives on names like `.selected-feature`, but the rule's contract makes selection and focus indicators its one exception, and `.active-tab` / `.current-step` / `.selected-row` are syntactically identical to `.selected-feature`. No regex separates them, so tightening the guard trades missed stripes for false positives on exactly the case the rule exempts. The conservative skip is the intended behavior. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Classify failed accepts as errors, and fix parallel lane race/all misuse Two of the three new findings, plus the bug that chasing them exposed in my own earlier fix. The third is mitigated rather than broken; details below. Failed accepts reported success: live/completion.mjs only classifies a result as `error` when it carries `mode: 'error'`. Everything else unhandled falls through to `agent_done` with an ok ack, which is deliberate for the documented fallback paths (two tests pin it) but wrong for a real failure. So `accept_receipt_conflict` reported success, and reference/live.md's `handled: false` without `mode` bullet told the agent to "read file, find markers, edit" — hand-applying a second accept on top of the one the receipt already recorded. The same hole swallowed `source_locked`, which is mine: the earlier commit made lock contention return clean JSON so the agent could retry, but the classifier turned that failure into agent_done/ok, so the accept was dequeued and silently lost. Mark genuine failures with `mode: 'error'` through one `operationFailure` helper, and give live.md a `mode: "error"` bullet with per-error guidance: retry the same command on `source_locked`, never hand-edit, and on a receipt conflict report what the session actually resolved to. The deliberate fallback and markers-not-found handoffs stay untouched. parallel-compact lane orchestration: `Promise.race` settles on the first *settlement*, so one lane failing fast rejected the whole first-variant step while two lanes were still on their way to succeeding. `Promise.any` now takes the first success and only a total wipeout is fatal, reporting every lane's reason. The tail step's `Promise.all` surfaced a raw lane error non-deterministically; `Promise.allSettled` now reports how many lanes failed and why. Added a `requestImpl` seam so lane orchestration is testable without a provider key. Not a defect: the browser releasing Accept before the source write. That is the intended optimistic design, and it is safe because poll-lanes ranks accept at priority 0 against generate at 2, so a queued accept is always leased before a generate the user queues afterwards, even if the generate arrived first. Its source write lands inside the poll script before the next generate preflights. That invariant is load-bearing and had no tests at all; poll-lanes.mjs now has a suite covering it plus lease and type filtering. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Finish the failed-accept classification my last commit only half did All three new findings are the same root cause, and it is my incomplete fix: operationFailure only covered results built from a *thrown* error. Two paths it missed: - Two catches wrote the failure result as a multi-line literal, so the single-line replace skipped them. The Vue accept catch was still bare, exactly as reported; the Svelte one too, though its failures happened to be caught by completion.mjs's Svelte-only special case. - The accept implementations also *return* `{handled: false, error}` for their own checks (variant missing, template empty, original text ambiguous). Those never throw, so no catch ran and no `mode` was set. Both layers now agree, because each is reachable on its own: - live-accept marks any unhandled preview-path result via markPreviewFailure, keyed on `previewMode` — a clean discriminator, since only the preview branches set it and a plain wrapper never does. This is what the agent reads: reference/live.md routes on `mode`, so without it the agent was told "read file, find markers, edit" for a preview that has no markers in source. - completion.mjs replaces its arbitrary svelte-component special case with the set of preview modes whose variants live outside the user's source. That case existed for precisely this reason; Vue and source-artifact were simply never added, so the identical failure on those paths acknowledged as success. The plain wrapper keeps its manual handoff, which is the one shape with editable markers in source. Both deliberate handoffs (mode: 'fallback' and markers not found) still classify as agent_done, now pinned by a test so the generalization cannot swallow them. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Stop the progressive benchmark agent inventing a second variant on count:1 `Math.max(1, event.count - 1)` floored the tail request at one variant, so a one-variant request fetched a second direction and assembled two. Ask for `count - 1` and return the first variant untouched when there is no tail. Latent rather than live: the only caller hardcodes `count: 3`. The reason it is worth fixing is the caller inconsistency it exposed. tests/live-e2e/agent.mjs gates its split-progressive path on `event.count > 1`; benchmark-live-providers.mjs had no such guard, so it would have run the tail for a one-variant request, and the parallel strategy would have assembled its three fixed lanes regardless of what was asked for. Guard the caller the same way. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Drop the live generator subagent; fix the artifact decoy that broke accept The first real Claude Code Live run failed, and the subagent was not the cause. Root cause: progressive publication stages each revision as `.impeccable/live/artifacts/<id>-r<n>.<source-ext>`, nothing ever deleted them, and findSessionFile's walker skipped only node_modules/.git/dist/build. It searches src, app, pages, ... then `.`; a project whose source is not under one of those (this repo's own site lives in site/pages/) falls through to the `.` walk, where dot-directories sort before letters. So accept found the artifact instead of the real file. Two outcomes, both reproduced: where isGeneratedFile returns true it declines with mode: 'fallback' (what the run hit, after which the agent hand-carbonized several hundred lines across three stylesheets, including unrequested drive-by edits); where it returns false, accept writes the variant into the throwaway artifact and reports handled: true while real source never changes. The E2E suite could not have caught this. Every fixture puts source under `src/`, which is searched before the `.` walk can reach `.impeccable`. Five framework fixtures and three progressive scenarios pass because of fixture layout, not because the path works. I read that as evidence and shouldn't have. - Never search `.impeccable`: it is Impeccable's own state, never project source. - Retire a session's staged artifacts on accept/discard, so they cannot outlive the session and become a decoy for anything else that walks the tree. - Regression tests use a site/pages layout with artifacts present. All three fail against the previous code. Generator subagent removed, on both harnesses: The parent must hand-compress the design system into the handoff, and compression is lossy. Measured on the real run: a 6,826-char handoff carrying exactly one token reference, after the parent had itself read kinpaku-tokens.css. The subagent then spent 3 of its first 9 turns hunting DESIGN.md, gave up, and emitted 0 var(--token) uses and 22 raw oklch literals — violating its own spec's "Never invent raw colors when tokens exist" — including a 1:1 gold-on-gold contrast bug. Isolation is not a benefit here; knowing the design system is the job. Generation stays in the main thread, which already holds the tokens and writes them from the first byte, so carbonize is a move rather than a translation. Copy edits keep their subagent: applying a known set of ops to a named file is self-contained, so an isolated context costs nothing. That is the line. Progressive delivery stays for Codex and Claude Code, main-thread driven. Claude Code keeps the full benefit because its poll is a background task. Codex's poll blocks the foreground, so with no subagent the user sees variant 1 early via HMR but cannot accept it until the trio finishes; that is the cost of the simplification and it is worth naming. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Rip out the dead isolated-preview mode and the private repo's job Comparing this branch's live against main's turned up two whole features that never made sense here. -2,466 lines. 1. The isolated source-artifact preview was never switched on. `scaffoldSourceArtifactSession` is only reachable via live-wrap's `--isolated`, and nothing passes it: not the server's preflight, not live.md, nothing. Proved it end-to-end — the default wrap writes markers straight into real source and creates no previews/ session. So the mode was wired through three modules, carried its own accept/discard branches, browser branches, server metadata resolution, preview-mode classifier entry, and test suites, and none of it could run. Worse, live.md documented it as the active path and told the agent "The true source is only the publisher's hash fence and must remain byte-identical until Accept." That is false: the wrapper lands in source at scaffold time and each revision rewrites it. An agent following that sentence believes source is protected when it isn't, and the leftover artifacts are what made accept resolve the wrong file in the first real run. live.md now describes what actually happens, including that markers are visible in source until Accept or Discard. Removed: source-artifact.mjs, --isolated, the preflight's isolated option, the accept/discard branches, four dead browser branches, the server's previews/ resolution, the classifier entry, and their tests. Kept the previews/ gitignore pattern: an ignore line for a directory that cannot exist is free, and a test pins it. 2. Quality judging belongs to the private evals repo, which says so. runner/live/README.md there is explicit: the public repo owns protocol correctness, framework coverage, timing, source commit, recovery, and a rubric-free evidence bundle; the private repo owns the task corpus, baselines, comparative judges, and release-quality decisions — "Do not add quality rubrics, competitor comparisons, or broad fixture corpora to the public Live benchmark." This branch added exactly those: an LLM judge scoring 1-10 on "off-brand, generic-AI" (live-rendered-quality.mjs, judge-live-rendered.mjs), a cross-provider comparison with a BRAND_CONTRACT rubric (live-provider-benchmark .mjs, benchmark-live-providers.mjs), and a brand-fidelity fixture corpus. All removed, with bench:live:providers and their suite entries. Also removed tests/framework-fixtures/README.md's "External quality-eval fixtures" section: it documented a bench:live workflow using --fixture-dir, --agent=codex, --action and --evidence-bundle, none of which benchmark-live.mjs implements, plus an evidenceCapture block nothing reads. Kept: timing benchmarks (the public repo's half of that boundary), progressive publication, the source lock, poll lanes, and Nuxt/Vue component previews. Coverage note: deleting the isolated suites took the only tests for `source_locked` classification with them, so the plain wrapper path — now the only non-component preview — gets equivalent accept and discard coverage. Both new tests fail if mode:'error' is removed. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Flag inset stripes written with the two-length box-shadow form box-shadow takes <length>{2,4}: only the two offsets are required, so `inset 4px 0 red` is valid and paints the same single-edge stripe as `inset 4px 0 0 red`. The scan demanded a third length, so the short form was silently missed. Blur and spread now default to 0 when omitted, which is exactly the stripe shape the rule looks for. The neutral-color and blur/spread exclusions still hold: `inset 4px 0 #000` and `inset 4px 0 5px var(--brand-accent)` both pass. Fixture covers both orders of the short form plus those two exclusions, and fails against the previous regex. Third false negative found in this rule (after trailing `inset` and literal neutral colors), all from the same cause: the scan was written against one spelling of the syntax rather than the grammar. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Live: polling rework, source locks, preflight scaffolding, Vue previews Carved out of #371, minus progressive publication. Everything here works against real project source the way main's Live already does: the agent writes variants into the file the browser loaded, HMR fires, Accept promotes and carbonizes. Nothing is staged anywhere. Poll lanes. Events now carry an explicit priority: accept/discard/exit ahead of manual_edit_apply/steer/carbonize_cleanup ahead of generate. A long generate can no longer sit in front of the Accept the user just clicked. leaseEvent claims its lease before awaiting, so a slow prepare cannot hand the same event to two pollers. Source locks. A per-file mutex around every accept and discard path, keyed on a digest of the absolute path. Staleness is decided by owner-pid liveness rather than mtime, so a wedged lock clears when its owner dies instead of after an arbitrary timeout, and a slow-but-live accept is never stolen from. Only the owning process can release a lock. Preflight scaffolding. The server runs live-wrap (or live-insert) before the poll returns and hands the result back as event.scaffold. That walk is measured at ~7.6s on a large repo; moving it off the agent's critical path removes a deterministic tool round trip without touching the generated design. Falls back cleanly to the agent running the helper itself. Vue previews. previewMode: "vue-component" for Nuxt/Vue targets, matching the existing Svelte component path: variants compile as real SFCs from a dev-only directory so the route is never rewritten during generation, and Vite mounts them without invalidating page state. Accept is the only route write. Includes a Vue attr tokenizer that normalizes shorthand bindings (@x, :x, #x) to their canonical forms. Accept hardening. Every thrown failure now returns mode: 'error' rather than an ambiguous unhandled result, so a real failure is never classified as a deliberate manual handoff and silently dropped. The marker search skips node_modules/.git/dist/build/.impeccable. Shared CLI arg parsing extracted to scripts/lib/cli-args.mjs. Assisted-by: Claude Code * Drop the progressive benchmark, remove dead wrap scaffolding Review fallout from removing progressive publication. The Live benchmark existed to compare atomic against progressive delivery: compareModelBackedReports measures goToFirstVariantMs improvement of one over the other. With progressive gone it measures nothing against nothing. Worse, benchmark-live.mjs still passed `progressive` to bootFixtureSession, which no longer accepts it, so `--delivery progressive` was silently ignored and would have emitted reports labeled progressive that actually ran atomic. Silent wrong data is worse than a crash. It was built for progressive, so it goes with progressive: benchmark-live.mjs, its lib, its test, and the bench:live script. If an atomic latency baseline is wanted later, that is a smaller thing built on purpose. live-wrap.mjs: sourceOriginalLines was assigned and never read. Both found by review bots on #381 (Copilot). Assisted-by: Claude Code * Drop the Vue preview mode; it never reached Svelte's accept path Cursor found that inlineVueComponentAccept never receives paramValues, while the Svelte equivalent uses them in 23 places: Accept on a tuned Vue variant silently persisted the default and threw the user's tuning away. Chasing that corrected something I had asserted the other way round. I said Vue's raw-CSS-append was inherited from the Svelte path. It is not. svelte-component.mjs calls sanitizeAcceptedSvelteCss before writing, which sanitizes the CSS and bakes tuned params into it. vue-component.mjs had no sanitize step at all — it appended the variant's <style scoped> body into whatever style block came last, so a variant could leak CSS site-wide when the last block was global, and brace CSS landed in a lang="sass" block. Both are the same defect: the Vue mode mirrored Svelte's preview path without its accept-side subsystem (bakeParamValuesInCss, sanitizeAcceptedSvelteCss, appendSanitizedCssRule, rewriteAcceptedSvelteSelector, rewriteParamSelectors — roughly 200 lines of CSS rewriting). Both were introduced here, not inherited. A shipped Vue session could leak styles and discard tuning without saying so. So it comes out. The poll lanes, source locks, preflight scaffolding, and accept hardening do not depend on it and are worth landing now. Vue returns when its accept path reaches parity. The nuxt-vite7 fixture goes back to main's plain-wrapper shape. Assisted-by: Claude Code * Stop the lease redelivery test racing the scheduler CI failed `does not drop polled events until the agent acknowledges them` on a commit whose content was byte-identical to one that passed, which is the signature of a flake rather than a regression. The test leased an event for 50ms, then asserted a second poll saw a timeout because the lease was still held. That gave the whole second HTTP round trip a 50ms real-time budget: cross it and the lease expires, the event is redelivered, and the assertion fails for a scheduling hiccup instead of a bookkeeping bug. Locally it passed 6/6; a loaded runner is where it bites. Hold the lease for 1000ms so a round trip cannot cross it, and wait LEASE_MS + 300 before asserting redelivery, so each half has headroom in the direction it asserts. Verified by injecting a 60ms stall before the second poll: the old test fails with exactly the CI message, the new one passes. Assisted-by: Claude Code * Recover live sessions that reload past the generation done broadcast The preflight scaffold write (new in this PR) triggers a framework full-reload — Astro reloads the page for any .astro edit. When the agent's variant write and its done SSE land while the browser is mid-reload, the resumed page misses both the second HMR reload and the done broadcast: it comes back up on the scaffold-only source and waits in GENERATING at 0/N forever, with the finished variants sitting in source. This is the astro-vite7 CI timeout; the failure artifacts show the full sequence (scaffold at 26.319s, done at 26.515s, the new page's browser_resumed checkpoint at 26.653s, DOM still scaffold-only). Three-part fix: - session-store: agent_done now stamps a monotone generationCompletedAt on the snapshot. Browser checkpoints legitimately regress phase and arrivedVariants (a resumed page reports what it sees), so completion needed a field checkpoints cannot un-set. - live-browser: on every SSE (re)connect, compare the session summary's generationCompletedAt against local progress; when behind while GENERATING, pull the finished variants from source (same settle delay as the done handler's HMR-first fallback). Covers both orderings of resumed-checkpoint vs agent_done. Also, the source-fallback empty- wrapper branch no longer tears the session down mid-generation — a scaffold-only wrapper is a legitimate in-flight state, so stay in GENERATING instead of destroying a session the agent is still filling. - live-server: a browser checkpoint reporting generating/behind for a session whose generation already completed re-broadcasts the stored done (idempotent for every other tab), and connected-payload summaries expose generationCompletedAt for the browser-side check. Coverage: live-server unit tests for redelivery, the no-redelivery guard, and marker durability across checkpoint regression; plus a deterministic live-e2e scenario on astro-vite7 that blocks the reloaded page's SSE stream and mocks its HMR websocket dead until after the agent finishes, forcing the missed-broadcast window every run. All new tests fail against the pre-fix code. The e2e harness additionally gains an IMPECCABLE_E2E_ATOMIC_DELAY_MS lever (widens the scaffold-to-write window) and env-gated console/nav tracing (IMPECCABLE_E2E_CONSOLE=1) used to diagnose this. The hypothesis that preflight opens a wrapper-with-no-variants window came from Copilot's review sketch in the follow-up WIP PR; the killing mechanism differs from that sketch (nothing calls recoverEmptyCycling in the CI trace — the session hangs precisely because no code path runs at all), but the window is real and the guard it suggested is folded into the source-fallback fix. Assisted-by: Claude Code Co-Authored-By: Claude Code <noreply@anthropic.com> * Retry a completion-driven source fallback that reads only the scaffold Greptile flagged a hole in the previous commit's empty-scaffold guard: when a `done` has already been delivered, the source fallback gets exactly one read. If that read returns the preflight-only scaffold (a stale source view, or an agent whose write lands in multiple steps), the guard's silent return left the tab in GENERATING with no further event ever coming — the same stuck state the previous commit fixed, reintroduced through a different door. Callers that know generation finished (the done handler's fallback and the SSE-reconnect self-heal) now pass generationCompleted, and an empty read on that path re-reads the source up to 3 times before surfacing recoverEmptyCycling instead of hanging. Mid-generation callers are unchanged and still wait indefinitely — a real agent can legitimately take minutes between scaffold and write, and tearing that down was the original #385 hazard. The missed-done e2e scenario now also serves a captured scaffold-only copy for the first post-reconnect /source read, forcing the retry path every run. Verified failing against the pre-retry code (tab stranded in GENERATING, test timeout) and passing with it. Assisted-by: Claude Code Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
965 lines
45 KiB
JavaScript
965 lines
45 KiB
JavaScript
/**
|
|
* Static-source regression guards for live-browser.js.
|
|
*
|
|
* `skill/scripts/live-browser.js` is a self-contained
|
|
* IIFE served directly to user pages by live-server.mjs (no bundle step,
|
|
* no module exports). That makes its internal helpers untestable via
|
|
* normal import — but a few behaviors have failed in real-world live
|
|
* sessions in ways that are easy to express as "this exact code shape
|
|
* MUST NOT come back." This file pins those down.
|
|
*
|
|
* Add a guard whenever a bug we fix has a one-line "anti-pattern" cause
|
|
* that's easy to reintroduce on an unrelated edit.
|
|
*/
|
|
|
|
import { describe, it } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const LIVE_BROWSER = path.resolve(
|
|
__dirname,
|
|
'..',
|
|
'skill/scripts/live-browser.js',
|
|
);
|
|
const SOURCE = fs.readFileSync(LIVE_BROWSER, 'utf-8');
|
|
|
|
describe('live-browser.js regression guards', () => {
|
|
it('resolveCanvasBackground does not fall back to `getComputedStyle(...).backgroundColor || ...`', () => {
|
|
// The browser returns the literal string `"rgba(0, 0, 0, 0)"` for an
|
|
// unset body/html background. That string is non-empty and truthy, so a
|
|
// `||` chain short-circuits to transparent-black, which modern-screenshot
|
|
// hands to its WebGL shader as the canvas color and the screenshot
|
|
// overlay flashes solid black during loading on any page that doesn't
|
|
// explicitly set its own background. Forbid the pattern outright; the
|
|
// correct fallback is a literal `'#ffffff'` (the browser's default
|
|
// canvas color).
|
|
const buggy =
|
|
/getComputedStyle\(document\.(?:body|documentElement)\)\.backgroundColor\s*\|\|/;
|
|
assert.ok(
|
|
!buggy.test(SOURCE),
|
|
'live-browser.js must not chain `getComputedStyle(...).backgroundColor || ...` — that returns transparent-black for default-bg pages and renders the screenshot overlay as solid black during loading. Use a literal fallback (`#ffffff`) instead.',
|
|
);
|
|
});
|
|
|
|
it('detectPageTheme honors alpha when reading body / html backgroundColor', () => {
|
|
// Equivalent trap: `rgba(0, 0, 0, 0)` parsed naively as `(0,0,0)` makes
|
|
// a perfectly white default page register as "dark," which flips the
|
|
// chrome to the wrong palette. The fix introduced an alpha guard
|
|
// (function readOpaque) — keep that signature in source.
|
|
assert.match(
|
|
SOURCE,
|
|
/function detectPageTheme\b[\s\S]{0,1500}?function readOpaque\b/,
|
|
'detectPageTheme must keep its readOpaque helper that filters out fully-transparent backgrounds before computing luminance',
|
|
);
|
|
});
|
|
|
|
it('shader bitmap decode failure keeps a visible fallback overlay', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function showShaderBitmapFallback\(canvas, blob\)[\s\S]{0,900}?fallback\.style\.backgroundImage = 'url\("' \+ objectUrl \+ '"\)';[\s\S]{0,300}?shaderState = \{ canvas: fallback,[\s\S]{0,180}?objectUrl \};/,
|
|
'shader fallback should render the captured bitmap via a background-image div and keep its object URL revocable',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/catch \(err\) \{[\s\S]{0,220}?shader bitmap decode failed[\s\S]{0,220}?showShaderBitmapFallback\(canvas, blob\);[\s\S]{0,80}?return;/,
|
|
'createImageBitmap failures should fall back to a visible captured-bitmap overlay',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/new Image\(/,
|
|
'shader fallback should not use an image element fallback',
|
|
);
|
|
});
|
|
|
|
it('uses a framework-component-gated painted-ancestor crop proxy for shader capture', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function findShaderProxyCaptureRoot\(el\) \{[\s\S]{0,500}?let node = el\.parentElement;[\s\S]{0,700}?containsElement && paintsShaderProxySurface\(node\)[\s\S]{0,120}?return null;/,
|
|
'shader proxy should choose the nearest painted ancestor, not the document root',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/async function captureElementFromRenderedAncestor\(ms, el, opts\) \{[\s\S]{0,360}?const captureRoot = findShaderProxyCaptureRoot\(el\);[\s\S]{0,220}?ms\.domToCanvas\(captureRoot, opts\)[\s\S]{0,900}?cctx\.drawImage\(rootCanvas, sx, sy, sw, sh, 0, 0, crop\.width, crop\.height\);/,
|
|
'shader capture should render the minimal painted ancestor and crop the selected element rect',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function shouldUseAncestorCropShaderProxy\(el\) \{[\s\S]{0,260}?window\.__IMPECCABLE_LIVE_ADAPTER__[\s\S]{0,280}?isFrameworkComponentPreviewMode\(currentPreviewMode\) \|\| svelteComponentSession[\s\S]{0,260}?isFrameworkComponentPreviewMode\(wrapper\?\.dataset\?\.impeccablePreview\);/,
|
|
'ancestor crop proxy must be gated to Svelte/Vue component previews',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(shouldUseAncestorCropShaderProxy\(el\)\) \{[\s\S]{0,240}?return await hideCaptureChromeForShaderProxy\(\(\) => captureElementFromRenderedAncestor\(ms, el, opts\)\);[\s\S]{0,280}?Svelte ancestor crop capture failed, falling back to element capture/,
|
|
'Svelte ancestor crop must run before the legacy capture path and hide live chrome while doing so',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const paper = dominantRgb01\(cctx, crop\.width, crop\.height\) \|\| averageRgb01\(cctx, crop\.width, crop\.height\);/,
|
|
'shader paper should come from the cropped pixels so framework/backdrop composition is preserved',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const radius = getComputedStyle\(el\)\.borderRadius;[\s\S]{0,420}?borderRadius: radius,[\s\S]{0,80}?overflow: 'hidden'/,
|
|
'the shader canvas should clip to the selected element radius when using a rectangular ancestor crop',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/isSemiTransparentOwnBackground|findCompositedBackdropAncestor|compositeRgbOver|cssColorToRgba01/,
|
|
'the shader fix should not depend on semi-transparent CSS special cases',
|
|
);
|
|
});
|
|
|
|
it('locks every global bar mode toggle while manual Apply is in flight', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/const controlsLocked = pendingApplyInFlight === true;[\s\S]{0,120}?\[pickToggle, insertToggle, detectToggle, designToggle\]\.forEach/,
|
|
'pending manual Apply must visually disable Pick, Insert, Detect, and Design together',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function toggleInsert\(\) \{[\s\S]{0,120}?if \(pendingApplyInFlight\) \{ showManualApplyBusyToast\(\); return; \}/,
|
|
'Insert must have the same in-flight Apply guard as the other mode toggles',
|
|
);
|
|
});
|
|
|
|
it('exits inline editing directly on outside click', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function cancelEditingToPicking\(\) \{[\s\S]{0,600}?setLiveState\('PICKING'\);/,
|
|
'outside-click editing cancel should avoid rebuilding configure UI before hiding it',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/state === 'EDITING'[\s\S]{0,180}?cancelEditingToPicking\(\);[\s\S]{0,40}?return;/,
|
|
'outside-click handler should leave EDITING directly',
|
|
);
|
|
});
|
|
|
|
it('restores unsaved inline edit drafts before hideBar tears editing down', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function hideBar\(instant\) \{[\s\S]{0,720}?if \(state === 'EDITING'\) restoreInlineEditDrafts\(\);[\s\S]{0,80}?disableInlineEdit\(\);/,
|
|
'hideBar should not leave unsaved contenteditable drafts in the DOM when an external event hides the bar',
|
|
);
|
|
});
|
|
|
|
it('discards variants without hiding the original or animating stale chrome', () => {
|
|
assert.match(SOURCE, /function showOriginalDuringDiscard\(sessionId\)[\s\S]{0,900}?data-impeccable-variant="original"/);
|
|
assert.match(SOURCE, /function handleDiscard\(\)[\s\S]{0,420}?cleanup\(\{ restoreOriginal: true, instantChrome: true \}\)/);
|
|
assert.match(SOURCE, /if \(instant\) barEl\.style\.display = 'none'/);
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(restoreOriginal\) showOriginalDuringDiscard\(cleanupSessionId\);\s*else wrapper\.style\.display = 'none';/,
|
|
'only non-discard cleanup may blank the wrapper while waiting for HMR',
|
|
);
|
|
});
|
|
|
|
it('stores live state off the document root and preserves the selected anchor top', () => {
|
|
assert.match(SOURCE, /window\.__IMPECCABLE_LIVE_STATE__ = next/);
|
|
assert.doesNotMatch(SOURCE, /document\.documentElement\.dataset\.impeccableLiveState/);
|
|
assert.match(SOURCE, /pickedAnchorViewportTop: Number\.isFinite\(pickedAnchorViewportTop\)/);
|
|
assert.match(SOURCE, /scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite\(initialAnchorTop\)/);
|
|
assert.match(SOURCE, /const anchorDelta = anchorTop - scrollLockAnchorTop/);
|
|
});
|
|
|
|
it('does not autofocus the steering chat while inline editing', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function shouldFocusSteerChat\(\) \{\s*return state !== 'CONFIGURING'\s*&& state !== 'EDITING'\s*&& !steerLocked;\s*\}/,
|
|
'edit-mode contenteditable focus must not be stolen by the global steering chat focus recovery',
|
|
);
|
|
});
|
|
|
|
it('keeps the Steer pill from clipping its label or the global bar exit control', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/const PAGE_CHAT_COLLAPSED_W = '104px';/,
|
|
'collapsed Steer pill should reserve enough room for icon, "Steer", and voice button',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function pageChatExpandedWidth\(\)[\s\S]{0,520}?window\.innerWidth - 16 - nonChatWidth[\s\S]{0,220}?Math\.max\(pageChatCollapsedWidthPx\(\), Math\.min\(PAGE_CHAT_EXPANDED_MAX_W, available\)\)/,
|
|
'expanded Steer width should reserve viewport room for the rest of the global bar',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/syncGlobalBarExpandedLabels\(false\);[\s\S]{0,80}?pageChatEl\.style\.width = pageChatExpandedWidth\(\);/,
|
|
'opening Steer should collapse inactive mode labels before measuring input width',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/maxWidth: 'calc\(100vw - 16px\)'[\s\S]{0,80}?boxSizing: 'border-box'/,
|
|
'global bar should be constrained to the viewport instead of clipping the exit control offscreen',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/globalBarEl = el\('div', \{[\s\S]{0,360}?width: 'max-content'/,
|
|
'fixed-position global bar must use max-content sizing before maxWidth clamps it, or narrow panes clip the exit button',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const inner = el\('div', \{[\s\S]{0,220}?flex: '0 0 auto'/,
|
|
'global bar inner controls must not flex-shrink and crop hover labels',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function makeIconBtn[\s\S]{0,360}?flex: '0 0 auto'[\s\S]{0,80}?minWidth: '30px'/,
|
|
'global bar icon buttons must keep stable hitboxes when Steer expands',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/applyGlobalBarLabelState\(expandInactive, pageChatExpanded\)/,
|
|
'expanded Steer should force labels closed without shrinking the icons',
|
|
);
|
|
});
|
|
|
|
it('does not autofocus the steering chat while a page editable is focused', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function isPageEditableElement\(el\) \{[\s\S]{0,160}?own\(el\)[\s\S]{0,160}?\^\(INPUT\|TEXTAREA\|SELECT\)\$[\s\S]{0,80}?el\.isContentEditable/,
|
|
'page-owned inputs, textareas, selects, and contenteditables must be recognized before steer focus recovery runs',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function isPageEditableActive\(\) \{[\s\S]{0,120}?activeElementDeep\(\)[\s\S]{0,120}?isPageEditableElement\(active\) && !isInlineEditActive\(active\)/,
|
|
'auto-focus recovery must check the deep active element instead of only host text selection',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function shouldSteerAutoFocus\(\) \{[\s\S]{0,160}?&& !isPageEditableActive\(\)/,
|
|
'steer chat auto-focus must back off while the page owns an editable caret',
|
|
);
|
|
});
|
|
|
|
it('pins edit badge button metrics instead of inheriting host button chrome', () => {
|
|
const start = SOURCE.indexOf('const calloutStyle = (color, borderColor) => ({');
|
|
const end = SOURCE.indexOf(' });', start);
|
|
const calloutStyle = SOURCE.slice(start, end);
|
|
assert.match(
|
|
calloutStyle,
|
|
/fontSize: '10px'/,
|
|
'edit badge controls should not scale from host rem settings',
|
|
);
|
|
assert.match(
|
|
calloutStyle,
|
|
/lineHeight: '16px'/,
|
|
'edit badge controls need the same 22px button height on pages with or without button resets',
|
|
);
|
|
assert.match(
|
|
calloutStyle,
|
|
/boxSizing: 'border-box'/,
|
|
'edit badge controls should include padding and border in their rendered dimensions',
|
|
);
|
|
assert.doesNotMatch(
|
|
calloutStyle,
|
|
/fontSize: '0\.625rem'/,
|
|
'edit badge controls should not depend on the host root font-size',
|
|
);
|
|
});
|
|
|
|
it('does not shadow the global live state when storing Apply state', () => {
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/function readStoredManualApplyState\(\)[\s\S]{0,240}?const state = JSON\.parse\(raw\);/,
|
|
'stored manual Apply JSON should not shadow the outer UI state variable',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/function writeManualApplyState\(state\)/,
|
|
'stored manual Apply object should not shadow the outer UI state variable',
|
|
);
|
|
});
|
|
|
|
it('handleServerLost preserves the current recoverable phase', () => {
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/state\s*=\s*currentSessionId\s*\?\s*['"]GENERATING['"]\s*:\s*['"]IDLE['"]/,
|
|
'event=live_browser.server_lost_phase actor=browser operation=sse_disconnect risk=cycling_or_saving_session_saved_as_generating expected=preserve current phase actual=forced generating',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function handleServerLost\(\)[\s\S]{0,300}?const recoveryState = currentSessionId \? state : 'IDLE';[\s\S]{0,1200}?setLiveState\(recoveryState\);[\s\S]{0,120}?if \(currentSessionId\) saveSession\(\);/,
|
|
'server-lost cleanup should keep the current session phase in local recovery state instead of rewriting it to GENERATING',
|
|
);
|
|
});
|
|
|
|
it('source reinjection preserves the visible variant after cycling', () => {
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/Replace the live element[\s\S]{0,900}?visibleVariant\s*=\s*1;\s*showVariantInDOM\(sessionId,\s*1\);/,
|
|
'event=live_browser.visible_variant_reset actor=browser operation=hmr_source_reinject risk=late_hmr_accepts_variant_1_after_user_cycles expected=preserve visible variant actual=reset_to_first',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/previousVisibleVariant[\s\S]{0,900}?savedVisibleVariant[\s\S]{0,500}?showVariantInDOM\(sessionId, visibleVariant\);/,
|
|
'source reinjection should preserve the in-memory or saved visible variant instead of always showing variant 1',
|
|
);
|
|
});
|
|
|
|
it('suppresses scroll anchoring via a stylesheet rule, not inline html/body style', () => {
|
|
// The scroll lock disables the browser's scroll-anchoring on the scroll
|
|
// root so it can't fight our manual scroll correction. Doing that by
|
|
// mutating `document.documentElement.style` / `document.body.style`
|
|
// inline makes React 19 report a hydration mismatch on the next
|
|
// Fast-Refresh re-render: <html>/<body> are server-rendered by frameworks
|
|
// like Next.js App Router, so a client-only inline `style` the server HTML
|
|
// never emitted trips "a tree hydrated but some attributes ... didn't
|
|
// match." That surfaced as a console.error and failed the
|
|
// nextjs-app-router live-e2e fixture's expectConsoleClean probe. The fix
|
|
// injects a <style> rule with the same computed effect instead.
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/document\.documentElement\.style\.overflowAnchor\s*=/,
|
|
'event=live_browser.scroll_anchor_hydration actor=browser operation=start_scroll_lock risk=react19_hydration_mismatch_on_next_app_router expected=stylesheet_rule actual=inline_style_on_html',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/document\.body\.style\.overflowAnchor\s*=/,
|
|
'scroll lock must not mutate <body> inline overflowAnchor — it desyncs server/client hydration on SSR frameworks',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';/,
|
|
'the anchor-suppression style needs a stable id constant so it can be created and removed by id',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/document\.getElementById\(SCROLL_ANCHOR_LOCK_ID\);[\s\S]{0,400}?createElement\('style'\)[\s\S]{0,400}?overflow-anchor:none[\s\S]{0,400}?\(document\.head \|\| document\.documentElement\)\.appendChild/,
|
|
'the scroll lock must suppress scroll anchoring with an injected <style> rule keyed by SCROLL_ANCHOR_LOCK_ID',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/scrollLockAbort\.signal\.addEventListener\('abort', \(\) => \{\s*document\.getElementById\(SCROLL_ANCHOR_LOCK_ID\)\?\.remove\(\);/,
|
|
'stopping the scroll lock must remove the injected anchor-suppression <style> so it never outlives the session',
|
|
);
|
|
});
|
|
|
|
it('drives variant visibility and --p-* params through a stylesheet, not inline SSR element mutation', () => {
|
|
// Variant divs live in page source, so Next.js App Router server-renders
|
|
// them. Toggling hidden/style.display/--p-* on those nodes client-side
|
|
// makes React 19 report a hydration mismatch on the next Fast-Refresh
|
|
// re-render — the same failure mode as scroll-anchor (#276) and pick-cursor
|
|
// (#286). Visibility and range/toggle custom properties must go through an
|
|
// injected <style> rule instead.
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/function setVariantShown\(/,
|
|
'event=live_browser.variant_visibility_hydration actor=browser operation=show_variant_in_dom risk=react19_hydration_mismatch_on_next_app_router expected=stylesheet_rule actual=hidden_and_inline_display_on_variant_div',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(svelteComponentSession\?\.sessionId === currentSessionId\)[\s\S]{0,280}?variantEl\.style\.setProperty\('--p-'/,
|
|
'client-mounted Svelte component variants drive --p-* inline (no SSR div, no hydration), unlike server-rendered variant divs',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function applyParamValue\([\s\S]{0,1200}?svelteComponentSession\?\.sessionId === currentSessionId[\s\S]{0,400}?return;[\s\S]{0,400}?updateVariantStateStylesheet\(currentSessionId, visibleVariant\)/,
|
|
'applyParamValue must short-circuit the Svelte inline path before the SSR stylesheet path',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';/,
|
|
'the variant-state style needs a stable id constant so it can be created and removed by id',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const VARIANT_HIDE_DECL = 'display: none !important;';/,
|
|
'the hidden-variant rule should be a named constant for readability',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function updateVariantStateStylesheet\(sessionId, num\)[\s\S]{0,500}?createElement\('style'\)[\s\S]{0,500}?VARIANT_HIDE_DECL/,
|
|
'variant cycling must hide non-visible variants with an injected <style> rule keyed by VARIANT_STATE_STYLE_ID',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function removeVariantStateStylesheet\(\)[\s\S]{0,120}?document\.getElementById\(VARIANT_STATE_STYLE_ID\)\?\.remove\(\)/,
|
|
'leaving CYCLING or tearing down live mode must remove the injected variant-state <style>',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/function refreshParamsPanel\(\)[\s\S]{0,220}?if \(state !== 'CYCLING'\)[\s\S]{0,220}?removeVariantStateStylesheet\(\)/,
|
|
'refreshParamsPanel must not strip the variant-state sheet during GENERATING first-reveal',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function refreshParamsPanel\(\)[\s\S]{0,600}?if \(!variantEl \|\| params\.length === 0\)[\s\S]{0,220}?updateVariantStateStylesheet\(currentSessionId, visibleVariant\)/,
|
|
'paramless variant switches must re-sync the variant-state sheet to clear stale --p-* params',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function isVariantShown\(el\)[\s\S]{0,120}?getComputedStyle\(el\)\.display/,
|
|
'visible-variant detection must read computed display, not el.hidden or el.style.display',
|
|
);
|
|
});
|
|
|
|
it('global bar includes expandable page chat affordance', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function initPageChat\(/,
|
|
'live-browser must mount a page-level chat control in the global bar',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/pageChatEl\.id = PREFIX \+ '-page-chat'/,
|
|
'page chat container needs a stable id for future wiring and tests',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function syncPageChatFocus\(reason\)[\s\S]{0,220}?if \(state === 'CONFIGURING'\) focusConfigureInput\(reason\);[\s\S]{0,120}?else if \(shouldSteerAutoFocus\(\)\) focusSteerChat\(reason\);/,
|
|
'focus configure input while configuring; steer auto-focus unless page text is selected',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function steerFocusLog\(reason, extra\)/,
|
|
'steer focus attempts should be logged for debugging before adding retries',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function submitSteerMessage\(\)[\s\S]{0,1200}?type: 'steer'/,
|
|
'steer submit must post a steer event to the live poller',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/case 'steer_done':[\s\S]{0,80}?maybeCompleteSteer\(msg\)/,
|
|
'steer_done SSE must unlock the chat bar',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function toggleSteerVoice\(\)/,
|
|
'steer voice must toggle Web Speech recognition from the mic button',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/webkitSpeechRecognition|SpeechRecognition/,
|
|
'steer voice must use the Web Speech API',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/Voice mode coming soon/,
|
|
'steer voice placeholder toast must not ship once voice is wired',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function isEmbeddedPreviewBrowser\(\)/,
|
|
'steer voice must detect embedded preview browsers (Cursor/Electron)',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/steerVoiceUnavailableMessage\(\)/,
|
|
'steer voice must explain when preview browsers cannot reach speech services',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/Handing off|pageChatHint\.textContent = 'Working'/,
|
|
'steer processing state should use dots-only animation, not truncated text',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function syncAgentPollingUi\(/,
|
|
'global bar brand must reflect agent poll connectivity',
|
|
);
|
|
// The indicator goes quiet both when nobody is polling and when the agent
|
|
// holds leased work. Under one-shot foreground polling the second case is
|
|
// every normal generation, so a single "run live-poll.mjs to connect" tip
|
|
// told users to fix a healthy session.
|
|
assert.match(
|
|
SOURCE,
|
|
/function agentHasWorkInFlight\(\)\s*\{\s*return state === 'GENERATING' \|\| state === 'SAVING';/,
|
|
'agent poll copy must distinguish a busy agent from an absent one',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/agentHasWorkInFlight\(\) \? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP/,
|
|
'a busy agent must not be described as disconnected',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/tip\.textContent = agentStatusText\(\)/,
|
|
'tooltip copy must be derived at display time, not read from a cache the 5s status poll last wrote',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/case 'agent_polling':/,
|
|
'browser must listen for agent_polling SSE updates',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function showAgentPollTooltip\(/,
|
|
'disconnected agent state must use an instant custom tooltip on brand hover',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function scheduleSteerFocusRecover\(reason\)/,
|
|
'steer focus must reschedule after page clicks once selection/pause gates clear',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/steer-blur-recover/,
|
|
'steer blur should recover focus for type-to-steer when not selecting page text',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function syncPageChatFocusRing\(\)[\s\S]{0,900}?typingReady[\s\S]{0,500}?pageChatInput\.style\.opacity = '1'/,
|
|
'collapsed steer focus must reveal the real input and caret instead of a patina truncated label',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/armPageChatForTyping\([\s\S]{0,120}?expand: true/,
|
|
'steer pill pointerdown must expand before click so focus never flashes a dead collapsed state',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function syncPageChatChrome\(\)[\s\S]{0,400}?pageChatEl\.style\.borderColor = 'transparent'/,
|
|
'steer pill must stay borderless; surface contrast carries the affordance',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/floating bar surface IS the input; modifier pills sit left of the field/,
|
|
'element configure bar must use the bar surface as the input, not a nested field',
|
|
);
|
|
});
|
|
|
|
it('empty configure and steer inputs passthrough arrow nav to handleKeyDown', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function shouldPassthroughElementNav\(deepActive, e\)[\s\S]{0,500}?PREFIX \+ '-input' && state === 'CONFIGURING'/,
|
|
'configure prompt must passthrough empty arrow keys for sibling navigation',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function shouldPassthroughElementNav\(deepActive, e\)[\s\S]{0,700}?PREFIX \+ '-page-chat-input' && state === 'PICKING'/,
|
|
'steer prompt must passthrough empty arrow keys while picking',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/&& !shouldPassthroughElementNav\(deepActive, e\)/,
|
|
'global input guard must honor empty-input arrow passthrough',
|
|
);
|
|
});
|
|
|
|
it('lets page editables keep Enter and arrow keydown events', () => {
|
|
const start = SOURCE.indexOf('function handleKeyDown(e)');
|
|
const pendingApplyStart = SOURCE.indexOf('if (pendingApplyInFlight)', start);
|
|
const guardSource = SOURCE.slice(start, pendingApplyStart);
|
|
assert.match(
|
|
guardSource,
|
|
/isPageEditableElement\(deepActive\) && !isInlineEditActive\(deepActive\)[\s\S]{0,40}?return;/,
|
|
'page-owned editables must short-circuit global key handling before variant navigation or accept handling',
|
|
);
|
|
assert.match(
|
|
guardSource,
|
|
/e\.target\.isContentEditable && isInlineEditActive\(e\.target\)/,
|
|
'impeccable inline edit rows must keep their existing Escape-cancel path',
|
|
);
|
|
});
|
|
|
|
it('configure input Escape tears down annotation overlay before returning to picking', () => {
|
|
// The configure prompt auto-focuses. While focused, the global keydown
|
|
// handler bails on own() inputs, so this local Escape path must hide the
|
|
// annotation overlay. Leaving it active strands a crosshair layer that
|
|
// flashes comment pins on every click after pick mode is turned off.
|
|
assert.match(
|
|
SOURCE,
|
|
/input\.addEventListener\('keydown', \(e\) => \{[\s\S]{0,400}?if \(e\.key === 'Escape'\) \{[\s\S]{0,200}?exitConfigureToPicking\('configure-input-escape'\)/,
|
|
'configure input Escape must call exitConfigureToPicking so annot overlay is removed',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function togglePick\(\)[\s\S]{0,500}?teardownConfigureChrome\(\);/,
|
|
'togglePick off must tear down configure chrome so a stuck annot overlay cannot survive IDLE',
|
|
);
|
|
});
|
|
|
|
it('pick mode preference persists in localStorage', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/const INTERACTION_PREFS_KEY = 'impeccable-live-interaction';[\s\S]{0,3000}?function saveInteractionPrefs\(\)/,
|
|
'pick/insert interaction prefs must persist in localStorage',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function togglePick\(\)[\s\S]{0,200}?saveInteractionPrefs\(\);/,
|
|
'togglePick must persist interaction prefs',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function toggleInsert\(\)[\s\S]{0,800}?saveInteractionPrefs\(\);/,
|
|
'toggleInsert must persist interaction prefs',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(state === 'IDLE' && \(pickActive \|\| insertActive\)\) setLiveState\('PICKING'\);/,
|
|
'SSE connected must arm insert mode when saved preference has insert on',
|
|
);
|
|
});
|
|
|
|
it('detect mode shows an empty result toast once per requested scan', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/const DETECT_EMPTY_MESSAGE = 'No detector issues found\.';/,
|
|
'live detector zero result copy should live in one named constant',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function requestDetectScan\(\)[\s\S]{0,240}?const scanId = String\(\+\+detectScanSeq\);[\s\S]{0,80}?activeDetectScanId = scanId;[\s\S]{0,160}?config: \{ scanId \}/,
|
|
'Detect scans must send a fresh scan id to the detector',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(!detectActive\) return;[\s\S]{0,80}?if \(activeDetectScanId && e\.data\.scanId !== activeDetectScanId\) return;/,
|
|
'live detector results must ignore inactive and stale scan ids',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(detectActive && pendingDetectScanId && detectCount === 0\) \{[\s\S]{0,80}?showToast\(DETECT_EMPTY_MESSAGE, 3200\);[\s\S]{0,120}?pendingDetectScanId = null;/,
|
|
'a matching zero result scan must use the existing toast UI and clear the pending scan id',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/window\.postMessage\(\{ source: 'impeccable-command', action: 'remove' \}, '\*'\);[\s\S]{0,80}?activeDetectScanId = null;[\s\S]{0,80}?pendingDetectScanId = null;/,
|
|
'turning Detect off must clear scan ids',
|
|
);
|
|
});
|
|
|
|
it('toast enter and dismiss timers only touch the current toast element', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function showToast\(message, duration\)[\s\S]{0,1200}?const currentToast = el\('div'/,
|
|
'showToast must capture the created toast in a local so delayed callbacks cannot dereference or remove a stale global toastEl',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/requestAnimationFrame\(\(\) => \{[\s\S]{0,80}?if \(toastEl !== currentToast\) return;[\s\S]{0,120}?currentToast\.style\.opacity = '1';/,
|
|
'toast enter rAF must no-op when dismissToast or a newer toast replaced toastEl before the frame fires',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/setTimeout\(\(\) => \{[\s\S]{0,80}?if \(toastEl !== currentToast\) return;[\s\S]{0,120}?currentToast\.style\.opacity = '0';/,
|
|
'toast auto-dismiss timer must not animate a newer toast created after this timer was scheduled',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/setTimeout\(\(\) => \{[\s\S]{0,80}?if \(toastEl !== currentToast\) return;[\s\S]{0,80}?currentToast\.remove\(\);[\s\S]{0,80}?toastEl = null;/,
|
|
'toast removal timer must only remove and clear the same toast it scheduled',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/requestAnimationFrame\(\(\) => \{\s*toastEl\.style/,
|
|
'toast enter rAF must not read toastEl.style directly after dismissToast can null it',
|
|
);
|
|
});
|
|
|
|
it('insert mode UI and generate payload guards', () => {
|
|
assert.match(SOURCE, /function toggleInsert\(\)/, 'global bar must expose insert toggle');
|
|
assert.match(SOURCE, /PREFIX \+ '-insert-toggle'/, 'insert toggle needs stable id');
|
|
assert.match(SOURCE, /function buildInsertConfigureRow\(\)/, 'insert configure bar required');
|
|
assert.match(SOURCE, /function handleInsertCreate\(\)/, 'insert create handler required');
|
|
assert.match(SOURCE, /mode: 'insert'/, 'insert generate must set mode insert');
|
|
assert.match(SOURCE, /function syncInsertCreateButton\(btn, input\)/, 'Create button must reflect prompt/annotation gate');
|
|
assert.match(
|
|
SOURCE,
|
|
/syncInsertCreateButton\(create, input\)/,
|
|
'Create gate must sync before the row is attached to the document',
|
|
);
|
|
assert.match(SOURCE, /function showInsertCreateTooltip\(/, 'Create disabled state uses a custom hover tooltip');
|
|
assert.match(
|
|
SOURCE,
|
|
/function buildCyclingRow\(\)[\s\S]*?background: C\.brand, color: C\.ink/,
|
|
'Accept button uses lacquer-deep text on kinpaku gold',
|
|
);
|
|
assert.match(SOURCE, /insertCreateDisabledReason/, 'disabled Create hover must explain why');
|
|
assert.match(SOURCE, /data-impeccable-insert-placeholder/, 'placeholder element must be marked');
|
|
assert.match(
|
|
SOURCE,
|
|
/showHighlight\(el\)[\s\S]{0,120}?data-impeccable-insert-placeholder/,
|
|
'pick highlight must not stack on insert placeholder',
|
|
);
|
|
assert.match(SOURCE, /border: '2px dotted ' \+ BP\.accent/, 'placeholder border matches insert line (dotted)');
|
|
assert.match(
|
|
SOURCE,
|
|
/function syncPageInteractionCursor\(\)[\s\S]{0,420}?cursorForInsertAxis/,
|
|
'insert picking cursor follows row/column axis',
|
|
);
|
|
// The pick / insert cursor must be driven by an injected <style>, never by a
|
|
// class or inline style on <html>. <html>/<body> are server-rendered by
|
|
// frameworks like Next.js App Router, so a client-only attribute the server
|
|
// HTML never emitted trips React 19's "a tree hydrated but some attributes
|
|
// ... didn't match" on the next Fast-Refresh re-render — surfacing as a
|
|
// console.error that fails the nextjs-app-router live-e2e expectConsoleClean
|
|
// probe. Same fix shape as the scroll-anchor lock above.
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/document\.documentElement\.classList\.(?:add|remove|toggle)\(/,
|
|
'event=live_browser.pick_cursor_hydration actor=browser operation=sync_page_interaction_cursor risk=react19_hydration_mismatch_on_next_app_router expected=stylesheet_rule actual=class_on_html',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const PICK_CURSOR_STYLE_ID = PREFIX \+ '-pick-cursor-style';/,
|
|
'the pick-cursor style needs a stable id constant so it can be created and removed by id',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function setPageInteractionCursor\(cursor\)[\s\S]{0,700}?cursor: ' \+ cursor \+ ' !important/,
|
|
'pick / insert cursor is applied through the injected <style> textContent, keyed by PICK_CURSOR_STYLE_ID',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/cursor = 'crosshair'/,
|
|
'pick mode uses a crosshair cursor that wins over page pointer styles',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/document\.getElementById\(PICK_CURSOR_STYLE_ID\)\?\.remove\(\)/,
|
|
'exiting live mode removes the injected pick-cursor <style> so it never outlives the session',
|
|
);
|
|
assert.match(SOURCE, /function hitSiblingInsertGap\(/, 'insert mode detects gaps between siblings');
|
|
assert.match(SOURCE, /function resolveInsertHover\(/, 'insert hover resolves axis-aware boundaries');
|
|
assert.match(SOURCE, /data-impeccable-placeholder-resize/, 'placeholder edge handles on annotation overlay');
|
|
assert.match(SOURCE, /resizeEdge && configureKind === 'insert'/, 'resize takes priority over draw');
|
|
assert.match(SOURCE, /cursorForPlaceholderEdge\(spec\.edge\)/, 'edge handles use resize cursors');
|
|
assert.match(
|
|
SOURCE,
|
|
/create\.id = PREFIX \+ '-insert-create'/,
|
|
'Create button id must be set on the element, not passed to el() styles',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/buildInsertConfigureRow[\s\S]{0,1200}?toggleActionPicker/,
|
|
'insert configure bar must not include action picker',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/buildInsertConfigureRow[\s\S]*?buildConfigureCountControl\(/,
|
|
'insert count toggle uses the same inline bar control as configure mode',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/buildInsertConfigureRow[\s\S]*?buildConfigureSubmitButton\(/,
|
|
'insert Create button must match input height',
|
|
);
|
|
assert.match(SOURCE, /function resolveBarAnchor\(\)/, 'bar positions from a connected anchor');
|
|
assert.match(SOURCE, /function finalizeInsertSession\(\)/, 'insert placeholder outlives capture');
|
|
assert.match(SOURCE, /function placeholderSizing\(/, 'insert placeholder picks implicit vs explicit width');
|
|
assert.match(SOURCE, /applyPlaceholderSizingStyles\(placeholder, sizing\)/, 'placeholder width styles applied by kind');
|
|
assert.match(
|
|
SOURCE,
|
|
/function createInsertPlaceholder[\s\S]*?applyPlaceholderSizingStyles\(placeholder, sizing\)/,
|
|
'createInsertPlaceholder must not always set parent pixel width',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/sendEvent\(screenshotPath[\s\S]{0,200}?removeInsertPlaceholder/,
|
|
'capture must not remove insert placeholder before variants land',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function updateVariantStateStylesheet\(sessionId, num\)[\s\S]{0,900}?VARIANT_HIDE_DECL/,
|
|
'variant cycling must hide non-visible variants via injected stylesheet, not hidden/style.display on SSR divs',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/count > 0 \? pickVariantContent\(wrapper, visibleVariant \|\| 1\) : null/,
|
|
'insert HMR re-anchor must not drop placeholder until variants exist',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function ensureInsertPlaceholder\(\)/,
|
|
'insert generating must recreate placeholder after scaffold HMR',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/insertPlaceholder: insertPlaceholderSnapshot/,
|
|
'insert placeholder snapshot must persist across HMR resume',
|
|
);
|
|
});
|
|
|
|
it('handleAccept reads the visible DOM variant before sending accept', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function readVisibleVariantFromDOM\(sessionId\)[\s\S]{0,900}?isVariantShown\(variant\)[\s\S]{0,500}?return idx;/,
|
|
'live-browser should be able to derive the accepted variant from the currently visible DOM node',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function handleAccept\(\)[\s\S]{0,360}?const domVisibleVariant = readVisibleVariantFromDOM\(currentSessionId\);[\s\S]{0,120}?if \(domVisibleVariant > 0\) visibleVariant = domVisibleVariant;[\s\S]{0,160}?variantId: String\(visibleVariant\)/,
|
|
'event=live_browser.accept_stale_visible_variant actor=browser operation=accept_after_hmr risk=accept_sends_variant_1_after_user_cycles_to_2 expected=read_dom_visible_variant actual=stale_state_variable',
|
|
);
|
|
});
|
|
|
|
it('configure row groups selection and input on the left, trailing controls before submit', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function configureModifierPillStyle\(extra = \{\}\)[\s\S]{0,480}?background: 'transparent'[\s\S]{0,120}?color: P\.textDim/,
|
|
'configure modifier chips use muted global-bar idle chrome, not active gold',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const CONFIGURE_ROW_TRACK_H = '18px'/,
|
|
'configure row shares one text track height across pills and input',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function configureInputFieldStyle\(extra = \{\}\)[\s\S]{0,320}?height: CONFIGURE_ROW_TRACK_H/,
|
|
'configure input uses the same track height as modifier pills',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const CONFIGURE_PILL_PAD_Y = '3px'/,
|
|
'modifier pills share 3px vertical padding',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function configureInputShellStyle\(\)[\s\S]{0,200}?alignItems: 'center'[\s\S]{0,120}?padding: '0 6px 0 ' \+ CONFIGURE_BAR_INSET/,
|
|
'configure shell vertically centers the row; inset matches centered pill margin',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/inputShell\.appendChild\(buildSelectionPill[\s\S]{0,120}?inputShell\.appendChild\(input\)/,
|
|
'selection pill and prompt input share the left side of the bar',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/buildConfigureTrailingCluster\(\[action, count\], voiceBtn, go\)/,
|
|
'freeform and variant count sit just left of voice and submit',
|
|
);
|
|
});
|
|
|
|
it('configure bar keeps selection pill, inline controls, outline, and instant tooltips', () => {
|
|
assert.match(SOURCE, /function buildSelectionPill\(/, 'selected element tag lives in the configure bar');
|
|
assert.match(SOURCE, /CONFIGURE_SELECTION_PILL_PAD = '1px 4px'/, 'selection pill uses 1px 4px padding');
|
|
assert.match(
|
|
SOURCE,
|
|
/function configureSelectionPillStyle\(extra = \{\}\)[\s\S]{0,400}?color: P\.patina/,
|
|
'selection pill label uses patina text color',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/function configureSelectionPillStyle\(extra = \{\}\)[\s\S]{0,400}?minHeight:/,
|
|
'selection pill must not impose a min-height',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/gridArea: '1 \/ 1'/,
|
|
'selection pill swaps tag and clear faces without resizing the bar',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/function shouldShowHighlightTagTooltip\(\)[\s\S]{0,160}?state !== 'CONFIGURING'/,
|
|
'configure mode keeps the outline but drops the floating tag tooltip',
|
|
);
|
|
assert.match(SOURCE, /function buildConfigureActionControl\(/, 'action dropdown is an inline bar control, not a pill');
|
|
assert.match(SOURCE, /function buildConfigureCountControl\(/, 'variant count is an inline bar control, not a pill');
|
|
assert.match(
|
|
SOURCE,
|
|
/const hiTarget = resolveBarAnchor\(\);[\s\S]{0,200}?showHighlight\(hiTarget\);/,
|
|
'scroll tracking keeps the element outline visible while configuring',
|
|
);
|
|
assert.match(SOURCE, /function showConfigureBarTooltip\(/, 'configure controls use instant custom tooltips');
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/count\.title = controlsLocked \? 'Apply is still running' : 'Variants: click to change'/,
|
|
'variant count must not rely on native title tooltips',
|
|
);
|
|
});
|
|
|
|
it('variant count pill cycles through x1', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function cycleSelectedCount\(\)[\s\S]{0,200}?selectedCount = VARIANT_COUNT_MIN/,
|
|
'variant count must wrap back to x1 after the max',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/selectedCount >= 4 \? 2/,
|
|
'variant count must not skip x1 by wrapping 4 back to 2',
|
|
);
|
|
});
|
|
|
|
it('makes every arrived progressive variant immediately actionable', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/if \(arrivedVariants > 0\) \{[\s\S]{0,180}?setLiveState\('CYCLING'\)/,
|
|
'the first arrived variant should leave the generating-only state',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/arrivedVariants < expectedVariants\) \{[\s\S]{0,180}?accept\.style\.pointerEvents = 'none'/,
|
|
'Accept must not wait for variants the user did not choose',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/arrivedVariants < expectedVariants\) \{[\s\S]{0,180}?discard\.style\.pointerEvents = 'none'/,
|
|
'Discard must cancel remaining work immediately',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const resumedState = arrivedVariants > 0 \? 'CYCLING' : 'GENERATING'/,
|
|
'reload recovery should preserve a partially delivered review state',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/arrivedVariants >= expectedVariants && expectedVariants > 0[\s\S]{0,100}?\? 'variants_ready'[\s\S]{0,60}?: 'variants_progress'/,
|
|
'checkpoint timing must distinguish partial review from complete delivery by counts',
|
|
);
|
|
});
|
|
|
|
it('keeps deferred Tune controls visible and refreshes params-only publications', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/const paramsPending = !hasParams && \(parameterGenerationState === 'pending' \|\| parameterGenerationState === 'loading'\)/,
|
|
'the cycling bar must expose Tune while parameter generation is outstanding',
|
|
);
|
|
assert.match(SOURCE, /tune\.disabled = true/, 'pending Tune must be visibly loading but non-interactive');
|
|
assert.match(SOURCE, /Tune controls are ready\./, 'parameter arrival needs a clear ready indication');
|
|
assert.match(
|
|
SOURCE,
|
|
/msg\.publicationKind !== 'params' && arrivedVariants >= targetArrived/,
|
|
'a params-only publication must refresh even though the variant count is unchanged',
|
|
);
|
|
assert.match(SOURCE, /revisionDomain: 'browser'/, 'browser checkpoints must use their own revision domain');
|
|
});
|
|
|
|
it('promotes an early-accepted Svelte preview before releasing the picker', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function scheduleAcceptCleanup\(accepted\) \{[\s\S]{0,420}?if \(accepted\?\.isSvelteComponent\) \{[\s\S]{0,120}?commitAcceptedSvelteComponentToDom\(accepted\.id\);[\s\S]{0,120}?cleanupAcceptedSession\(\);/,
|
|
'Svelte early accept must tear down its adapter mount before the next picking session starts',
|
|
);
|
|
});
|
|
|
|
it('variant injection resolves the picked anchor before entering recovery', () => {
|
|
assert.match(
|
|
SOURCE,
|
|
/function resolveLiveInjectionAnchor\(originalMarkup\)/,
|
|
'variant source fallback must try the live picked element before giving up on anchor resolution',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/pickedAnchor: pickedAnchorSnapshot/,
|
|
'picked anchor snapshot must persist in session storage for resume and reinjection',
|
|
);
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/showToast\('Variants ready\. Reveal the selected element to resume\.'/,
|
|
'recovery chrome already shows this message in the generating bar; a duplicate toast stacks two bars',
|
|
);
|
|
});
|
|
|
|
it('editing focus timeout does not read a stale inline edit row', () => {
|
|
assert.doesNotMatch(
|
|
SOURCE,
|
|
/setTimeout\(\(\) => \{\s*const el = inlineEditRows\[0\]\.el;/,
|
|
'event=live_browser.stale_edit_focus actor=browser operation=edit_mode_focus_timeout risk=post_apply_or_accept_pageerror expected=capture editable element before timeout and guard state actual=reads inlineEditRows[0].el after rows can be cleared',
|
|
);
|
|
assert.match(
|
|
SOURCE,
|
|
/const firstEditable = inlineEditRows\[0\] && inlineEditRows\[0\]\.el;[\s\S]{0,120}?setTimeout\(\(\) => \{[\s\S]{0,120}?if \(!el \|\| !el\.isConnected \|\| state !== 'EDITING'\) return;/,
|
|
'edit-mode delayed focus should capture the element before scheduling and no-op if editing ended before the timeout fires',
|
|
);
|
|
});
|
|
});
|