mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 22:26:38 +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>
1148 lines
43 KiB
JavaScript
1148 lines
43 KiB
JavaScript
/**
|
||
* Playwright helpers that drive the live-mode bar UI exactly the way a user
|
||
* would: pick an element, configure, Go, cycle, accept.
|
||
*
|
||
* Selector strategy: live-browser.js uses deterministic ids (`impeccable-live-*`)
|
||
* for the global bar, per-element bar, action picker, and params panel. Buttons
|
||
* inside the per-element bar are matched by visible text or unicode glyph
|
||
* (`← / →`, `✓ Accept`, `✕`), or by aria-label for icon-only buttons (the
|
||
* configure submit button). All selectors below come from
|
||
* skill/scripts/live-browser.js — keep this file in sync if
|
||
* the bar's text content changes.
|
||
*/
|
||
|
||
import { readFileSync } from 'node:fs';
|
||
import { join } from 'node:path';
|
||
|
||
const BAR_ID = '#impeccable-live-bar';
|
||
const GLOBAL_BAR_ID = '#impeccable-live-global-bar';
|
||
const PICKER_ID = '#impeccable-live-picker';
|
||
const EDIT_BADGE_ID = '#impeccable-live-edit-badge';
|
||
const PENDING_DOCK_ID = '#impeccable-live-pending-dock';
|
||
// The configure-row submit button is icon-only; its accessible name is the
|
||
// only stable handle (see buildConfigureSubmitButton in live-browser.js).
|
||
const GO_BUTTON_ARIA_LABEL = 'Generate variants';
|
||
const STEER_CHAT_ID = '#impeccable-live-page-chat';
|
||
const STEER_INPUT_ID = '#impeccable-live-page-chat-input';
|
||
const PICK_TOGGLE = '#impeccable-live-pick-toggle';
|
||
// Alias kept so references introduced via origin/main (PICK_TOGGLE_ID)
|
||
// continue to resolve to the same selector as the older PICK_TOGGLE name.
|
||
const PICK_TOGGLE_ID = PICK_TOGGLE;
|
||
const INSERT_TOGGLE = '#impeccable-live-insert-toggle';
|
||
const DETECT_TOGGLE = '#impeccable-live-detect-toggle';
|
||
const DETECT_BADGE = '#impeccable-live-detect-badge';
|
||
const DESIGN_TOGGLE = '#impeccable-live-design-toggle';
|
||
const DESIGN_HOST = '#impeccable-live-design-host';
|
||
const EXIT_BUTTON = '#impeccable-live-exit';
|
||
const INSERT_INPUT_ID = '#impeccable-live-insert-input';
|
||
const INSERT_CREATE_ID = '#impeccable-live-insert-create';
|
||
const ANNOTATION_ID = '#impeccable-live-annot';
|
||
const ANNOTATION_PINS_ID = '#impeccable-live-annot-pins';
|
||
const ANNOTATION_CLEAR_ID = '#impeccable-live-annot-clear';
|
||
|
||
/**
|
||
* Wait for the live handshake to complete:
|
||
* - window.__IMPECCABLE_LIVE_INIT__ set
|
||
* - global bar mounted
|
||
* - SSE connection established (state transitioned to PICKING)
|
||
*
|
||
* Times out generously since some frameworks delay first render.
|
||
*/
|
||
export async function waitForHandshake(page, { timeout = 20_000 } = {}) {
|
||
await page.waitForFunction(
|
||
() => window.__IMPECCABLE_LIVE_INIT__ === true,
|
||
{ timeout },
|
||
);
|
||
await installLiveQueryHelpers(page);
|
||
await page.waitForFunction(
|
||
(sel) => Boolean(window.__impeccableLiveQuery?.(sel)),
|
||
GLOBAL_BAR_ID,
|
||
{ timeout },
|
||
);
|
||
// Wait for the picker mode to be active (live.js flips state PICKING after
|
||
// SSE 'connected' arrives). We can detect it via the global bar's pick
|
||
// toggle being in its ready state. Soft wait — fall through after a beat
|
||
// even if the toggle hasn't visibly shifted.
|
||
await page.waitForTimeout(250);
|
||
}
|
||
|
||
export async function assertBottomBarIdle(page, { timeout = 5_000 } = {}) {
|
||
await installLiveQueryHelpers(page);
|
||
await page.waitForFunction(
|
||
({ ids }) => ids.every((sel) => Boolean(window.__impeccableLiveQuery(sel))),
|
||
{
|
||
ids: [
|
||
GLOBAL_BAR_ID,
|
||
PICK_TOGGLE,
|
||
INSERT_TOGGLE,
|
||
DETECT_TOGGLE,
|
||
DESIGN_TOGGLE,
|
||
STEER_CHAT_ID,
|
||
STEER_INPUT_ID,
|
||
'#impeccable-live-page-chat-voice',
|
||
EXIT_BUTTON,
|
||
],
|
||
},
|
||
{ timeout },
|
||
);
|
||
const snapshot = await page.evaluate(({ pickSel, insertSel, detectSel, designSel }) => {
|
||
const q = window.__impeccableLiveQuery;
|
||
return {
|
||
pick: controlSnapshot(q(pickSel)),
|
||
insert: controlSnapshot(q(insertSel)),
|
||
detect: controlSnapshot(q(detectSel)),
|
||
design: controlSnapshot(q(designSel)),
|
||
};
|
||
|
||
function controlSnapshot(el) {
|
||
return {
|
||
exists: !!el,
|
||
text: (el?.textContent || '').replace(/\s+/g, ' ').trim(),
|
||
ariaLabel: el?.getAttribute('aria-label') || '',
|
||
active: el?.dataset?.active || null,
|
||
disabled: !!el?.disabled,
|
||
};
|
||
}
|
||
}, {
|
||
pickSel: PICK_TOGGLE,
|
||
insertSel: INSERT_TOGGLE,
|
||
detectSel: DETECT_TOGGLE,
|
||
designSel: DESIGN_TOGGLE,
|
||
});
|
||
for (const [name, value] of Object.entries(snapshot)) {
|
||
if (!value.exists) throw new Error(`bottom bar ${name} control is missing`);
|
||
if (value.disabled) throw new Error(`bottom bar ${name} control unexpectedly disabled`);
|
||
}
|
||
}
|
||
|
||
export async function runLiveChromeBottomBarSmoke(page, {
|
||
expectDetectMinCount = 1,
|
||
designTitle = '',
|
||
designRawText = '',
|
||
} = {}) {
|
||
await assertBottomBarIdle(page);
|
||
await runPickInsertToggleSmoke(page);
|
||
await runDetectSmoke(page, { expectMinCount: expectDetectMinCount });
|
||
await runDesignPanelSmoke(page, { title: designTitle, rawText: designRawText });
|
||
}
|
||
|
||
function installLiveQueryHelpersInPage() {
|
||
window.__impeccableLiveQuery = (selector) => {
|
||
const root = window.__IMPECCABLE_LIVE_CHROME_CORE__?.root?.()
|
||
|| window.__IMPECCABLE_LIVE_UI_ROOT__
|
||
|| null;
|
||
return root?.querySelector?.(selector) || document.querySelector(selector);
|
||
};
|
||
window.__impeccableLiveQueryAll = (selector) => {
|
||
const root = window.__IMPECCABLE_LIVE_CHROME_CORE__?.root?.()
|
||
|| window.__IMPECCABLE_LIVE_UI_ROOT__
|
||
|| null;
|
||
const fromRoot = root?.querySelectorAll ? [...root.querySelectorAll(selector)] : [];
|
||
const fromDoc = [...document.querySelectorAll(selector)];
|
||
return [...new Set([...fromRoot, ...fromDoc])];
|
||
};
|
||
}
|
||
|
||
export async function installLiveQueryHelpers(page, { timeout = 5_000 } = {}) {
|
||
await page.addInitScript(installLiveQueryHelpersInPage).catch(() => {});
|
||
await withTimeout(
|
||
page.evaluate(installLiveQueryHelpersInPage),
|
||
timeout,
|
||
'install live query helpers',
|
||
);
|
||
}
|
||
|
||
function withTimeout(promise, timeout, label) {
|
||
let timer;
|
||
const timeoutPromise = new Promise((_, reject) => {
|
||
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeout}ms`)), timeout);
|
||
});
|
||
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timer));
|
||
}
|
||
|
||
async function clickLiveControl(page, selector) {
|
||
await installLiveQueryHelpers(page);
|
||
const clicked = await page.evaluate((sel) => {
|
||
const el = window.__impeccableLiveQuery(sel);
|
||
if (!el || el.disabled) return false;
|
||
el.click();
|
||
return true;
|
||
}, selector);
|
||
if (clicked) return;
|
||
await page.locator(selector).click({ timeout: 5_000 });
|
||
}
|
||
|
||
async function readControlActive(page, selector) {
|
||
await installLiveQueryHelpers(page);
|
||
return page.evaluate((sel) => window.__impeccableLiveQuery(sel)?.dataset.active === 'true', selector);
|
||
}
|
||
|
||
async function ensureLiveControlActive(page, selector, active) {
|
||
if (await readControlActive(page, selector) === active) return;
|
||
await clickLiveControl(page, selector);
|
||
await page.waitForFunction(
|
||
({ sel, expected }) => window.__impeccableLiveQuery(sel)?.dataset.active === (expected ? 'true' : 'false'),
|
||
{ sel: selector, expected: active },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
export async function runPickInsertToggleSmoke(page) {
|
||
await ensureLiveControlActive(page, PICK_TOGGLE, true);
|
||
await page.waitForFunction(
|
||
({ pickSel, insertSel }) =>
|
||
window.__impeccableLiveQuery(pickSel)?.dataset.active === 'true'
|
||
&& window.__impeccableLiveQuery(insertSel)?.dataset.active === 'false',
|
||
{ pickSel: PICK_TOGGLE, insertSel: INSERT_TOGGLE },
|
||
{ timeout: 5_000 },
|
||
);
|
||
|
||
await ensureLiveControlActive(page, INSERT_TOGGLE, true);
|
||
await page.waitForFunction(
|
||
({ pickSel, insertSel }) =>
|
||
window.__impeccableLiveQuery(pickSel)?.dataset.active === 'false'
|
||
&& window.__impeccableLiveQuery(insertSel)?.dataset.active === 'true',
|
||
{ pickSel: PICK_TOGGLE, insertSel: INSERT_TOGGLE },
|
||
{ timeout: 5_000 },
|
||
);
|
||
|
||
await ensureLiveControlActive(page, INSERT_TOGGLE, false);
|
||
await ensureLiveControlActive(page, PICK_TOGGLE, false);
|
||
}
|
||
|
||
export async function runDetectSmoke(page, { expectMinCount = 1 } = {}) {
|
||
await ensureLiveControlActive(page, DETECT_TOGGLE, true);
|
||
await page.waitForFunction(
|
||
({ badgeSel, expectMin }) => {
|
||
const badge = window.__impeccableLiveQuery(badgeSel);
|
||
const count = parseInt(badge?.textContent || '0', 10);
|
||
const overlays = document.querySelectorAll('.impeccable-overlay').length;
|
||
return count >= expectMin && overlays >= expectMin && badge?.style.display !== 'none';
|
||
},
|
||
{ badgeSel: DETECT_BADGE, expectMin: expectMinCount },
|
||
{ timeout: 15_000 },
|
||
);
|
||
|
||
await ensureLiveControlActive(page, PICK_TOGGLE, true);
|
||
await page.waitForFunction(
|
||
() => [...document.querySelectorAll('.impeccable-overlay')]
|
||
.every((overlay) => overlay.style.pointerEvents === 'none'),
|
||
{ timeout: 5_000 },
|
||
);
|
||
await ensureLiveControlActive(page, PICK_TOGGLE, false);
|
||
|
||
await ensureLiveControlActive(page, DETECT_TOGGLE, false);
|
||
await page.waitForFunction(
|
||
({ badgeSel }) => {
|
||
const badge = window.__impeccableLiveQuery(badgeSel);
|
||
return document.querySelectorAll('.impeccable-overlay').length === 0
|
||
&& (!badge || badge.style.display === 'none' || (badge.textContent || '') === '0');
|
||
},
|
||
{ badgeSel: DETECT_BADGE },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
export async function runDesignPanelSmoke(page, { title = '', rawText = '' } = {}) {
|
||
await ensureLiveControlActive(page, DESIGN_TOGGLE, true);
|
||
await page.waitForFunction(
|
||
({ hostSel, titleText }) => {
|
||
const host = window.__impeccableLiveQuery(hostSel);
|
||
const root = host?.shadowRoot;
|
||
const panel = root?.querySelector('.panel');
|
||
const bodyText = root?.querySelector('#panel-body')?.textContent || '';
|
||
return panel?.getAttribute('data-open') === 'true'
|
||
&& bodyText.trim().length > 0
|
||
&& !bodyText.includes('Loading design system')
|
||
&& !bodyText.includes('No DESIGN.md yet')
|
||
&& !bodyText.includes('Failed to load design system')
|
||
&& (!titleText || bodyText.includes(titleText));
|
||
},
|
||
{ hostSel: DESIGN_HOST, titleText: title },
|
||
{ timeout: 15_000 },
|
||
);
|
||
|
||
await page.evaluate((hostSel) => {
|
||
const root = window.__impeccableLiveQuery(hostSel)?.shadowRoot;
|
||
const raw = [...(root?.querySelectorAll('.tab') || [])].find((btn) => /Raw/i.test(btn.textContent || ''));
|
||
raw?.click();
|
||
}, DESIGN_HOST);
|
||
await page.waitForFunction(
|
||
({ hostSel, expected }) => {
|
||
const text = window.__impeccableLiveQuery(hostSel)?.shadowRoot?.textContent || '';
|
||
return !expected || text.includes(expected);
|
||
},
|
||
{ hostSel: DESIGN_HOST, expected: rawText },
|
||
{ timeout: 10_000 },
|
||
);
|
||
|
||
await page.evaluate((hostSel) => {
|
||
const root = window.__impeccableLiveQuery(hostSel)?.shadowRoot;
|
||
root?.querySelector('.panel-close')?.click();
|
||
}, DESIGN_HOST);
|
||
await page.waitForFunction(
|
||
({ hostSel, toggleSel }) => {
|
||
const panel = window.__impeccableLiveQuery(hostSel)?.shadowRoot?.querySelector('.panel');
|
||
const toggle = window.__impeccableLiveQuery(toggleSel);
|
||
return panel?.getAttribute('data-open') === 'false' && toggle?.dataset.active === 'false';
|
||
},
|
||
{ hostSel: DESIGN_HOST, toggleSel: DESIGN_TOGGLE },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
export async function clickExitLiveMode(page) {
|
||
await clickLiveControl(page, EXIT_BUTTON);
|
||
await page.waitForFunction(
|
||
({ barSel }) => {
|
||
const bar = window.__impeccableLiveQuery?.(barSel);
|
||
return window.__IMPECCABLE_LIVE_INIT__ === false && (!bar || !bar.isConnected);
|
||
},
|
||
{ barSel: GLOBAL_BAR_ID },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
export async function drawAnnotationPinAndStroke(page, {
|
||
comment = 'Make this area easier to scan',
|
||
} = {}) {
|
||
await installLiveQueryHelpers(page);
|
||
const rect = await waitForAnnotationRect(page);
|
||
const pinPoint = {
|
||
x: rect.left + Math.min(28, Math.max(12, rect.width * 0.2)),
|
||
y: rect.top + Math.min(28, Math.max(12, rect.height * 0.35)),
|
||
};
|
||
await page.mouse.click(pinPoint.x, pinPoint.y);
|
||
await page.waitForFunction(
|
||
(pinsSel) => Boolean(window.__impeccableLiveQuery(pinsSel)?.querySelector('input')),
|
||
ANNOTATION_PINS_ID,
|
||
{ timeout: 5_000 },
|
||
);
|
||
await page.evaluate(({ pinsSel, value }) => {
|
||
const input = window.__impeccableLiveQuery(pinsSel)?.querySelector('input');
|
||
if (!input) return false;
|
||
input.value = value;
|
||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||
return true;
|
||
}, { pinsSel: ANNOTATION_PINS_ID, value: comment });
|
||
await page.waitForFunction(
|
||
({ pinsSel, expected }) => {
|
||
const pins = window.__impeccableLiveQuery(pinsSel);
|
||
return pins && pins.textContent.includes(expected);
|
||
},
|
||
{ pinsSel: ANNOTATION_PINS_ID, expected: comment },
|
||
{ timeout: 5_000 },
|
||
);
|
||
|
||
const strokeStart = { x: rect.left + rect.width * 0.58, y: rect.top + rect.height * 0.28 };
|
||
const strokeEnd = { x: rect.left + rect.width * 0.86, y: rect.top + rect.height * 0.72 };
|
||
await page.mouse.move(strokeStart.x, strokeStart.y);
|
||
await page.mouse.down();
|
||
await page.mouse.move((strokeStart.x + strokeEnd.x) / 2, (strokeStart.y + strokeEnd.y) / 2, { steps: 4 });
|
||
await page.mouse.move(strokeEnd.x, strokeEnd.y, { steps: 4 });
|
||
await page.mouse.up();
|
||
|
||
await page.waitForFunction(
|
||
({ annotSel, clearSel }) => {
|
||
const annot = window.__impeccableLiveQuery(annotSel);
|
||
const clear = window.__impeccableLiveQuery(clearSel);
|
||
const stroke = annot?.querySelector('[data-annot-stroke]');
|
||
return Boolean(stroke) && clear?.style.display !== 'none';
|
||
},
|
||
{ annotSel: ANNOTATION_ID, clearSel: ANNOTATION_CLEAR_ID },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
export async function assertAnnotationUploadEvent(event) {
|
||
if (!event) throw new Error('expected recorded generate event');
|
||
if (!Array.isArray(event.comments) || event.comments.length < 1) {
|
||
throw new Error('expected generate event to include annotation comments');
|
||
}
|
||
if (!Array.isArray(event.strokes) || event.strokes.length < 1) {
|
||
throw new Error('expected generate event to include annotation strokes');
|
||
}
|
||
if (!event.screenshotPath || typeof event.screenshotPath !== 'string') {
|
||
throw new Error('expected generate event to include screenshotPath');
|
||
}
|
||
}
|
||
|
||
async function waitForAnnotationRect(page) {
|
||
await page.waitForFunction(
|
||
(sel) => {
|
||
const el = window.__impeccableLiveQuery(sel);
|
||
if (!el || el.style.display === 'none') return false;
|
||
const rect = el.getBoundingClientRect();
|
||
return rect.width > 20 && rect.height > 20;
|
||
},
|
||
ANNOTATION_ID,
|
||
{ timeout: 5_000 },
|
||
);
|
||
return page.evaluate((sel) => {
|
||
const rect = window.__impeccableLiveQuery(sel).getBoundingClientRect();
|
||
return {
|
||
left: rect.left,
|
||
top: rect.top,
|
||
width: rect.width,
|
||
height: rect.height,
|
||
};
|
||
}, ANNOTATION_ID);
|
||
}
|
||
|
||
/**
|
||
* Click an in-page element to select it. live-browser.js's picker only acts
|
||
* when state === 'PICKING' AND pickActive is true. Both interaction toggles
|
||
* default off on a fresh page — enable pick mode before hovering.
|
||
*/
|
||
export async function pickElement(page, selector, opts = {}) {
|
||
const position = opts.position || null;
|
||
if (opts.resetPickMode) await resetPickMode(page);
|
||
else await enablePickMode(page);
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
const el = await page.waitForSelector(selector, { timeout: 5_000 });
|
||
await ensurePickerActive(page);
|
||
await hideAnnotationOverlay(page);
|
||
try {
|
||
await el.hover(position ? { position } : undefined);
|
||
// Tiny settle: live-browser updates `hoveredElement` on mousemove, and the
|
||
// click handler reads from it.
|
||
await page.waitForTimeout(50);
|
||
await clickPickTarget(page, el, position);
|
||
} catch (err) {
|
||
if (attempt === 2) throw err;
|
||
await page.waitForTimeout(250);
|
||
await resetPickMode(page);
|
||
continue;
|
||
}
|
||
// Per-element bar mounts on click → wait for it. Dialog fixtures can
|
||
// briefly hide the global live chrome while preActions open a portal, so
|
||
// retry once after explicitly re-arming picker mode.
|
||
const visible = await page
|
||
.waitForSelector(BAR_ID, { state: 'visible', timeout: 5_000 })
|
||
.then(() => true, () => false);
|
||
if (visible) break;
|
||
await resetPickMode(page);
|
||
if (attempt === 2) {
|
||
const snapshot = await page.evaluate(({ selector, barSel, pickSel }) => {
|
||
const target = document.querySelector(selector);
|
||
const rect = target?.getBoundingClientRect();
|
||
const hit = rect ? document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2) : null;
|
||
const query = window.__impeccableLiveQuery || ((sel) => document.querySelector(sel));
|
||
const bar = query(barSel);
|
||
const pick = query(pickSel);
|
||
return {
|
||
liveState: window.__IMPECCABLE_LIVE_STATE__ || null,
|
||
target: target ? { tag: target.tagName, classes: target.className, rect: rect?.toJSON?.() || null } : null,
|
||
hit: hit ? { tag: hit.tagName, classes: hit.className, text: (hit.textContent || '').slice(0, 80) } : null,
|
||
pickActive: pick?.dataset.active || null,
|
||
bar: bar ? { display: bar.style.display, text: bar.textContent } : null,
|
||
debugState: window.__IMPECCABLE_LIVE_CHROME_CORE__?.debugState?.() || null,
|
||
};
|
||
}, { selector, barSel: BAR_ID, pickSel: PICK_TOGGLE_ID }).catch((error) => ({ error: error.message }));
|
||
throw new Error(`pick did not open configure bar for ${selector}: ${JSON.stringify(snapshot)}`);
|
||
}
|
||
}
|
||
// Wait specifically for the Configure-row submit button to be in the bar.
|
||
// pickElement returning before that race-conditions with clickGo on
|
||
// fixtures whose framework re-renders right after pick (modal open, tab
|
||
// switch). Anchoring the wait on the submit button's accessible name is
|
||
// robust: the bar can be visible-but-empty (state=PICKING) before
|
||
// showBar('configure') populates the row, and the button itself is
|
||
// icon-only.
|
||
await page.waitForFunction(
|
||
({ barSel, goLabel }) => {
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!bar) return false;
|
||
const btns = [...bar.querySelectorAll('button')];
|
||
return btns.some((b) => (b.getAttribute('aria-label') || '') === goLabel);
|
||
},
|
||
{ barSel: BAR_ID, goLabel: GO_BUTTON_ARIA_LABEL },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
async function hideAnnotationOverlay(page) {
|
||
await page.evaluate(() => {
|
||
const annot = window.__impeccableLiveQuery('#impeccable-live-annot');
|
||
if (annot) annot.style.display = 'none';
|
||
}).catch(() => {});
|
||
}
|
||
|
||
async function clickPickTarget(page, el, position = null) {
|
||
const box = await el.boundingBox();
|
||
if (box) {
|
||
const x = position ? box.x + position.x : box.x + box.width / 2;
|
||
const y = position ? box.y + position.y : box.y + box.height / 2;
|
||
await page.mouse.click(x, y);
|
||
return;
|
||
}
|
||
await el.evaluate((node) => node.click());
|
||
}
|
||
|
||
async function ensurePickerActive(page) {
|
||
await page.waitForSelector(GLOBAL_BAR_ID, { timeout: 5_000 });
|
||
const active = await page
|
||
.locator(PICK_TOGGLE_ID)
|
||
.evaluate((el) => el.dataset.active === 'true')
|
||
.catch(() => false);
|
||
if (active) return;
|
||
|
||
const clicked = await page.evaluate((sel) => {
|
||
const btn = window.__impeccableLiveQuery(sel);
|
||
if (!btn) return false;
|
||
btn.click();
|
||
return true;
|
||
}, PICK_TOGGLE_ID);
|
||
if (!clicked) {
|
||
await page.locator(PICK_TOGGLE_ID).click({ timeout: 5_000 });
|
||
}
|
||
await page.waitForFunction(
|
||
(sel) => window.__impeccableLiveQuery(sel)?.dataset.active === 'true',
|
||
PICK_TOGGLE_ID,
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
async function resetPickMode(page) {
|
||
await page.keyboard.press('Escape').catch(() => {});
|
||
await page.waitForTimeout(100);
|
||
await page.keyboard.press('Escape').catch(() => {});
|
||
await page.waitForTimeout(100);
|
||
await page.evaluate((sel) => {
|
||
const btn = window.__impeccableLiveQuery(sel);
|
||
if (!btn) return;
|
||
const active = btn.dataset.active === 'true';
|
||
if (active) btn.click();
|
||
btn.click();
|
||
}, PICK_TOGGLE_ID).catch(() => {});
|
||
await page.waitForFunction(
|
||
(sel) => window.__impeccableLiveQuery(sel)?.dataset.active === 'true',
|
||
PICK_TOGGLE_ID,
|
||
{ timeout: 5_000 },
|
||
).catch(() => {});
|
||
}
|
||
|
||
/**
|
||
* Set the variant count by clicking the count button (cycles 2 → 3 → 4 → 2).
|
||
* Default is 3. If the desired count is already showing, this is a no-op.
|
||
*/
|
||
export async function setCount(page, count) {
|
||
if (count < 2 || count > 4) throw new Error('count must be 2..4');
|
||
for (let i = 0; i < 4; i++) {
|
||
const current = await page.evaluate((barSel) => {
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!bar) return null;
|
||
const btns = [...bar.querySelectorAll('button')];
|
||
const btn = btns.find((b) => /^×\d+$/.test((b.textContent || '').trim()));
|
||
if (!btn) return null;
|
||
return parseInt((btn.textContent || '').trim().slice(1), 10);
|
||
}, BAR_ID);
|
||
if (current === count) return;
|
||
await page.locator(`${BAR_ID} button`, { hasText: /^×\d+$/ }).click();
|
||
}
|
||
throw new Error(`could not cycle count to ${count}`);
|
||
}
|
||
|
||
/** Select a named Impeccable sub-command from the configure-row picker. */
|
||
export async function selectAction(page, action) {
|
||
const pickerSelector = '#impeccable-live-picker';
|
||
const opened = await page.evaluate(({ barSel, pickerSel }) => {
|
||
const query = window.__impeccableLiveQuery || ((selector) => document.querySelector(selector));
|
||
const bar = query(barSel);
|
||
const picker = query(pickerSel);
|
||
const actionControl = [...(bar?.querySelectorAll('button') || [])]
|
||
.find((button) => (button.textContent || '').includes('\u25BE'));
|
||
if (!actionControl || !picker) return false;
|
||
actionControl.click();
|
||
return true;
|
||
}, { barSel: BAR_ID, pickerSel: pickerSelector });
|
||
if (!opened) throw new Error('could not open Live action picker');
|
||
|
||
await page.waitForFunction((selector) => {
|
||
const picker = window.__impeccableLiveQuery(selector);
|
||
return picker && picker.style.display !== 'none';
|
||
}, pickerSelector, { timeout: 5_000 });
|
||
|
||
const selected = await page.evaluate(({ pickerSel, value }) => {
|
||
const picker = window.__impeccableLiveQuery(pickerSel);
|
||
const chip = picker?.querySelector(`button[data-action="${CSS.escape(value)}"]`);
|
||
if (!chip) return false;
|
||
chip.click();
|
||
return true;
|
||
}, { pickerSel: pickerSelector, value: action });
|
||
if (!selected) throw new Error(`Live action ${JSON.stringify(action)} is unavailable`);
|
||
}
|
||
|
||
/**
|
||
* Click Go. Browser POSTs the generate event; the agent picks it up. Headed
|
||
* browser runs can occasionally accept the click without leaving configure
|
||
* mode after a long manual Apply, so verify the bar advanced and retry the
|
||
* visible click if it did not.
|
||
*/
|
||
export async function clickGo(page) {
|
||
let lastErr;
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
await clickBarButton(page, { ariaLabel: GO_BUTTON_ARIA_LABEL });
|
||
const advanced = await page.waitForFunction(
|
||
({ barSel, goLabel }) => {
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!bar) return false;
|
||
const text = bar.textContent || '';
|
||
if (/Generating\b/.test(text)) return true;
|
||
if (/\d+\s*\/\s*\d+/.test(text)) return true;
|
||
return ![...bar.querySelectorAll('button')].some((button) => (button.getAttribute('aria-label') || '') === goLabel);
|
||
},
|
||
{ barSel: BAR_ID, goLabel: GO_BUTTON_ARIA_LABEL },
|
||
{ timeout: 3_000 },
|
||
).then(() => true, (err) => {
|
||
lastErr = err;
|
||
return false;
|
||
});
|
||
if (advanced) return;
|
||
await page.waitForTimeout(500);
|
||
}
|
||
throw lastErr || new Error('Go click did not leave configure mode');
|
||
}
|
||
|
||
/**
|
||
* Wait for the bar to enter CYCLING state — happens after the agent's
|
||
* variants land in the DOM via HMR and the MutationObserver counts them.
|
||
*
|
||
* The cycling row has the visible counter `N/M` in monospaced font; we
|
||
* detect it by content. The bar can also auto-reload if HMR was slow, so
|
||
* we give it a generous window.
|
||
*/
|
||
export async function waitForCycling(page, expectedCount, { timeout = 30_000 } = {}) {
|
||
await installLiveQueryHelpers(page);
|
||
try {
|
||
await page.waitForFunction(
|
||
({ barSel, expected }) => {
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!bar) return false;
|
||
const text = bar.textContent || '';
|
||
// Counter format: "1/3", "2/3" etc. Look for any "i/N" with N matching.
|
||
const m = text.match(/(\d+)\s*\/\s*(\d+)/);
|
||
if (!m) return false;
|
||
const wrapper = window.__impeccableLiveQuery('[data-impeccable-variants]');
|
||
const debugState = window.__IMPECCABLE_LIVE_CHROME_CORE__?.debugState?.();
|
||
const arrived = /^(?:svelte|vue)-component$/.test(wrapper?.dataset.impeccablePreview || '')
|
||
? Number(debugState?.arrivedVariants || 0)
|
||
: wrapper
|
||
? wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])').length
|
||
: 0;
|
||
return parseInt(m[2], 10) === expected && arrived >= expected;
|
||
},
|
||
{ barSel: BAR_ID, expected: expectedCount },
|
||
{ timeout },
|
||
);
|
||
} catch (err) {
|
||
if (process.env.IMPECCABLE_E2E_DEBUG) {
|
||
const snapshot = await page.evaluate((barSel) => {
|
||
const query = window.__impeccableLiveQuery || ((sel) => document.querySelector(sel));
|
||
const root = window.__IMPECCABLE_LIVE_CHROME_CORE__?.root?.() || window.__IMPECCABLE_LIVE_UI_ROOT__ || null;
|
||
const bar = query(barSel);
|
||
const toast = query('#impeccable-live-toast');
|
||
const wrapper = query('[data-impeccable-variants]');
|
||
return {
|
||
liveInit: window.__IMPECCABLE_LIVE_INIT__,
|
||
adapter: window.__IMPECCABLE_LIVE_ADAPTER__,
|
||
rootText: root?.textContent?.replace(/\s+/g, ' ').trim().slice(0, 600) || null,
|
||
bar: bar ? { display: bar.style.display, text: bar.textContent } : null,
|
||
toast: toast?.textContent || null,
|
||
wrapper: wrapper ? { preview: wrapper.dataset.impeccablePreview, count: wrapper.dataset.impeccableVariantCount, html: wrapper.outerHTML.slice(0, 600) } : null,
|
||
debugState: window.__IMPECCABLE_LIVE_CHROME_CORE__?.debugState?.() || null,
|
||
storage: localStorage.getItem('impeccable-live-session'),
|
||
scripts: document.querySelectorAll('script[data-impeccable-live-script]').length,
|
||
bodyText: document.body.textContent.replace(/\s+/g, ' ').trim().slice(0, 600),
|
||
};
|
||
}, BAR_ID).catch((snapErr) => ({ error: snapErr.message }));
|
||
console.error('--- waitForCycling snapshot ---\n' + JSON.stringify(snapshot, null, 2));
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Click the next variant button (right arrow).
|
||
*/
|
||
export async function clickNext(page) {
|
||
await clickBarButton(page, '→');
|
||
}
|
||
|
||
export async function clickPrev(page) {
|
||
await clickBarButton(page, '←');
|
||
}
|
||
|
||
function barButtonMatch(label) {
|
||
if (label instanceof RegExp) return { kind: 'regex', source: label.source, flags: label.flags };
|
||
if (label && typeof label === 'object' && label.ariaLabel) return { kind: 'aria', value: label.ariaLabel };
|
||
return { kind: 'text', value: String(label) };
|
||
}
|
||
|
||
async function clickBarButton(page, label) {
|
||
const textMatch = barButtonMatch(label);
|
||
let lastErr;
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
try {
|
||
await installLiveQueryHelpers(page);
|
||
const button = textMatch.kind === 'aria'
|
||
? page.locator(`${BAR_ID} button[aria-label="${textMatch.value}"]`)
|
||
: page.locator(`${BAR_ID} button`, { hasText: label });
|
||
await button.click({ timeout: 5_000 });
|
||
return;
|
||
} catch (err) {
|
||
lastErr = err;
|
||
await page.waitForTimeout(500);
|
||
}
|
||
}
|
||
// Real-LLM fixtures can leave Vite/Tailwind HMR settling for longer than a
|
||
// human-visible click target stays Playwright-stable. Dispatch the click on
|
||
// the current button if normal user-like clicks lost the remount race.
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
try {
|
||
const clicked = await page.evaluate(findAndClickBarButton, { barSel: BAR_ID, textMatch });
|
||
if (clicked) return;
|
||
} catch (err) {
|
||
lastErr = err;
|
||
}
|
||
await page.waitForSelector(BAR_ID, { timeout: 5_000 }).catch(() => {});
|
||
await page.waitForTimeout(500);
|
||
}
|
||
throw lastErr;
|
||
}
|
||
|
||
async function dispatchBarButton(page, label) {
|
||
try {
|
||
await installLiveQueryHelpers(page);
|
||
const textMatch = barButtonMatch(label);
|
||
return await withTimeout(
|
||
page.evaluate(findAndClickBarButton, { barSel: BAR_ID, textMatch }),
|
||
5_000,
|
||
'dispatch bar button',
|
||
);
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function findAndClickBarButton({ barSel, textMatch }) {
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!bar) return false;
|
||
const btn = [...bar.querySelectorAll('button')]
|
||
.find((candidate) => {
|
||
const text = candidate.textContent || '';
|
||
if (textMatch.kind === 'regex') return new RegExp(textMatch.source, textMatch.flags).test(text);
|
||
if (textMatch.kind === 'aria') return (candidate.getAttribute('aria-label') || '') === textMatch.value;
|
||
return text.includes(textMatch.value);
|
||
});
|
||
if (!btn) return false;
|
||
btn.click();
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* Read the currently visible variant index (the "i" in "i/N").
|
||
*/
|
||
export async function getVisibleVariant(page) {
|
||
try {
|
||
await installLiveQueryHelpers(page);
|
||
return await withTimeout(
|
||
page.evaluate((barSel) => {
|
||
const wrapper = window.__impeccableLiveQuery('[data-impeccable-variants]');
|
||
if (wrapper) {
|
||
const variants = [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')];
|
||
const visible = variants.find((variant) => getComputedStyle(variant).display !== 'none');
|
||
const idx = visible ? parseInt(visible.dataset.impeccableVariant || '0', 10) : 0;
|
||
if (idx > 0) return idx;
|
||
}
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!bar) return null;
|
||
const m = (bar.textContent || '').match(/(\d+)\s*\/\s*(\d+)/);
|
||
return m ? parseInt(m[1], 10) : null;
|
||
}, BAR_ID),
|
||
5_000,
|
||
'read visible variant',
|
||
);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Click Accept — sends accept event with current variantId + paramValues.
|
||
* The bar transitions to a "Saving..." spinner, then a green confirmed row.
|
||
*/
|
||
export async function clickAccept(page, { expectedVariant } = {}) {
|
||
if (expectedVariant != null) {
|
||
await ensureVisibleVariant(page, expectedVariant);
|
||
}
|
||
if (await dispatchBarButton(page, /Accept/)) return;
|
||
await clickBarButton(page, /Accept/);
|
||
}
|
||
|
||
async function ensureVisibleVariant(page, expectedVariant) {
|
||
for (let attempt = 0; attempt < 5; attempt++) {
|
||
const current = await getVisibleVariant(page);
|
||
if (current === expectedVariant) return;
|
||
if (current == null) {
|
||
await page.waitForTimeout(300);
|
||
continue;
|
||
}
|
||
await clickBarButton(page, current < expectedVariant ? '→' : '←');
|
||
await page.waitForTimeout(300);
|
||
}
|
||
const current = await getVisibleVariant(page);
|
||
if (current !== expectedVariant) {
|
||
throw new Error(`expected visible variant ${expectedVariant} before accept, got ${current}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Click Discard — sends discard event. live-accept.mjs unwinds the wrapper
|
||
* and restores the original.
|
||
*/
|
||
export async function clickDiscard(page) {
|
||
// The discard button has just a "✕" glyph as text content.
|
||
if (await dispatchBarButton(page, '✕')) return;
|
||
await clickBarButton(page, '✕');
|
||
}
|
||
|
||
export async function clickEditCopy(page) {
|
||
await clickEditBadgeButton(page, 'Edit copy');
|
||
await page.waitForFunction(
|
||
() => window.__impeccableLiveQuery('[data-impeccable-editable="true"]')?.isContentEditable === true,
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
export async function editTextLeaf(page, leafSelector, newText) {
|
||
const leaf = page.locator(leafSelector).first();
|
||
await leaf.waitFor({ state: 'visible', timeout: 5_000 });
|
||
const editable = await resolveEditableLeaf(page, leafSelector);
|
||
await editable.click({ timeout: 5_000 });
|
||
await editable.fill(newText, { timeout: 5_000 });
|
||
}
|
||
|
||
async function resolveEditableLeaf(page, leafSelector) {
|
||
const direct = page.locator(`${leafSelector}[contenteditable="true"]`).first();
|
||
if (await direct.count()) return direct;
|
||
const nested = page.locator(leafSelector).first().locator('[contenteditable="true"]').first();
|
||
if (await nested.count()) return nested;
|
||
return page.locator(leafSelector).first();
|
||
}
|
||
|
||
export async function clickSaveEdit(page) {
|
||
await clickEditBadgeButton(page, 'Save');
|
||
await page.waitForFunction(
|
||
() => !window.__impeccableLiveQuery('[data-impeccable-editable="true"]'),
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
async function clickEditBadgeButton(page, label) {
|
||
const proxyRect = await page.evaluate((text) => {
|
||
const proxies = [...document.querySelectorAll('[data-impeccable-edit-badge-proxy="true"]')];
|
||
const proxy = proxies.find((candidate) =>
|
||
(candidate.title || candidate.getAttribute('aria-label') || '').includes(text)
|
||
);
|
||
if (!proxy) return null;
|
||
const rect = proxy.getBoundingClientRect();
|
||
if (rect.width < 1 || rect.height < 1) return null;
|
||
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
|
||
}, label).catch(() => null);
|
||
if (proxyRect) {
|
||
await page.mouse.click(proxyRect.x, proxyRect.y);
|
||
return;
|
||
}
|
||
const button = page.locator(`${EDIT_BADGE_ID} button`, { hasText: label });
|
||
try {
|
||
await button.click({ timeout: 5_000 });
|
||
return;
|
||
} catch (err) {
|
||
const clicked = await page.evaluate(({ badgeSel, text }) => {
|
||
const badge = window.__impeccableLiveQuery(badgeSel);
|
||
const btn = [...(badge?.querySelectorAll('button') || [])].find((candidate) =>
|
||
(candidate.textContent || candidate.getAttribute('aria-label') || candidate.title || '').includes(text)
|
||
);
|
||
if (!btn) return false;
|
||
btn.click();
|
||
return true;
|
||
}, { badgeSel: EDIT_BADGE_ID, text: label });
|
||
if (!clicked) throw err;
|
||
}
|
||
}
|
||
|
||
export async function assertApplyDockVisible(page, expectedCount, { timeout = 5_000 } = {}) {
|
||
await page.waitForFunction(
|
||
({ dockSel, expected }) => {
|
||
const dock = window.__impeccableLiveQuery(dockSel);
|
||
if (!dock || dock.style.display === 'none') return false;
|
||
const pill = [...dock.querySelectorAll('button')].find((btn) =>
|
||
/Apply copy edit/.test(btn.textContent || '')
|
||
);
|
||
if (!pill || pill.style.display === 'none') return false;
|
||
if (expected == null) return true;
|
||
return parseInt(pill.dataset.count || '0', 10) === expected;
|
||
},
|
||
{ dockSel: PENDING_DOCK_ID, expected: expectedCount },
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
export async function waitForApplyDockHidden(page, { timeout = 10_000 } = {}) {
|
||
await page.waitForFunction(
|
||
(dockSel) => {
|
||
const dock = window.__impeccableLiveQuery(dockSel);
|
||
if (!dock || dock.style.display === 'none') return true;
|
||
const pill = [...dock.querySelectorAll('button')].find((btn) =>
|
||
/Apply copy edit/.test(btn.textContent || '')
|
||
);
|
||
return !pill || pill.style.display === 'none' || parseInt(pill.dataset.count || '0', 10) === 0;
|
||
},
|
||
PENDING_DOCK_ID,
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
export async function assertApplyDockLoading(page, { timeout = 5_000 } = {}) {
|
||
await page.waitForFunction(
|
||
(dockSel) => {
|
||
const dock = window.__impeccableLiveQuery(dockSel);
|
||
if (!dock || dock.style.display === 'none') return false;
|
||
const pill = [...dock.querySelectorAll('button')].find((btn) =>
|
||
/Apply copy edit|Applying|Verifying|Fixing apply issue/.test(btn.textContent || '')
|
||
);
|
||
if (!pill) return false;
|
||
const spinner = dock.querySelector('[aria-hidden="true"]');
|
||
return pill.disabled === true
|
||
|| pill.getAttribute('aria-busy') === 'true'
|
||
|| /Applying|Verifying|Fixing apply issue/.test(pill.textContent || '')
|
||
|| spinner?.style?.display === 'inline-block';
|
||
},
|
||
PENDING_DOCK_ID,
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
export async function clickApplyEdits(page) {
|
||
const dialog = page.waitForEvent('dialog', { timeout: 5_000 })
|
||
.then((d) => d.accept())
|
||
.catch(() => {});
|
||
await page.locator(`${PENDING_DOCK_ID} button`, { hasText: /Apply copy edit/ }).click({ timeout: 5_000 });
|
||
await dialog;
|
||
}
|
||
|
||
export function assertSourceApplied(tmp, file, originalText, newText) {
|
||
const body = readFileSync(join(tmp, file), 'utf-8');
|
||
if (!body.includes(newText)) {
|
||
throw new Error(`expected ${file} to include ${JSON.stringify(newText)}`);
|
||
}
|
||
if (originalText && !String(newText).includes(originalText) && body.includes(originalText)) {
|
||
throw new Error(`expected ${file} not to include ${JSON.stringify(originalText)}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Wait for the bar to go away (after accept/discard the bar hides on confirm).
|
||
*/
|
||
export async function waitForBarHidden(page, { timeout = 10_000 } = {}) {
|
||
await installLiveQueryHelpers(page);
|
||
await page.waitForFunction(
|
||
(barSel) => {
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
return !bar || bar.style.display === 'none';
|
||
},
|
||
BAR_ID,
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Dismiss dev-tool overlays that intercept clicks on the live bar (Astro, etc.).
|
||
* @param {import('playwright').Page} page
|
||
*/
|
||
export async function preparePageForBarInteraction(page) {
|
||
await page.evaluate(() => {
|
||
for (const el of window.__impeccableLiveQueryAll('astro-dev-toolbar')) {
|
||
el.style.setProperty('display', 'none', 'important');
|
||
el.style.setProperty('pointer-events', 'none', 'important');
|
||
}
|
||
});
|
||
}
|
||
|
||
export async function waitForSteerInputFocused(page, { timeout = 5_000 } = {}) {
|
||
await page.waitForFunction(
|
||
(inputSel) => {
|
||
const input = window.__impeccableLiveQuery(inputSel);
|
||
const active = window.__IMPECCABLE_LIVE_CHROME_CORE__?.activeElementDeep?.()
|
||
|| input?.getRootNode?.()?.activeElement
|
||
|| document.activeElement;
|
||
return Boolean(input && active === input && input.style.pointerEvents !== 'none' && input.style.opacity !== '0');
|
||
},
|
||
STEER_INPUT_ID,
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
export async function waitForSteerInputValue(page, value, { timeout = 5_000 } = {}) {
|
||
await page.waitForFunction(
|
||
({ inputSel, value: expected }) => window.__impeccableLiveQuery(inputSel)?.value === expected,
|
||
{ inputSel: STEER_INPUT_ID, value },
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Expand the Steer pill, type a message, and submit with Enter.
|
||
* Uses a normal click when possible; falls back to direct focus when overlays
|
||
* (e.g. Astro dev toolbar) intercept pointer events — same outcome as keyboard focus.
|
||
*/
|
||
export async function submitSteer(page, message) {
|
||
await installLiveQueryHelpers(page);
|
||
await preparePageForBarInteraction(page);
|
||
const chat = page.locator(STEER_CHAT_ID);
|
||
await chat.waitFor({ state: 'visible', timeout: 5_000 });
|
||
|
||
try {
|
||
await chat.click({ timeout: 2_500 });
|
||
} catch {
|
||
await chat.click({ force: true, timeout: 2_500 });
|
||
}
|
||
await waitForSteerInputFocused(page);
|
||
|
||
const input = page.locator(STEER_INPUT_ID);
|
||
await input.type(message, { timeout: 5_000 });
|
||
await waitForSteerInputValue(page, message);
|
||
await input.press('Enter');
|
||
}
|
||
|
||
/**
|
||
* Poll until a marked hero is visible. Uses Playwright's visible check so
|
||
* elements inside closed modals/tabs do not satisfy the assertion.
|
||
*/
|
||
export async function waitForSteerDomMarker(page, selector, { timeout = 20_000 } = {}) {
|
||
const loc = page.locator(selector).first();
|
||
await loc.waitFor({ state: 'visible', timeout });
|
||
}
|
||
|
||
/**
|
||
* Steer bar enters processing mode after submit (handing off / working).
|
||
*/
|
||
export async function waitForSteerLocked(page, { timeout = 5_000 } = {}) {
|
||
await page.waitForFunction(
|
||
(sel) => window.__impeccableLiveQuery(sel)?.dataset.processing === 'true',
|
||
STEER_CHAT_ID,
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Steer bar unlocks after the agent replies steer_done over SSE.
|
||
*/
|
||
export async function waitForSteerUnlocked(page, { timeout = 15_000 } = {}) {
|
||
await page.waitForFunction(
|
||
(sel) => {
|
||
const chat = window.__impeccableLiveQuery(sel);
|
||
const input = window.__impeccableLiveQuery('#impeccable-live-page-chat-input');
|
||
return chat?.dataset.processing !== 'true' && input && !input.disabled;
|
||
},
|
||
STEER_CHAT_ID,
|
||
{ timeout },
|
||
);
|
||
}
|
||
|
||
async function ensureToggleActive(page, selector, shouldBeActive) {
|
||
await installLiveQueryHelpers(page);
|
||
const isActive = await page.locator(selector).evaluate((el) => el?.dataset.active === 'true');
|
||
if (isActive === shouldBeActive) return;
|
||
await page.locator(selector).click({ timeout: 5_000 });
|
||
await page.waitForFunction(
|
||
({ sel, active }) => window.__impeccableLiveQuery(sel)?.dataset.active === (active ? 'true' : 'false'),
|
||
{ sel: selector, active: shouldBeActive },
|
||
{ timeout: 5_000 },
|
||
);
|
||
}
|
||
|
||
/** Turn on Pick mode (and off Insert — they are mutually exclusive). */
|
||
export async function enablePickMode(page) {
|
||
await ensureToggleActive(page, PICK_TOGGLE, true);
|
||
}
|
||
|
||
/** Turn on Insert mode (and off Pick — they are mutually exclusive). */
|
||
export async function enableInsertMode(page) {
|
||
await ensureToggleActive(page, INSERT_TOGGLE, true);
|
||
}
|
||
|
||
/**
|
||
* Insert flow: hover an anchor at before/after edge, click to place the
|
||
* resizable placeholder, describe the new element, and click Create.
|
||
*/
|
||
export async function runInsertFlow(page, {
|
||
anchorSelector,
|
||
position = 'after',
|
||
prompt = 'Add a testimonial strip',
|
||
} = {}) {
|
||
await enableInsertMode(page);
|
||
const anchor = await page.waitForSelector(anchorSelector, { timeout: 5_000 });
|
||
const box = await anchor.boundingBox();
|
||
if (!box) throw new Error(`anchor ${anchorSelector} has no layout box`);
|
||
|
||
const x = box.x + box.width / 2;
|
||
const y = position === 'before' ? box.y + 4 : box.y + box.height - 4;
|
||
await page.mouse.move(x, y);
|
||
await page.waitForFunction(() => {
|
||
const line = window.__impeccableLiveQuery('#impeccable-live-insert-line');
|
||
return line && line.style.display !== 'none';
|
||
}, { timeout: 5_000 });
|
||
await page.mouse.click(x, y);
|
||
|
||
await installLiveQueryHelpers(page);
|
||
await page.waitForFunction(
|
||
({ inputSel, barSel }) => {
|
||
const input = window.__impeccableLiveQuery(inputSel);
|
||
const bar = window.__impeccableLiveQuery(barSel);
|
||
if (!input || !bar) return false;
|
||
const rect = input.getBoundingClientRect();
|
||
return rect.width > 0 && rect.height > 0 && bar.style.display !== 'none';
|
||
},
|
||
{ inputSel: INSERT_INPUT_ID, barSel: BAR_ID },
|
||
{ timeout: 5_000 },
|
||
);
|
||
|
||
const focused = await page.evaluate((sel) => {
|
||
const el = window.__impeccableLiveQuery(sel);
|
||
if (!el) return false;
|
||
try { el.focus({ preventScroll: true }); } catch { el.focus(); }
|
||
let active = document.activeElement;
|
||
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
|
||
return active === el;
|
||
}, INSERT_INPUT_ID);
|
||
if (!focused) throw new Error('Insert prompt input did not receive focus');
|
||
|
||
await page.keyboard.type(prompt);
|
||
await page.waitForFunction(
|
||
({ sel, value }) => window.__impeccableLiveQuery(sel)?.value === value,
|
||
{ sel: INSERT_INPUT_ID, value: prompt },
|
||
{ timeout: 5_000 },
|
||
);
|
||
|
||
await page.waitForFunction(
|
||
(sel) => {
|
||
const btn = window.__impeccableLiveQuery(sel);
|
||
return btn && !btn.disabled;
|
||
},
|
||
INSERT_CREATE_ID,
|
||
{ timeout: 5_000 },
|
||
);
|
||
const clicked = await page.evaluate((sel) => {
|
||
const btn = window.__impeccableLiveQuery(sel);
|
||
if (!btn || btn.disabled) return false;
|
||
btn.click();
|
||
return true;
|
||
}, INSERT_CREATE_ID);
|
||
if (!clicked) {
|
||
await page.locator(INSERT_CREATE_ID).click({ force: true, timeout: 5_000 });
|
||
}
|
||
}
|