diff --git a/.agent/skills/impeccable/SKILL.md b/.agent/skills/impeccable/SKILL.md index 63e309e81..12d0a48f8 100644 --- a/.agent/skills/impeccable/SKILL.md +++ b/.agent/skills/impeccable/SKILL.md @@ -66,7 +66,8 @@ Choose the mode from the requested surface, not the product, and persist it only | `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) | | `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) · native: [reference/adapt.native.md](reference/adapt.native.md) | | `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) | -| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) | +| `live` | Iterate | Visual variant mode: pick elements in the browser, iterate on alternatives | [reference/live.md](reference/live.md) | +| `generate [n] [action] [element]` | Iterate | Variants, versions, or alternatives of a named element to choose from in the live browser; no manual picking | [reference/generate.md](reference/generate.md) | Routing: diff --git a/.agent/skills/impeccable/reference/generate.md b/.agent/skills/impeccable/reference/generate.md new file mode 100644 index 000000000..6a438bdc8 --- /dev/null +++ b/.agent/skills/impeccable/reference/generate.md @@ -0,0 +1,101 @@ +> **Additional context needed**: only the target element, when the request does not name one that resolves uniquely on the page. + +Generate is the fast lane into live mode: the user names an element, a direction, and a count in one sentence, and within a minute they are cycling through variants in their browser. One command boots the helper, hands the element to the overlay in the page your harness already shows (it scrolls to it, selects it, and fires the same Go a click fires) and returns the generate event; one edit writes the variants; one call replies and waits for the user's choice, which the helper bakes into source itself. This file owns the lane's plumbing; from the event onward the design work is [live.md](live.md)'s, unchanged, so read it in full now if you have not this session. + +**Web only.** Live mode's browser overlay has no native equivalent; on `ios` / `android` / `adaptive` projects, decline this command and offer `bolder` or `quieter` on the source instead. + +The plumbing is where the lane saves time: one command starts the session around the page your harness already shows, one call replies and waits, and nothing here is a browser you have to babysit. The design work is not where it saves time. Setup runs as for any command (`impeccable context`, this reference, craft-floor.md before the edit), and the variants are planned, written, and accepted exactly the way a live session plans, writes, and accepts them. + +Three prohibitions cover the known ways this command goes wrong: + +- **Never run init or document, and never ask for PRODUCT.md or DESIGN.md.** When they exist, the start command prints them under `boot` and you use them. When they do not, it says so (`contextMissing`, `contextNote`) and you extract the identity from the event (Step 3). A missing file is never a reason to interview the user inside this command; offer `init` in one line after the session ends. +- **Never hand-write a variants wrapper or invent a session id.** Only the browser mints session ids (8 hex characters, at Go). A missing event is fixed by rerunning Step 2, never with a direct source edit. +- **Do not act on hook findings while live markers are in the file**, and do not restyle variants to appease them; the accept verifies the file once the variant is permanent. + +## Step 1: Parse the request + +Three parts, all from the user's sentence: + +- **A number in the request**: that is the count. **No number**: 3. The protocol caps count at 8. +- **The direction wording** maps onto the live action vocabulary; never invent a new action value: + - **bold, bolder, stronger, punchier**: `bolder` + - **quiet, calmer, softer, toned down**: `quieter` + - **simpler, minimal, stripped**: `distill` + - **refined, tightened, polished**: `polish` + - **font and type words**: `typeset` + - **color words**: `colorize` + - **arrangement and spacing words**: `layout` + - **device and breakpoint words**: `adapt` + - **motion words**: `animate` + - **playful words**: `delight` + - **rule-breaking words**: `overdrive` + - **Wording that carries intent but no vocabulary word** ("make it feel like a bank", "warmer", "more premium"): `impeccable`, with the user's wording passed as the prompt. + - **An action fits AND extra intent rides along** ("bolder, but keep it monochrome"): that action, with the rest as the prompt. + - **The wording names no direction at all** ("better", "improve", "nicer", "different", "fresh", "new", "redesign", "fix", "some options", "ideas", "alternatives", or just "variants" with nothing else): Ask the user directly to clarify what you cannot infer. Ask one question, offering the vocabulary: *"Which direction should the variants take? bolder, quieter, simpler (distill), polished, typography (typeset), color (colorize), layout, motion (animate), playful (delight), or rule-breaking (overdrive)."* Map the answer with this list; an answer that is still open ("surprise me", "you pick") is `impeccable` with the user's original wording as the prompt, and Step 2 starts on that answer. +- **The element description** ("the pricing cards", "the hero heading"): Step 2 resolves it to a selector. + +Done when you hold an action from the vocabulary (asked for, when the request named no direction), a count from 1 to 8, and the element description. + +## Step 2: Reuse the page, then start + +**Reuse** the dev server already running and the tab your harness already shows it in; a second server or a second browser window is the failure this step prevents. + +1. **Find the dev server**, cheapest source first, and stop at the first hit: the user's message, a browser tab already on the app (Claude Code: an origin in `tabs_context`), a server your harness started (Claude Code: `preview_list`), a terminal that printed its URL. Its origin is your `--dev-url`. **No hit**: leave `--dev-url` off and run the start command with no wait; the boot probes for a running server and its verdict names the move. `browser_needed` carries the `devUrl` it found: open it as in 2, then rerun with `--dev-url --wait-for-browser 60000`. `no_dev_server` means nothing serves the app: start the dev script the way the verdict says (Claude Code: `preview_start`; Cursor: a background terminal; Codex: an exec you yield from), wait for its URL, then rerun with `--dev-url `. +2. **Open the page that renders the element in your browser, then start.** The route the request names, else the one `--target` serves; `--dev-url` takes only the origin. + - **Cursor** (`browser_navigate`) and **Claude Code** (`navigate`, which opens the Browser pane when it is closed and takes the `tabId` from `tabs_context` when a tab is already on that origin): open the URL, then run the start command with `--dev-url --wait-for-browser 60000`. The boot injects the overlay and the page reloads into it while the command waits. Your browser tool is the only opener on these harnesses; the engine ignores `--open` there. + - **No browser tool** (Codex, others): run the start command with `--open --wait-for-browser 120000`; it opens the system browser, and the longer wait covers the user finding the tab. **`browser_open_failed` back**: tell the user the `url` in one line and rerun with `--wait-for-browser 120000`. + +```bash +.agent/skills/impeccable/scripts/impeccable live-generate --target src/App.jsx --dev-url http://127.0.0.1:5173/ --selector ".pricing-grid" --action bolder --count 3 --boot --wait-for-browser 60000 +``` + +Run it in the foreground in Cursor and Claude Code (it returns within the wait); on Codex, in an exec you yield from, the way Step 3 runs the poll. + +- `--target`: the file that renders the element when the request or the project makes it obvious; skip it otherwise. +- `--dev-url`: the origin from 1; omit it and the boot probes. +- `--selector`: a unique class first, then a landmark tag plus class, an id last (every variant mounts a copy of the element, so an id repeats in the DOM). **The request names a repeated component in plural** ("the pricing cards"): target the container that holds the set, so one scoped stylesheet restyles every instance. One read of the source file that renders the element is allowed when the selector is not obvious; `--dry-run` resolves and reports without starting anything when it is not certain. +- `--boot`: runs the lane's boot (PRODUCT.md and DESIGN.md loaded again for the helper, missing files tolerated, dev URL found, bottom bar hidden for the helper's lifetime) and reuses a helper that is already running. Its result rides along as `boot`. +- Also available: `--prompt`, `--text` (keep only matches whose visible text contains a snippet), `--index` (1-based pick among matches). + +Read the output in this order: `boot` (or `boot.contextMissing` with `boot.contextNote`: the page is the source of truth, per the note), then `event`, the generate event for `sessionId`, with the same `_instructions` a user's Go gets. Every verdict carries `_instructions`, and they win over your recollection of this file; the ones whose move is a decision of yours: + +- **`ambiguous`**: the candidates are listed; target their common container, or rerun with `--text ""` or `--index `. +- **`dev_server_gone`**: the dev server stopped answering while the command waited for the page (on Cursor, a server another chat started dies with that chat). Start it the way the verdict says, then rerun with `--dev-url `. +- **`no_match`**: the tab is on a route that does not render the element (navigate to the right route, rerun), or the selector is wrong (derive a better one from the source, or add `--text`). +- **`config_missing` / `config_invalid`** under `bootError`: follow [live-setup.md](live-setup.md) first, then rerun. +- **`event: null`** with `ok: true`: the event was slower than the wait; run `.agent/skills/impeccable/scripts/impeccable live-poll` once to collect it, then continue. + +Done when the output shows `ok: true`, a `sessionId`, and an `event`, reached with at most one server started and one tab opened by you. + +## Step 3: Generate + +The event is a standard `generate` event: the picked element's context, a preflighted scaffold, and `_instructions` naming the action's reference, the planning section, and the exact splice. Handle it exactly per live.md's **Handle generate**, which owns everything from the identity lock to the done reply: read the action's reference and craft-floor.md as it says, plan per section 4 (identity first, then mode, then three different primary axes, then the squint test), declare knobs per section 7, and deliver per section 6 (a complete replacement of the element per variant, the preview CSS plus every variant in one edit at the scaffold's splice). The lane changes nothing about what a variant may be: the moves a live session would make on this element (a promoted tier, a restructured set, a reordered card, a different surface) are open here too. Never screenshot the page; the overlay preview is the review channel until accept. + +**Reply and wait in one call**, with the file you wrote: + +```bash +.agent/skills/impeccable/scripts/impeccable live-poll --reply EVENT_ID done --file src/App.jsx --then-poll +``` + +This replies done (the browser mounts the variants) and then blocks until the user's choice arrives, so run it the way your harness runs a long wait: **Claude Code** in the foreground with your tool's longest timeout (600000 ms), so you are paused until the choice arrives; **Codex** in a yielded foreground exec; **Cursor** in a background terminal with notify on `"type":"(accept|discard|variant_mount_failed|exit)"`. Never pass a short `--timeout=`. While it runs there is nothing else to do: never sleep and never poll its output on a timer; a harness that backgrounds it wakes you when it returns. `{"type":"timeout"}` means the user has not chosen yet: run `live-poll` again and keep waiting. If the edit fails after the browser flipped to GENERATING, `--reply EVENT_ID error "Short reason"` (without `--then-poll`) so the bar resets. + +Then tell the user, in one line, where their variants are: *"Three [bolder] variants are live on [the pricing cards]: cycle with the floating bar's arrows, adjust the Tune knobs, and Accept the keeper."* + +Outside the replace path, read the matching live.md section before acting: `scaffold.previewMode: "svelte-component"` (Svelte previews are edited as components, and their accept is mechanical), `mode: "insert"`, `variant_mount_failed`, `steer`, `manual_edit_apply`, and any `fallback: "agent-driven"` wrap error. + +## Step 4: Accept and close + +The call from Step 3 returns the user's choice. **`discard`**: nothing to do. **`accept`**: `_acceptResult.carbonize: true` is the normal case, and the cleanup is live.md's **Required after accept**, unchanged: move the accepted variant's rules into the stylesheet that already owns the element with real selectors, bake the chosen knob values in, unwrap the element and drop every `data-impeccable-*` attribute, delete the inline `").unwrap()); + +/// Plan the bake, or say why it is not mechanical. `css_lines` is the whole +/// preview stylesheet (JSX template wrap already stripped), `restored` the +/// accepted variant at the wrapper's indentation, `element` the descriptor +/// the overlay journaled with the generate event (the anchor it saw and how +/// many elements matched it), `source_after_unwrap` the source file with the +/// variant unwrapped (to find its own `\n{v1}{v2}{v3} {{/* impeccable-variants-end {s} */}}\n \n \n \n );\n}}\n", + s = SESSION, + v1 = variant("1", false), + v2 = variant("2", true), + v3 = variant("3", true) + ) + } + + /// A project whose session journal says the overlay saw the anchor + /// `div.pricing-grid` match exactly one element. + fn project(tag: &str) -> PathBuf { + project_with(tag, Some(json!({ "tagName": "div", "id": null, "classes": ["pricing-grid"], "anchor": "div.pricing-grid", "anchorMatches": 1 }))) + } + + fn project_with(tag: &str, element: Option) -> PathBuf { + let dir = std::env::temp_dir().join(format!("impeccable-accept-bake-{}-{}", tag, std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::create_dir_all(dir.join(".impeccable/live")).unwrap(); + std::fs::write(dir.join("src/App.jsx"), app_jsx()).unwrap(); + std::fs::write(dir.join("src/styles.css"), ".pricing-grid { display: grid; gap: 20px; }\n.pricing-card { padding: 20px; }\n").unwrap(); + std::fs::write(dir.join("index.html"), "
").unwrap(); + std::fs::write(dir.join("package.json"), "{\"name\":\"t\"}").unwrap(); + let env: Env = std::env::vars().collect(); + let mut generate = json!({ "type": "generate", "id": SESSION, "count": 3, "pageUrl": "/", "action": "bolder" }); + if let Some(element) = element { + generate["element"] = element; + } + crate::session::create_live_session_store(&dir.to_string_lossy(), &env, Some(SESSION)) + .append_event(&generate) + .unwrap(); + dir + } + + fn accept(dir: &PathBuf, args: &[&str]) -> Value { + let env: Env = std::env::vars().collect(); + let (mut io, captured) = Io::captured("", dir.clone(), env); + let argv: Vec = args.iter().map(|a| a.to_string()).collect(); + let code = run(&argv, &mut io); + drop(io); + let out = String::from_utf8_lossy(&captured.stdout.borrow()).into_owned(); + let err = String::from_utf8_lossy(&captured.stderr.borrow()).into_owned(); + assert_eq!(code, 0, "stdout: {out}\nstderr: {err}"); + serde_json::from_str(out.trim()).unwrap_or_else(|e| panic!("{e}: {out}")) + } + + #[test] + fn a_bake_makes_the_variant_permanent_and_appends_its_rules() { + let dir = project("flag"); + let result = accept(&dir, &["--id", SESSION, "--variant", "2", "--bake"]); + assert_eq!(result["handled"], json!(true), "{result}"); + assert_eq!(result["baked"], json!(true), "{result}"); + assert_eq!(result["carbonize"], json!(false)); + assert_eq!(result["variant"], json!("2")); + assert_eq!(result["css"]["file"], json!("src/styles.css"), "{result}"); + assert_eq!(result["css"]["rules"], json!(2)); + assert_eq!(result["css"]["anchor"], json!("div.pricing-grid")); + assert_eq!(result["verify"]["clean"], json!(true), "{result}"); + let jsx = std::fs::read_to_string(dir.join("src/App.jsx")).unwrap(); + assert!(!jsx.contains("data-impeccable"), "{jsx}"); + assert!(!jsx.contains("impeccable-variants"), "{jsx}"); + assert!(!jsx.contains("Simple pricing\n
\n
Starter
\n
\n "), "{jsx}"); + let css = std::fs::read_to_string(dir.join("src/styles.css")).unwrap(); + assert!(css.starts_with(".pricing-grid { display: grid; gap: 20px; }\n"), "existing rules untouched: {css}"); + assert!(css.contains("/* impeccable generate ab12cd34: accepted variant 2 */"), "{css}"); + assert!(css.contains("div.pricing-grid { gap: 32px; }"), "{css}"); + assert!(css.contains("div.pricing-grid .pricing-card { border: 2px solid #111; }"), "{css}"); + assert!(!css.contains("8px") && !css.contains("gap: 0"), "other variants dropped: {css}"); + assert!(!css.contains(":scope") && !css.contains("data-impeccable"), "{css}"); + // Idempotent: the receipt answers a rerun. + let again = accept(&dir, &["--id", SESSION, "--variant", "2", "--bake"]); + assert_eq!(again["alreadyApplied"], json!(true), "{again}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn no_session_bakes_without_the_flag_the_generate_lane_included() { + let env: Env = std::env::vars().collect(); + // Plain live: no origin, no flag -> the carbonize block, as before. + let dir = project("origin"); + let plain = accept(&dir, &["--id", SESSION, "--variant", "2"]); + assert_eq!(plain["carbonize"], json!(true), "{plain}"); + assert!(plain.get("baked").is_none(), "{plain}"); + let jsx = std::fs::read_to_string(dir.join("src/App.jsx")).unwrap(); + assert!(jsx.contains("impeccable-carbonize-start"), "{jsx}"); + assert!(!std::fs::read_to_string(dir.join("src/styles.css")).unwrap().contains("32px")); + + // The generate verb's session (the journal says origin agent) carbonizes + // the same way: the agent integrates the accepted variant per live.md. + let dir2 = project("origin2"); + let cwd2 = dir2.to_string_lossy().into_owned(); + crate::session::create_live_session_store(&cwd2, &env, Some(SESSION)) + .append_event(&json!({ "type": "generate", "id": SESSION, "origin": "agent", "count": 3, "pageUrl": "/", "action": "bolder" })) + .unwrap(); + let lane = accept(&dir2, &["--id", SESSION, "--variant", "2"]); + assert_eq!(lane["carbonize"], json!(true), "{lane}"); + assert!(lane.get("baked").is_none(), "{lane}"); + assert!(std::fs::read_to_string(dir2.join("src/App.jsx")).unwrap().contains("impeccable-carbonize-start")); + // --bake is the only way in, and --no-bake still wins over it. + let dir3 = project("origin3"); + let baked = accept(&dir3, &["--id", SESSION, "--variant", "2", "--bake"]); + assert_eq!(baked["baked"], json!(true), "{baked}"); + let dir4 = project("origin4"); + let kept = accept(&dir4, &["--id", SESSION, "--variant", "2", "--bake", "--no-bake"]); + assert_eq!(kept["carbonize"], json!(true), "{kept}"); + for d in [dir, dir2, dir3, dir4] { + let _ = std::fs::remove_dir_all(&d); + } + } + + #[test] + fn a_class_anchor_the_page_showed_more_than_once_refuses_the_bake() { + // Three elements matched the anchor when Go fired (three cards from + // one JSX element, say): lasting rules on it would restyle them all. + let dir = project_with("siblings", Some(json!({ "anchor": "div.pricing-grid", "anchorMatches": 3 }))); + let result = accept(&dir, &["--id", SESSION, "--variant", "2", "--bake"]); + assert_eq!(result["carbonize"], json!(true), "{result}"); + assert!(result["bakeSkipped"].as_str().unwrap().contains("div.pricing-grid matches 3 elements"), "{result}"); + assert!(std::fs::read_to_string(dir.join("src/App.jsx")).unwrap().contains("impeccable-carbonize-start")); + assert!(!std::fs::read_to_string(dir.join("src/styles.css")).unwrap().contains("32px")); + // Without the overlay's descriptor there is nothing to verify against. + let dir2 = project_with("nodesc", None); + let result = accept(&dir2, &["--id", SESSION, "--variant", "2", "--bake"]); + assert_eq!(result["carbonize"], json!(true), "{result}"); + assert!(result["bakeSkipped"].as_str().unwrap().contains("no element descriptor"), "{result}"); + for d in [dir, dir2] { + let _ = std::fs::remove_dir_all(&d); + } + } + + #[test] + fn a_knob_session_falls_back_to_the_carbonize_block_with_the_reason() { + let dir = project("knobs"); + let src = std::fs::read_to_string(dir.join("src/App.jsx")).unwrap().replace("gap: 32px", "gap: var(--p-gap, 32px)"); + std::fs::write(dir.join("src/App.jsx"), src).unwrap(); + let result = accept(&dir, &["--id", SESSION, "--variant", "2", "--bake"]); + assert_eq!(result["carbonize"], json!(true), "{result}"); + assert!(result["bakeSkipped"].as_str().unwrap().contains("knobs"), "{result}"); + let jsx = std::fs::read_to_string(dir.join("src/App.jsx")).unwrap(); + assert!(jsx.contains("impeccable-carbonize-start"), "{jsx}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/live/src/live_boot.rs b/crates/live/src/live_boot.rs index f93ae8645..7d24d0ea8 100644 --- a/crates/live/src/live_boot.rs +++ b/crates/live/src/live_boot.rs @@ -118,7 +118,12 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { if design.is_none() { missing.push("DESIGN.md"); } - if !missing.is_empty() { + // `--allow-missing-context`: a caller that would rather start from the + // page than from an interview (the generate command) boots anyway; the + // payload names what is missing so the agent extracts the identity + // from the surface instead of running init or document mid-session. + let allow_missing_context = args.iter().any(|a| a == "--allow-missing-context"); + if !missing.is_empty() && !allow_missing_context { let payload = json!({ "ok": false, "error": "context_missing", @@ -260,7 +265,43 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { break; } let self_cmd = impeccable_context::provider::detect(&env, &cwd).self_cmd; - let payload = json!({ + // The generate lane's two opt-ins. Both are silent unless asked for, so + // a plain boot's payload is unchanged: `--dev-url` probes which dev + // server is serving this app right now (the page carrying our tag) and + // reports `devUrl`; `--allow-missing-context` reports `contextMissing` + // and a `contextNote` for the files it let the boot proceed without. + let want_dev_url = args.iter().any(|a| a == "--dev-url"); + // `--no-live-bar`: the generate lane wants no bottom bar in any tab for + // this helper's lifetime; tell the helper now, before any page connects. + let no_live_bar = args.iter().any(|a| a == "--no-live-bar"); + let live_bar_hidden = if no_live_bar { + let port = server_info.get("port").and_then(Value::as_u64).unwrap_or(0); + let token = server_info.get("token").and_then(Value::as_str).unwrap_or(""); + request_live_bar_hidden(port, token) + } else { + false + }; + let token_for_probe = match server_info.get("token") { + Some(Value::String(s)) => s.clone(), + _ => String::new(), + }; + let dev_url = if !want_dev_url || token_for_probe.is_empty() { + None + } else { + crate::dev_url::probe( + &crate::dev_url::candidates(env.get("IMPECCABLE_DEV_URL_CANDIDATES").map(String::as_str)), + &token_for_probe, + ) + }; + let context_note = if missing.is_empty() { + Value::Null + } else { + json!(format!( + "Booted without {} (--allow-missing-context). Extract the identity from the picked element's computed styles, CSS custom properties, and sibling styling; do not run init or document during this session, and do not ask for them.", + missing.join(" and ") + )) + }; + let mut payload = json!({ "ok": true, "serverPort": server_info.get("port").cloned().unwrap_or(Value::Null), "serverToken": server_info.get("token").cloned().unwrap_or(Value::Null), @@ -282,6 +323,18 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { "surfaceBriefPath": surface_brief_path, "_instructions": boot_instructions(&self_cmd), }); + if let Some(obj) = payload.as_object_mut() { + if no_live_bar { + obj.insert("liveBarHidden".into(), json!(live_bar_hidden)); + } + if want_dev_url { + obj.insert("devUrl".into(), dev_url.map(Value::String).unwrap_or(Value::Null)); + } + if allow_missing_context { + obj.insert("contextMissing".into(), json!(missing)); + obj.insert("contextNote".into(), context_note); + } + } println(io, &json_pretty(&payload)); 0 } @@ -298,6 +351,23 @@ fn run_inject(args: &[String], cwd: &str, io: &Io) -> String { /// JS: ensureServerRunning(cwd): reuse a live `server.json` record, else /// spawn `live-server --background` (part 3) and parse its output. +/// Ask the running helper to keep the overlay's global bar hidden for its +/// lifetime (`POST /live-bar`). True when the helper acknowledged. +fn request_live_bar_hidden(port: u64, token: &str) -> bool { + if port == 0 || token.is_empty() { + return false; + } + let agent = ureq::AgentBuilder::new() + .timeout(std::time::Duration::from_millis(3000)) + .build(); + agent + .post(&format!("http://127.0.0.1:{}/live-bar", port)) + .set("Content-Type", "application/json") + .send_string(&json!({ "token": token, "hidden": true }).to_string()) + .map(|res| res.status() == 200) + .unwrap_or(false) +} + fn ensure_server_running(cwd: &str, io: &Io) -> Option { if let Some((info, _)) = read_live_server_info(cwd, &io.env) { if let Some(pid) = info.pid { diff --git a/crates/live/src/live_generate.rs b/crates/live/src/live_generate.rs new file mode 100644 index 000000000..b3aa4880f --- /dev/null +++ b/crates/live/src/live_generate.rs @@ -0,0 +1,891 @@ +//! `impeccable live-generate`: agent-initiated element targeting for the +//! `generate` command. +//! +//! Asks the live overlay to find an element by CSS selector, scroll to it, +//! enter the picked state, and fire the normal Go pipeline with the given +//! action and count. On success the browser starts a standard generate +//! session and the verb collects that session's `generate` event into its +//! own output, so the agent's next move is the edit. With `--boot` it runs +//! the lane's boot itself first (reusing a running helper), and with +//! `--open` it opens the dev URL in the browser when no page is connected: +//! one command from a cold project to a leased generate event. + +use crate::live_resume::self_cmd; +use crate::paths::read_live_server_info; +use crate::roots::enter_live_root; +use crate::util::println; +use crate::vocabulary::VISUAL_ACTIONS; +use impeccable_common::Io; +use serde_json::{json, Map, Value}; +use std::time::{Duration, Instant}; + +const HELP: &str = "Usage: impeccable live-generate --selector [--text ] [--index ] [--action ] [--count ] [--prompt ] [--dry-run] [--wait-for-browser ] [--no-live-bar] [--boot] [--open] [--target ] + +Flags: + --boot optional; run the generate lane's boot first (impeccable live + --allow-missing-context --dev-url --no-live-bar, with --target + when given), reusing a running helper; the boot's context and + devUrl ride along in the output as `boot` + --open optional; when no page with the overlay is connected, open the + dev URL in the browser (IMPECCABLE_BROWSER, then `browser` in + .impeccable/config.local.json or config.json, then BROWSER, then + the platform opener) and wait for it (60 s unless + --wait-for-browser says otherwise). On a harness with its own + browser (Cursor, Claude Code) the flag is ignored unless + IMPECCABLE_BROWSER or the config's `browser` names one: the + page comes from the harness browser, never a second window + --target optional; the file that renders the element (the boot's --target) + --dev-url optional; the dev server you already know (a server the + harness runs, a tab on the app, the user's message); probed + first, reported as devUrl either way + --selector required; resolved with document.querySelectorAll + --text optional; keeps only matches whose textContent contains it + --index optional; 1-based pick among the remaining matches + --action optional; one of the live action vocabulary (default: impeccable) + --count optional; variants to request, 1-8 (default: 3) + --prompt optional; freeform direction, same as typing before Go + --dry-run optional; resolve and report without starting anything + --wait-for-browser optional; poll the helper until a page with the + overlay connects (or the budget runs out) before sending + the target. + +With no page connected and neither --open nor --wait-for-browser, the verdict +is browser_needed with devUrl and the harness's way to open it (Cursor +browser_navigate, Claude Code's Browser pane, Codex: --open or the user), so no +second browser is ever launched behind a harness that has one. + +On success the output carries the session's generate event as `event` (already +leased, with its _instructions), so the next command is the edit, then +`live-poll --reply done --file --then-poll` for the accept. +"; + +/// Client-side cap just above the server's 15s hold, so a hung helper still +/// fails fast. +const REQUEST_TIMEOUT_MS: u64 = 20_000; + +struct Flags { + values: Map, + dry_run: bool, + no_live_bar: bool, + boot: bool, + open: bool, +} + +fn parse_flags(argv: &[String]) -> Result { + let mut values = Map::new(); + let mut dry_run = false; + let mut no_live_bar = false; + let mut boot = false; + let mut open = false; + let mut i = 0; + while i < argv.len() { + let arg = &argv[i]; + if !arg.starts_with("--") { + i += 1; + continue; + } + let key = &arg[2..]; + if key == "dry-run" { + dry_run = true; + i += 1; + continue; + } + if key == "no-live-bar" { + no_live_bar = true; + i += 1; + continue; + } + if key == "boot" { + boot = true; + i += 1; + continue; + } + if key == "open" { + open = true; + i += 1; + continue; + } + // The boot's own opt-in, tolerated here so a caller that spells the + // lane's boot flags on this verb is not refused. + if key == "allow-missing-context" { + i += 1; + continue; + } + // `--dev-url` alone is the boot's probe flag (tolerated); with a + // value it is the dev server the caller already knows. + if key == "dev-url" { + match argv.get(i + 1) { + Some(v) if !v.starts_with("--") => { + values.insert(key.to_string(), json!(v)); + i += 2; + } + _ => i += 1, + } + continue; + } + match argv.get(i + 1) { + Some(v) if !v.starts_with("--") => { + values.insert(key.to_string(), json!(v)); + i += 2; + } + _ => { + return Err(json!({ "ok": false, "error": "missing_flag_value", "flag": arg })); + } + } + } + Ok(Flags { + values, + dry_run, + no_live_bar, + boot, + open, + }) +} + +fn flag<'a>(flags: &'a Flags, key: &str) -> Option<&'a str> { + flags.values.get(key).and_then(Value::as_str) +} + +/// JS `Number(v)` then `Number.isInteger`: an integer literal only. +fn int_flag(v: &str) -> Option { + let t = v.trim(); + if t.is_empty() { + return None; + } + if let Ok(i) = t.parse::() { + return Some(i); + } + t.parse::() + .ok() + .filter(|f| f.is_finite() && f.fract() == 0.0) + .map(|f| f as i64) +} + +fn print_json(io: &mut Io, v: &Value) { + println(io, &serde_json::to_string_pretty(v).unwrap_or_default()); +} + +fn fail(io: &mut Io, v: Value) -> i32 { + print_json(io, &v); + 1 +} + +/// The follow-up the agent runs after each verdict. Like the poll loop's +/// `_instructions`, regenerated locally from the verdict, never taken from +/// the wire. +fn instructions_for(result: &Map, self_cmd: &str) -> Option { + let s = |k: &str| result.get(k).and_then(Value::as_str).unwrap_or("").to_string(); + let n = |k: &str| result.get(k).and_then(Value::as_i64).unwrap_or(0); + if result.get("ok").and_then(Value::as_bool) == Some(true) { + if result.get("dryRun").and_then(Value::as_bool) == Some(true) { + let el = result.get("element").and_then(Value::as_object); + let tag = el.and_then(|e| e.get("tag")).and_then(Value::as_str).unwrap_or(""); + let id = el + .and_then(|e| e.get("id")) + .and_then(Value::as_str) + .filter(|i| !i.is_empty()) + .map(|i| format!("#{}", i)) + .unwrap_or_default(); + return Some(format!( + "Dry run only: the selector resolves to one element ({}{}) and no session was started. Rerun without --dry-run to generate.", + tag, id + )); + } + let reply = format!("{} live-poll --reply {} done --file --then-poll", self_cmd, s("sessionId")); + if result.get("event").map(|e| e.is_object()).unwrap_or(false) { + return Some(format!( + "Session {} started: the browser scrolled to the target and fired Go (action \"{}\", count {}). Its generate event is in this output as `event`, already leased: handle it exactly per live.md's Handle generate, as event._instructions say (the action's reference, section 4 planning, knobs per section 7, all variants in ONE edit at the scaffold's splice). When the edit is written, reply and wait for the user's choice in one call: {}. The accept it returns carbonizes like plain live's: finish live.md's Required after accept, run live-complete, then stop the helper.", + s("sessionId"), s("action"), n("count"), reply + )); + } + return Some(format!( + "Session {} started: the browser scrolled to the target and fired Go (action \"{}\", count {}). Its generate event had not arrived yet: run {} live-poll to collect it and handle it exactly per live.md's Handle generate, as its _instructions say; then reply and wait for the accept in one call: {}.", + s("sessionId"), s("action"), n("count"), self_cmd, reply + )); + } + let text = match s("error").as_str() { + "dev_server_gone" => format!( + "The dev server at {} stopped answering while this command waited for the page, so no page can load the overlay from it (a server another chat or session started dies with it). {}", + s("devUrl"), + start_dev_server_hint(&s("harness")) + ), + "no_dev_server" => format!("No dev server is serving this app: none of the usual ports answered with the page carrying the helper's tag (pass --dev-url when you know where it runs). {}", start_dev_server_hint(&s("harness"))), + "browser_needed" => format!("{}The helper is up and no page is connected yet. {} Then rerun this exact command with --wait-for-browser 60000.", open_ignored_note(result), open_in_harness_hint(&s("harness"), &s("devUrl"), self_cmd)), + "browser_open_failed" => format!("The browser could not be launched ({}). Open {} yourself with your harness browser tool, or give the user the URL, then rerun this command with --wait-for-browser 120000.", s("detail"), s("url")), + "no_browser_connected" if result.get("opened").map(|o| o.is_object()).unwrap_or(false) => format!("The page was opened in the browser but no overlay connected within {} ms. The dev server may still be compiling, or the page does not carry the injected tag (check pageFiles). Reload the page, then rerun this command.", n("waitedMs")), + "no_browser_connected" if !s("devUrl").is_empty() => format!("{}No page with the live overlay connected within {} ms. {} Then rerun this exact command with --wait-for-browser 60000.", open_ignored_note(result), n("waitedMs"), open_in_harness_hint(&s("harness"), &s("devUrl"), self_cmd)), + "no_browser_connected" => "No page with the live overlay is connected. Open the app URL that serves a pageFiles entry yourself with your harness browser tool, then rerun this command. Only when no browser tool exists: give the user the URL and rerun with --wait-for-browser 120000 so the command fires as soon as they open the page.".to_string(), + "browser_timeout" => "The overlay did not answer in time, and no session was started for this request (a Go that lands late is refused). The page may be mid-reload: reload the app page, then rerun this command.".to_string(), + "invalid_selector" => "The selector is not valid CSS. Fix the selector syntax and rerun.".to_string(), + "no_match" => { + if n("rawMatchCount") > 0 { + format!("The selector hit {} node(s) but none is pickable (too small, chrome, or filtered by --text). Target a larger element or adjust --text.", n("rawMatchCount")) + } else { + "The selector matched nothing on the open page. Derive a better selector from the page source (an id, a unique class, or a landmark), or add --text with a snippet of the element's visible text.".to_string() + } + } + "ambiguous" => format!("The selector matched {} elements. Either target their common container instead, or disambiguate with --text \"\" or --index <1-based position>. The candidates are listed in this output.", n("matchCount")), + "index_out_of_range" => format!("--index is out of range: only {} match(es). Use an index from 1 to {}.", n("matchCount"), n("matchCount")), + "busy" => { + if s("reason") == "agent_target_in_flight" { + "That tab is already acting on another generate request. Handle that request's pending event in your poll loop, or wait for its session to end, then rerun.".to_string() + } else { + format!("A live session is already mid-flight (browser state {}). Let the user finish or discard it in the browser, or handle the pending event in your poll loop, then rerun.", s("state")) + } + } + "go_failed" => format!("The overlay could not start generation from the picked state (browser state {}). Reload the app page and rerun this command.", s("state")), + "server_stopping" => format!("The live helper server is shutting down. Re-run the live boot ({} live), reopen the page, then rerun this command.", self_cmd), + _ => return None, + }; + Some(text) +} + +/// Said first when `--open` was passed on a harness with its own browser. +fn open_ignored_note(result: &Map) -> &'static str { + if result.get("openIgnored").is_some() { + "--open was ignored: this harness has its own browser, and a second window is exactly what the lane avoids. " + } else { + "" + } +} + +/// How this harness opens a page: its own browser when it has one (no second +/// browser behind it), the system browser or the user otherwise. +fn open_in_harness_hint(harness: &str, dev_url: &str, self_cmd: &str) -> String { + let _ = self_cmd; + match harness { + "cursor" => format!("Open {} with browser_navigate (Cursor's browser; it reuses the tab already on that origin).", dev_url), + "claude-code" => format!("Open {} in the Browser pane: navigate the tab already on that origin (tabs_context lists them), or preview_start with that URL when the pane is closed.", dev_url), + "codex" => format!("Codex has no browser tool: rerun this command with --open (the system browser opens {}), or give the user that URL.", dev_url), + _ => format!("Open {} with your harness's browser tool, reusing a tab already on that origin; without one, rerun this command with --open (the system browser), or give the user that URL.", dev_url), + } +} + +/// Where a dev server gets started in this harness, so the one already +/// running there is the one the page comes from. +fn start_dev_server_hint(harness: &str) -> String { + match harness { + "claude-code" => "Start it the way the harness runs servers (preview_start with the project's dev configuration, or the dev script in a background shell), wait for its URL, then rerun this exact command with --dev-url ; never kill or restart that server afterwards.".to_string(), + "cursor" => "Start the project's dev script in a background terminal (npm run dev or the framework's equivalent), wait for it to print its URL, then rerun this exact command with --dev-url ; never kill or restart that server afterwards.".to_string(), + _ => "Start the project's dev script in a background terminal (npm run dev or the framework's equivalent), wait for it to print its URL, then rerun this exact command with --dev-url ; never kill or restart that server afterwards.".to_string(), + } +} + +fn server_died(self_cmd: &str, detail: Option, waiting: bool) -> Value { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + v.insert("error".into(), json!("server_unreachable")); + if let Some(d) = detail { + v.insert("detail".into(), json!(d)); + } + let text = if waiting { + format!("The recorded live server did not answer while waiting for a browser; it likely died. Re-run the live boot ({} live), reopen the app page, then rerun this command.", self_cmd) + } else { + format!("The recorded live server did not answer; it likely died. Re-run the live boot ({} live), reopen the app page, then rerun this command.", self_cmd) + }; + v.insert("_instructions".into(), json!(text)); + Value::Object(v) +} + +fn server_not_running(self_cmd: &str) -> Value { + json!({ + "ok": false, + "error": "server_not_running", + "_instructions": format!("No live helper server is recorded for this project. Run the live boot first ({} live), open the app URL that serves a pageFiles entry, then rerun this command.", self_cmd), + }) +} + +/// The lane's boot flags, run in-process from the caller's original cwd +/// (`--target` is a path relative to it). Ok: the boot payload. Err: a +/// verdict to print, exit 1. +fn run_boot(args: &[String], original_cwd: &std::path::Path, io: &Io, dev_url_hint: Option<&str>) -> Result, Value> { + let mut boot_args: Vec = Vec::new(); + if let Some(i) = args.iter().position(|a| a == "--target") { + if let Some(t) = args.get(i + 1).filter(|t| !t.starts_with("--")) { + boot_args.push("--target".into()); + boot_args.push(t.clone()); + } + } + for a in args { + if let Some(t) = a.strip_prefix("--target=") { + boot_args.push("--target".into()); + boot_args.push(t.to_string()); + } + } + boot_args.push("--allow-missing-context".into()); + boot_args.push("--dev-url".into()); + boot_args.push("--no-live-bar".into()); + let mut env = io.env.clone(); + if let Some(hint) = dev_url_hint { + // The known server first, the usual ports behind it, unless the + // caller already narrowed the list. + if !env.contains_key("IMPECCABLE_DEV_URL_CANDIDATES") { + let mut list = vec![hint.trim_end_matches('/').to_string() + "/"]; + list.extend(crate::dev_url::candidates(None)); + env.insert("IMPECCABLE_DEV_URL_CANDIDATES".into(), list.join(",")); + } + } + let (mut child, captured) = Io::captured("", original_cwd.to_path_buf(), env); + let code = crate::live_boot::run(&boot_args, &mut child); + let out = String::from_utf8_lossy(&captured.stdout.borrow()).into_owned(); + let err = String::from_utf8_lossy(&captured.stderr.borrow()).into_owned(); + let payload: Option> = serde_json::from_str::(out.trim()) + .ok() + .and_then(|v| v.as_object().cloned()); + let Some(mut payload) = payload else { + return Err(json!({ + "ok": false, + "error": "boot_failed", + "exitCode": code, + "detail": if err.trim().is_empty() { out.trim().to_string() } else { err.trim().to_string() }, + "_instructions": "The live boot did not produce a verdict. Run `impeccable live --allow-missing-context --dev-url --no-live-bar` on its own, read its output, and fix what it names before rerunning this command.", + })); + }; + if payload.get("ok").and_then(Value::as_bool) != Some(true) { + let error = payload.get("error").and_then(Value::as_str).unwrap_or("").to_string(); + let text = match error.as_str() { + "config_missing" | "config_invalid" => "The live config is missing or invalid: follow reference/live-setup.md to create .impeccable/live/config.json, then rerun this command.", + "target_selection_required" => "Several apps live here: ask the user which one, then rerun this command with --target .", + "context_missing" => "The boot refused for missing context even though this verb asks it to proceed; rerun with the boot's own flags to see why.", + _ => "The boot refused; its fields say why. Fix that, then rerun this command.", + }; + payload.insert("ok".into(), json!(false)); + payload.insert("bootError".into(), json!(error)); + payload.insert("_instructions".into(), json!(text)); + return Err(Value::Object(payload)); + } + Ok(payload) +} + +/// What the verdict repeats from the boot: the context the edit needs and +/// where the page is. Plumbing (token, roots, drift) stays out. +fn boot_summary(boot: &Map) -> Value { + let mut m = Map::new(); + for key in [ + "devUrl", "pageFiles", "projectRoot", "targetPath", "liveBarHidden", "contextMissing", "contextNote", + "hasProduct", "product", "productPath", "hasDesign", "design", "designPath", "hasSurfaceBrief", + "surfaceBrief", "surfaceBriefPath", + ] { + if let Some(v) = boot.get(key) { + m.insert(key.into(), v.clone()); + } + } + Value::Object(m) +} + +/// Collect the session's own generate event (`GET /poll?types=generate&id=`) +/// so the caller's next move is the edit. The event is leased exactly as a +/// poll would lease it; nothing else in the queue is touched. +fn fetch_generate_event(port: i64, token: &str, session_id: &str, budget: Duration, self_cmd: &str) -> Option { + let deadline = Instant::now() + budget; + while Instant::now() < deadline { + let remaining = deadline.saturating_duration_since(Instant::now()).as_millis() as u64; + let slice = remaining.clamp(1_000, 5_000); + let url = format!( + "http://127.0.0.1:{}/poll?token={}&timeout={}&leaseMs={}&types=generate&id={}", + port, + crate::live_poll::form_encode(token), + slice, + crate::live_poll::DEFAULT_EVENT_LEASE_MS, + crate::live_poll::form_encode(session_id) + ); + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_millis(slice + 30_000)) + .build(); + let Ok(res) = agent.get(&url).call() else { return None }; + let Ok(mut event) = res.into_json::() else { return None }; + match event.get("type").and_then(Value::as_str) { + Some("generate") => { + if let Some(obj) = event.as_object_mut() { + match crate::instructions::instructions_for_event(obj, self_cmd) { + Some(text) if !text.is_empty() => { + obj.insert("_instructions".into(), json!(text)); + } + _ => { + obj.remove("_instructions"); + } + } + } + return Some(event); + } + Some("timeout") => continue, + _ => return None, + } + } + None +} + +/// How long the verb waits for the generate event after a started session. +const EVENT_BUDGET_MS: u64 = 20_000; +/// The wait `--open` implies when `--wait-for-browser` was not given. +const OPEN_WAIT_MS: u64 = 60_000; + +pub fn run(args: &[String], io: &mut Io) -> i32 { + if args.iter().any(|a| a == "--help" || a == "-h") { + println(io, HELP); + return 0; + } + let flags_probe = match parse_flags(args) { + Ok(f) => f, + Err(v) => return fail(io, v), + }; + // `--boot` runs before the root switch: the boot writes the roots + // manifest the switch reads, and reads --target relative to this cwd. + let original_cwd = io.cwd.clone(); + let dev_url_hint: Option = flag(&flags_probe, "dev-url").map(str::trim).filter(|u| !u.is_empty()).map(str::to_string); + let mut boot: Option> = None; + if flags_probe.boot { + match run_boot(args, &original_cwd, io, dev_url_hint.as_deref()) { + Ok(b) => boot = Some(b), + Err(v) => return fail(io, v), + } + } + let mut argv: Vec = args.to_vec(); + if let Err(code) = enter_live_root(&mut argv, io) { + return code; + } + let cwd = io.cwd.to_string_lossy().into_owned(); + let env = io.env.clone(); + let me = self_cmd(io); + let flags = match parse_flags(&argv) { + Ok(f) => f, + Err(v) => return fail(io, v), + }; + + let selector = flag(&flags, "selector").map(str::trim).unwrap_or("").to_string(); + if selector.is_empty() { + return fail(io, json!({ + "ok": false, + "error": "selector_required", + "_instructions": "Pass --selector with a CSS selector for the element to target. Derive it from the page source: prefer an id, a unique class, or a landmark section, and add --text \"\" when the class repeats.", + })); + } + let action = flag(&flags, "action").unwrap_or("impeccable").to_string(); + if !VISUAL_ACTIONS.contains(&action.as_str()) { + return fail(io, json!({ + "ok": false, + "error": "invalid_action", + "action": action, + "validActions": VISUAL_ACTIONS, + "_instructions": "Map the request wording onto the closest listed action (bold -> bolder, quiet/calmer -> quieter, simplify -> distill). When no action fits, use --action impeccable and carry the wording via --prompt.", + })); + } + let count = match flag(&flags, "count") { + None => 3, + Some(raw) => match int_flag(raw) { + Some(c) if (1..=8).contains(&c) => c, + _ => { + return fail(io, json!({ "ok": false, "error": "invalid_count", "count": raw, "_instructions": "Pass --count as an integer from 1 to 8." })); + } + }, + }; + let index = match flag(&flags, "index") { + None => None, + Some(raw) => match int_flag(raw) { + Some(i) if i >= 1 => Some(i), + _ => { + return fail(io, json!({ "ok": false, "error": "invalid_index", "index": raw, "_instructions": "Pass --index as a 1-based integer position among the matches." })); + } + }, + }; + let mut wait_for_browser_ms = match flag(&flags, "wait-for-browser") { + None => 0, + Some(raw) => match int_flag(raw) { + Some(ms) if ms >= 1 => ms as u64, + _ => { + return fail(io, json!({ "ok": false, "error": "invalid_wait", "wait": raw, "_instructions": "Pass --wait-for-browser as a positive integer of milliseconds, e.g. --wait-for-browser 120000." })); + } + }, + }; + + let Some((info, _)) = read_live_server_info(&cwd, &env) else { + return fail(io, server_not_running(&me)); + }; + let port = info.raw.get("port").and_then(Value::as_i64); + let token = info.raw.get("token").and_then(Value::as_str).map(str::to_string); + let (Some(port), Some(token)) = (port, token) else { + return fail(io, server_not_running(&me)); + }; + let harness = impeccable_context::provider::detect(&env, &cwd).id; + // Every verdict from here on repeats what the boot found, so a refusal + // still hands the caller its context and dev URL. + let with_boot = |mut v: Map| -> Value { + if let Some(b) = &boot { + v.insert("boot".into(), boot_summary(b)); + } + v.insert("harness".into(), json!(harness)); + Value::Object(v) + }; + + // Where the page is: the boot's probe, else a probe led by the caller's + // hint, else the hint itself (a server the harness runs that answers + // without our tag yet, before its first reload). + let resolve_dev_url = |boot: &Option>| -> (Option, bool) { + if let Some(u) = boot.as_ref().and_then(|b| b.get("devUrl")).and_then(Value::as_str).filter(|u| !u.is_empty()) { + return (Some(u.to_string()), true); + } + let mut candidates: Vec = Vec::new(); + if let Some(h) = &dev_url_hint { + candidates.push(h.trim_end_matches('/').to_string() + "/"); + } + candidates.extend(crate::dev_url::candidates(env.get("IMPECCABLE_DEV_URL_CANDIDATES").map(String::as_str))); + if let Some(u) = crate::dev_url::probe(&candidates, &token) { + return (Some(u), true); + } + (dev_url_hint.clone(), false) + }; + + // A harness with its own browser never gets a second window from this + // verb: `--open` there is ignored unless the user chose a browser + // explicitly (IMPECCABLE_BROWSER or the config's `browser`; the generic + // BROWSER variable is not that choice). + let harness_has_browser = matches!(harness.as_str(), "cursor" | "claude-code"); + let open_ignored = flags.open && harness_has_browser && crate::browser_open::explicit_browser(&cwd, &env).is_none(); + let open = flags.open && !open_ignored; + let with_open_note = |mut v: Map| -> Map { + if open_ignored { + v.insert("openIgnored".into(), json!("harness browser")); + } + v + }; + + // Nothing connected, nothing asked to open, nothing to wait for: the + // caller opens the page itself (its harness's browser, never a second + // one behind it) and comes back. + let mut opened: Option = None; + if !open && wait_for_browser_ms == 0 && !flags.dry_run { + let Some(status) = crate::server::fetch_status(port, &token) else { + return fail(io, server_died(&me, None, false)); + }; + if status.get("connectedClients").and_then(Value::as_i64).unwrap_or(0) == 0 { + let (dev_url, verified) = resolve_dev_url(&boot); + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + if let Some(u) = dev_url { + v.insert("error".into(), json!("browser_needed")); + v.insert("devUrl".into(), json!(u)); + v.insert("devUrlVerified".into(), json!(verified)); + } else { + v.insert("error".into(), json!("no_dev_server")); + } + v.insert("harness".into(), json!(harness)); + let mut v = with_open_note(v); + let text = instructions_for(&v, &me).unwrap_or_default(); + v.insert("_instructions".into(), json!(text)); + return fail(io, with_boot(v)); + } + } + + // `--open`: hand the page to the browser when nothing is connected yet. + if open { + let Some(status) = crate::server::fetch_status(port, &token) else { + return fail(io, server_died(&me, None, false)); + }; + let connected = status.get("connectedClients").and_then(Value::as_i64).unwrap_or(0) > 0; + if !connected { + let (dev_url, _) = resolve_dev_url(&boot); + let Some(url) = dev_url else { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + v.insert("error".into(), json!("no_dev_server")); + v.insert("harness".into(), json!(harness)); + let text = instructions_for(&v, &me).unwrap_or_default(); + v.insert("_instructions".into(), json!(text)); + return fail(io, with_boot(v)); + }; + match crate::browser_open::open_url(&url, &cwd, &env) { + Ok(via) => { + opened = Some(json!({ "url": url, "via": via })); + if wait_for_browser_ms == 0 { + wait_for_browser_ms = OPEN_WAIT_MS; + } + } + Err(detail) => { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + v.insert("error".into(), json!("browser_open_failed")); + v.insert("url".into(), json!(url)); + v.insert("detail".into(), json!(detail)); + let text = instructions_for(&v, &me).unwrap_or_default(); + v.insert("_instructions".into(), json!(text)); + return fail(io, with_boot(v)); + } + } + } + } + + if wait_for_browser_ms > 0 { + let deadline = Instant::now() + Duration::from_millis(wait_for_browser_ms); + // No page can load the overlay from a dead dev server, so the wait + // watches the one this command knows (the URL it opened, else the + // boot's or the caller's) and ends the moment it stops answering, + // instead of running out the budget on a page that will never + // reload. Two misses in a row, so a server mid-restart gets a grace. + let watched_dev_url: Option = opened + .as_ref() + .and_then(|o| o.get("url")) + .and_then(Value::as_str) + .map(String::from) + .or_else(|| resolve_dev_url(&boot).0); + let started = Instant::now(); + let mut ticks: u32 = 0; + let mut dev_misses: u32 = 0; + loop { + let Some(status) = crate::server::fetch_status(port, &token) else { + return fail(io, server_died(&me, None, true)); + }; + if status.get("connectedClients").and_then(Value::as_i64).unwrap_or(0) > 0 { + break; + } + if let Some(url) = &watched_dev_url { + ticks += 1; + if ticks % 3 == 0 { + if crate::dev_url::answers(url) { + dev_misses = 0; + } else { + dev_misses += 1; + } + if dev_misses >= 2 { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + v.insert("error".into(), json!("dev_server_gone")); + v.insert("devUrl".into(), json!(url)); + v.insert("waitedMs".into(), json!(started.elapsed().as_millis() as u64)); + v.insert("harness".into(), json!(harness)); + let mut v = with_open_note(v); + let text = instructions_for(&v, &me).unwrap_or_default(); + v.insert("_instructions".into(), json!(text)); + return fail(io, with_boot(v)); + } + } + } + if Instant::now() >= deadline { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + v.insert("error".into(), json!("no_browser_connected")); + v.insert("waitedMs".into(), json!(wait_for_browser_ms)); + if let Some(o) = &opened { + v.insert("opened".into(), o.clone()); + } else if let (Some(u), _) = resolve_dev_url(&boot) { + v.insert("devUrl".into(), json!(u)); + } + v.insert("harness".into(), json!(harness)); + let mut v = with_open_note(v); + let text = instructions_for(&v, &me).unwrap_or_default(); + v.insert("_instructions".into(), json!(text)); + return fail(io, with_boot(v)); + } + std::thread::sleep(Duration::from_millis(1_000)); + } + } + + let mut body = Map::new(); + body.insert("token".into(), json!(token)); + body.insert("selector".into(), json!(selector)); + body.insert("action".into(), json!(action)); + body.insert("count".into(), json!(count)); + if let Some(text) = flag(&flags, "text").filter(|t| !t.is_empty()) { + body.insert("text".into(), json!(text)); + } + if let Some(i) = index { + body.insert("index".into(), json!(i)); + } + if let Some(prompt) = flag(&flags, "prompt").filter(|p| !p.is_empty()) { + body.insert("prompt".into(), json!(prompt)); + } + if flags.dry_run { + body.insert("dryRun".into(), json!(true)); + } + if flags.no_live_bar || flags.boot { + body.insert("hideLiveBar".into(), json!(true)); + } + + let url = format!("http://127.0.0.1:{}/agent-target", port); + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_millis(REQUEST_TIMEOUT_MS)) + .build(); + let sent = agent + .post(&url) + .set("Content-Type", "application/json") + .send_string(&serde_json::to_string(&Value::Object(body)).unwrap_or_default()); + let (status, result) = match sent { + Ok(res) => { + let status = res.status(); + match res.into_json::() { + Ok(v) => (status, v), + Err(_) => return fail(io, json!({ "ok": false, "error": "bad_server_response", "status": status })), + } + } + Err(ureq::Error::Status(status, res)) => match res.into_json::() { + Ok(v) => (status, v), + Err(_) => return fail(io, json!({ "ok": false, "error": "bad_server_response", "status": status })), + }, + Err(ureq::Error::Transport(t)) => { + let detail = t.to_string(); + let lower = detail.to_ascii_lowercase(); + if lower.contains("timed out") || lower.contains("timeout") { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + v.insert("error".into(), json!("request_timeout")); + v.insert("detail".into(), json!(detail)); + let mut probe = Map::new(); + probe.insert("error".into(), json!("browser_timeout")); + let text = instructions_for(&probe, &me).unwrap_or_default(); + v.insert("_instructions".into(), json!(text)); + return fail(io, Value::Object(v)); + } + return fail(io, server_died(&me, Some(detail), false)); + } + }; + let mut fields = result.as_object().cloned().unwrap_or_default(); + if !(200..300).contains(&status) { + let mut v = Map::new(); + v.insert("ok".into(), json!(false)); + let code = fields + .get("error") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| format!("http_{}", status)); + v.insert("error".into(), json!(code)); + for (k, val) in fields { + if k != "ok" && k != "error" { + v.insert(k, val); + } + } + return fail(io, with_boot(v)); + } + let ok = fields.get("ok").and_then(Value::as_bool) == Some(true); + let dry_run = fields.get("dryRun").and_then(Value::as_bool) == Some(true); + if let Some(b) = &boot { + fields.insert("boot".into(), boot_summary(b)); + } + if let Some(o) = &opened { + fields.insert("opened".into(), o.clone()); + } + if ok && !dry_run { + let session_id = fields.get("sessionId").and_then(Value::as_str).map(str::to_string); + if let Some(sid) = session_id.filter(|s| !s.is_empty()) { + let event = fetch_generate_event(port, &token, &sid, Duration::from_millis(EVENT_BUDGET_MS), &me); + fields.insert("event".into(), event.unwrap_or(Value::Null)); + } + } + if let Some(text) = instructions_for(&fields, &me) { + fields.insert("_instructions".into(), json!(text)); + } + print_json(io, &Value::Object(fields)); + if ok { + 0 + } else { + 1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn busy(reason: &str) -> Map { + let mut m = Map::new(); + m.insert("ok".into(), json!(false)); + m.insert("error".into(), json!("busy")); + m.insert("state".into(), json!("CONFIGURING")); + m.insert("reason".into(), json!(reason)); + m + } + + #[test] + fn no_live_bar_is_a_boolean_flag() { + let flags = parse_flags(&["--selector".to_string(), "h1".to_string(), "--no-live-bar".to_string(), "--count".to_string(), "3".to_string()]).unwrap(); + assert!(flags.no_live_bar); + assert_eq!(flags.values.get("selector").and_then(Value::as_str), Some("h1")); + assert_eq!(flags.values.get("count").and_then(Value::as_str), Some("3")); + assert!(!parse_flags(&["--selector".to_string(), "h1".to_string()]).unwrap().no_live_bar); + } + + #[test] + fn dev_url_takes_a_value_and_still_works_bare() { + let with = parse_flags(&["--dev-url".to_string(), "http://127.0.0.1:5173/".to_string(), "--selector".to_string(), "h1".to_string()]).unwrap(); + assert_eq!(with.values.get("dev-url").and_then(Value::as_str), Some("http://127.0.0.1:5173/")); + let bare = parse_flags(&["--dev-url".to_string(), "--selector".to_string(), "h1".to_string()]).unwrap(); + assert!(bare.values.get("dev-url").is_none()); + assert_eq!(bare.values.get("selector").and_then(Value::as_str), Some("h1")); + } + + #[test] + fn a_dev_server_that_dies_mid_wait_gets_the_start_it_instructions() { + let mut m = Map::new(); + m.insert("error".into(), json!("dev_server_gone")); + m.insert("devUrl".into(), json!("http://127.0.0.1:5173/")); + m.insert("harness".into(), json!("cursor")); + let text = instructions_for(&m, "impeccable").unwrap(); + assert!(text.contains("stopped answering"), "{text}"); + assert!(text.contains("http://127.0.0.1:5173/"), "{text}"); + assert!(text.contains("background terminal") && text.contains("--dev-url"), "{text}"); + } + + #[test] + fn browser_needed_names_the_harness_browser_and_never_a_second_one() { + let mut m = Map::new(); + m.insert("ok".into(), json!(false)); + m.insert("error".into(), json!("browser_needed")); + m.insert("devUrl".into(), json!("http://127.0.0.1:5173/")); + m.insert("harness".into(), json!("cursor")); + let cursor = instructions_for(&m, "impeccable").unwrap(); + assert!(cursor.contains("browser_navigate"), "{cursor}"); + assert!(cursor.contains("--wait-for-browser 60000"), "{cursor}"); + assert!(!cursor.contains("--open"), "a harness with a browser is never told to open a second one: {cursor}"); + m.insert("harness".into(), json!("claude-code")); + let claude = instructions_for(&m, "impeccable").unwrap(); + assert!(claude.contains("Browser pane") && claude.contains("navigate") && claude.contains("preview_start"), "{claude}"); + assert!(!claude.contains("--open"), "{claude}"); + m.insert("harness".into(), json!("codex")); + let codex = instructions_for(&m, "impeccable").unwrap(); + assert!(codex.contains("--open") && codex.contains("give the user"), "{codex}"); + m.insert("harness".into(), json!("source")); + let other = instructions_for(&m, "impeccable").unwrap(); + assert!(other.contains("browser tool") && other.contains("--open"), "{other}"); + } + + #[test] + fn an_ignored_open_says_so_before_the_harness_hint() { + let mut m = Map::new(); + m.insert("ok".into(), json!(false)); + m.insert("error".into(), json!("browser_needed")); + m.insert("devUrl".into(), json!("http://127.0.0.1:5173/")); + m.insert("harness".into(), json!("cursor")); + m.insert("openIgnored".into(), json!("harness browser")); + let text = instructions_for(&m, "impeccable").unwrap(); + assert!(text.starts_with("--open was ignored"), "{text}"); + assert!(text.contains("browser_navigate"), "{text}"); + } + + #[test] + fn a_missing_dev_server_points_at_the_harness_way_to_start_one() { + let mut m = Map::new(); + m.insert("ok".into(), json!(false)); + m.insert("error".into(), json!("no_dev_server")); + m.insert("harness".into(), json!("claude-code")); + let text = instructions_for(&m, "impeccable").unwrap(); + assert!(text.contains("preview_start") && text.contains("--dev-url"), "{text}"); + m.insert("harness".into(), json!("cursor")); + let text = instructions_for(&m, "impeccable").unwrap(); + assert!(text.contains("background terminal") && text.contains("--dev-url"), "{text}"); + } + + #[test] + fn timeout_instructions_promise_no_stray_session() { + let mut m = Map::new(); + m.insert("ok".into(), json!(false)); + m.insert("error".into(), json!("browser_timeout")); + let text = instructions_for(&m, "impeccable").unwrap(); + assert!(text.contains("no session was started"), "{text}"); + } + + #[test] + fn busy_instructions_tell_the_agent_whose_session_is_in_the_way() { + let own = instructions_for(&busy("agent_target_in_flight"), "impeccable").unwrap(); + assert!(own.contains("already acting on another generate request"), "{own}"); + let user = instructions_for(&busy("session_active"), "impeccable").unwrap(); + assert!(user.contains("browser state CONFIGURING"), "{user}"); + } +} diff --git a/crates/live/src/live_poll.rs b/crates/live/src/live_poll.rs index ebd7ef4ea..1a17ffafa 100644 --- a/crates/live/src/live_poll.rs +++ b/crates/live/src/live_poll.rs @@ -31,6 +31,9 @@ Modes: poll --reply error \"msg\" Reply with an error message poll --reply done --data '' Reply with a structured JSON result (manual_edit_apply) + poll --reply done --then-poll + Reply, then keep waiting for the next event in the + same call (the generate lane: done, then the accept) Options: --timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode @@ -38,6 +41,8 @@ Options: --ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000) --file PATH Attach a source file path to the reply (generate/steer flow) --data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON + --then-poll After a successful --reply, run the one-shot poll and print its event + (the reply's ack rides along as _replyAck). --timeout= bounds the wait --help Show this help message Harness note: @@ -324,7 +329,7 @@ fn normalize_poll_types(value: Option<&str>) -> Vec { out } -fn form_encode(s: &str) -> String { +pub(crate) fn form_encode(s: &str) -> String { // URLSearchParams serialization (application/x-www-form-urlencoded) let mut out = String::new(); for b in s.bytes() { @@ -729,12 +734,16 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { return 1; } }; + let then_poll = argv.iter().any(|a| a == "--then-poll"); return match post_reply(&base, &token, &reply) { Ok(()) => { - println( - io, - &serde_json::to_string(&reply_ack_json(&reply)).unwrap_or_default(), - ); + let ack = reply_ack_json(&reply); + if then_poll { + // One round trip instead of two: the reply is in, so wait + // for what the browser does next (usually the accept). + return one_shot_poll(&argv, &base, &token, Some(ack), io); + } + println(io, &serde_json::to_string(&ack).unwrap_or_default()); 0 } Err(PollError::ConnRefused) => { @@ -803,7 +812,20 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { } } - let total_timeout = arg_value_int(&argv, "--timeout=", 600_000); + one_shot_poll(&argv, &base, &token, None, io) +} + +/// The default mode: block until one event (or the `--timeout=` deadline), +/// handle it, print it. `reply_ack` is the `--then-poll` case: the reply +/// that just went out rides along as `_replyAck` on the printed event so +/// the caller sees both halves of its one call. +fn one_shot_poll(argv: &[String], base: &str, token: &str, reply_ack: Option, io: &mut Io) -> i32 { + let types_arg = argv + .iter() + .find(|a| a.starts_with("--types=")) + .map(|a| a["--types=".len()..].to_string()); + let types = normalize_poll_types(types_arg.as_deref()); + let total_timeout = arg_value_int(argv, "--timeout=", 600_000); // JS: Date.now() + NaN -> NaN deadline; comparisons are false, so the // loop never times out. Approximate with a far deadline. let deadline = if total_timeout == i64::MIN { @@ -811,12 +833,24 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { } else { Instant::now() + Duration::from_millis(total_timeout.max(0) as u64) }; - match fetch_next_event(&base, &token, Some(deadline), &types) { - Ok(event) => { - handle_event(event, &base, &token, io); + match fetch_next_event(base, token, Some(deadline), &types) { + Ok(mut event) => { + if let (Some(mut ack), Some(obj)) = (reply_ack, event.as_object_mut()) { + if let Some(a) = ack.as_object_mut() { + a.remove("_instructions"); + } + obj.insert("_replyAck".into(), ack); + } + handle_event(event, base, token, io); 0 } - Err(e) => handle_poll_error(e, io), + Err(e) => { + if let Some(ack) = reply_ack { + // The reply itself succeeded; say so before the poll's error. + println(io, &serde_json::to_string(&ack).unwrap_or_default()); + } + handle_poll_error(e, io) + } } } diff --git a/crates/live/src/live_server.rs b/crates/live/src/live_server.rs index 38539c1d1..3aa3afc67 100644 --- a/crates/live/src/live_server.rs +++ b/crates/live/src/live_server.rs @@ -182,6 +182,10 @@ pub fn run(args: &[String], io: &mut Io) -> i32 { next_poll_id: 1, next_client_id: 1, next_apply_timer_gen: 0, + pending_agent_targets: Vec::new(), + next_agent_target_timer_gen: 0, + resolved_agent_targets: Vec::new(), + hide_live_bar: false, shutting_down: false, cleaned_up: false, log_tx, @@ -518,6 +522,9 @@ fn shutdown(shared: &Shared) { for poll in st.pending_polls.drain(..) { let _ = poll.tx.send(json!({ "type": "exit" })); } + for (_, pending) in st.pending_agent_targets.drain(..) { + let _ = pending.tx.send(json!({ "ok": false, "error": "server_stopping" })); + } // Give response writers a moment to flush before the process exits. drop(st); std::thread::sleep(Duration::from_millis(50)); @@ -656,9 +663,9 @@ fn handle_connection(shared: Shared, mut stream: TcpStream, mut ticket: Ticket) ); return; } - let (cwd, env, port, roots) = { + let (cwd, env, port, roots, live_bar_hidden) = { let st = lock(&shared); - (st.cwd.clone(), st.env.clone(), st.port, st.roots.clone()) + (st.cwd.clone(), st.env.clone(), st.port, st.roots.clone(), st.hide_live_bar) }; let parts = match read_live_browser_script_parts(scripts_dir(&env, &cwd).as_deref()) { Ok(p) => p, @@ -685,7 +692,7 @@ fn handle_connection(shared: Shared, mut stream: TcpStream, mut ticket: Ticket) roots.as_ref().and_then(|r| r.context_root.as_deref()), roots.as_ref().map(|r| r.repo_root.as_str()), ); - let body = assemble_live_browser_script(&token_now, port, &prefix, &cwd, &parts, &project_ignores); + let body = assemble_live_browser_script(&token_now, port, &prefix, &cwd, &parts, &project_ignores, live_bar_hidden); respond( &mut stream, &cors, @@ -744,6 +751,7 @@ fn handle_connection(shared: Shared, mut stream: TcpStream, mut ticket: Ticket) "connectedClients": st.sse_clients.len(), "pendingEvents": pending, "agentPolling": st.agent_polling_connected(), + "hideLiveBar": st.hide_live_bar, "activeSessions": sessions, "manualEdits": st.manual_edit_status(), }); @@ -907,7 +915,14 @@ fn handle_connection(shared: Shared, mut stream: TcpStream, mut ticket: Ticket) text_res(200, Some("text/html; charset=utf-8"), &content), ); } - ("/events", "GET") => handle_sse(&shared, stream, &cors, token_ok, &mut ticket), + ("/events", "GET") => handle_sse( + &shared, + stream, + &cors, + token_ok, + req.query_get("clientId").map(|s| s.to_string()), + &mut ticket, + ), ("/manual-edit-stash", "POST") | ("/manual-edit-stash", "GET") | ("/manual-edit-commit", "POST") @@ -943,6 +958,17 @@ fn handle_connection(shared: Shared, mut stream: TcpStream, mut ticket: Ticket) ("/poll", "POST") => { handle_poll_post(&shared, &mut stream, &cors, &req, &token_now, &mut ticket) } + // --- Agent-initiated targeting (the `generate` command) --- + ("/agent-target", "POST") => { + handle_agent_target_post(&shared, stream, &cors, &req, &token_now, &mut ticket) + } + ("/agent-target-result", "POST") => { + handle_agent_target_result_post(&shared, &mut stream, &cors, &req, &token_now) + } + ("/agent-target-claim", "POST") => { + handle_agent_target_claim_post(&shared, &mut stream, &cors, &req, &token_now) + } + ("/live-bar", "POST") => handle_live_bar_post(&shared, &mut stream, &cors, &req, &token_now), _ => respond(&mut stream, &cors, text_res(404, None, "Not found")), } } @@ -1028,6 +1054,7 @@ fn handle_sse( stream: TcpStream, cors: &[(String, String)], token_ok: bool, + agent_client_id: Option, ticket: &mut Ticket, ) { let mut stream = stream; @@ -1046,11 +1073,12 @@ fn handle_sse( "type": "connected", "hasProjectContext": has_ctx, "agentPolling": st.agent_polling_connected(), + "hideLiveBar": st.hide_live_bar, "activeSessions": st.active_session_summaries(), })) .unwrap_or_default() ); - let (id, rx, tx) = st.add_sse_client(); + let (id, rx, tx) = st.add_sse_client(agent_client_id); (id, rx, tx, frame) }; // Registered; the stream now parks, so let later requests through. @@ -1160,7 +1188,28 @@ fn handle_events_post( respond(stream, cors, json_res(400, json!({ "error": error }))); return; } + // A generate event may name the agent target it serves. The helper + // resolves that request from the event as well as from + // /agent-target-result, so a page that dies between Go and its result + // cannot leave the request pending for a second Go elsewhere. The + // envelope never reaches the journal or the poller. + let mut msg = msg; let mut msg_obj = msg_obj; + let agent_target = if ty == "generate" { + msg_obj.remove("agentTarget"); + msg.as_object_mut().and_then(|o| o.remove("agentTarget")) + } else { + None + }; + if agent_target.is_some() { + // An agent-initiated Go (the generate command): the poll hands its + // handler the fast-path instructions instead of the interactive + // planning ceremony. The marker rides in the journal and the queue. + msg_obj.insert("origin".into(), json!("agent")); + if let Some(o) = msg.as_object_mut() { + o.insert("origin".into(), json!("agent")); + } + } crate::server_state::strip_poller_owned_event_fields(&mut msg_obj); let mut st = lock(shared); if ty == "agent_phase" { @@ -1203,6 +1252,25 @@ fn handle_events_post( return; } } + if let Some(envelope) = agent_target.as_ref().and_then(Value::as_object) { + if let Some(refusal) = st.agent_target_refusal(envelope, id_str.as_deref()) { + // A superseded Go: this page's lease lapsed while it was still + // capturing and another page served the request, or the + // request was already answered (a timeout or a failure the CLI + // has reported). Journal nothing, so one request never gets a + // second session, or a session nobody was told about. + drop(st); + let mut body = json!({ + "error": "agent_target_already_served", + "targetId": envelope.get("targetId").cloned().unwrap_or(Value::Null), + }); + if let Some(sid) = refusal.session_id { + body["sessionId"] = Value::String(sid); + } + respond(stream, cors, json_res(409, body)); + return; + } + } let missed = st.detect_missed_generation_completion(&msg_obj); if id_truthy { if let Err(e) = st.store.append_event(&msg) { @@ -1237,6 +1305,13 @@ fn handle_events_post( if ty != "checkpoint" && ty != "variant_mounted" && !orphaned_discard { st.enqueue_event(msg_obj); } + if let Some(Value::Object(envelope)) = agent_target { + if let (Some(Value::String(target_id)), Some(result @ Value::Object(_))) = + (envelope.get("targetId"), envelope.get("result")) + { + st.resolve_agent_target(target_id, result.clone()); + } + } drop(st); respond(stream, cors, json_res(200, json!({ "ok": true }))); } @@ -1294,9 +1369,16 @@ fn handle_poll_get( let lease_raw = parse_int_or(req.query_get("leaseMs"), 30000); let lease_ms = if lease_raw == i64::MIN { 0 } else { lease_raw }; let types = parse_poll_types(req.query_get("types")); + // `id=`: only that session's events (the generate verb collecting its + // own generate event leaves every other session's queue alone). + let event_id = req + .query_get("id") + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); let mut st = lock(shared); st.last_poll_at = now_i64(); - if let Some(idx) = st.find_available_pending_event(types.as_deref()) { + if let Some(idx) = st.find_available_pending_event(types.as_deref(), event_id.as_deref()) { st.pending_events[idx].lease_until = now_i64() + lease_ms; let seq = st.pending_events[idx].seq; let event = st.pending_events[idx].event.clone(); @@ -1308,7 +1390,7 @@ fn handle_poll_get( respond(&mut stream, cors, json_res(200, Value::Object(event))); return; } - let (poll_id, rx) = st.park_poll(lease_ms, types); + let (poll_id, rx) = st.park_poll(lease_ms, types, event_id); drop(st); ticket.release(); let done = Arc::new(AtomicBool::new(false)); @@ -2588,6 +2670,250 @@ fn handle_manual_edit_commit( } } +// --------------------------------------------------------------------------- +// Agent-initiated element targeting (the `generate` command) +// --------------------------------------------------------------------------- + +/// JS: validateAgentTargetRequest(msg) +fn validate_agent_target_request(msg: &Value) -> Option { + let selector_ok = matches!(msg.get("selector"), Some(Value::String(s)) if !s.trim().is_empty()); + if !selector_ok { + return Some("agent_target: selector is required".into()); + } + if msg.get("selector").and_then(Value::as_str).map(|s| s.chars().count()).unwrap_or(0) > 1000 { + return Some("agent_target: selector too long".into()); + } + let action_ok = matches!(msg.get("action"), Some(Value::String(a)) if crate::vocabulary::VISUAL_ACTIONS.contains(&a.as_str())); + if !action_ok { + return Some(format!( + "agent_target: invalid action (valid: {})", + crate::vocabulary::VISUAL_ACTIONS.join(", ") + )); + } + let count_ok = match msg.get("count") { + Some(Value::Number(n)) => n.as_i64().map(|c| (1..=8).contains(&c)).unwrap_or(false), + _ => false, + }; + if !count_ok { + return Some("agent_target: count must be 1-8".into()); + } + if let Some(text) = msg.get("text") { + if !matches!(text, Value::String(t) if t.chars().count() <= 500) { + return Some("agent_target: text must be a string of at most 500 chars".into()); + } + } + if let Some(index) = msg.get("index") { + if !index.as_i64().map(|i| i >= 1).unwrap_or(false) { + return Some("agent_target: index must be a positive integer (1-based)".into()); + } + } + if let Some(prompt) = msg.get("prompt") { + if !matches!(prompt, Value::String(p) if p.chars().count() <= 2000) { + return Some("agent_target: prompt must be a string of at most 2000 chars".into()); + } + } + if let Some(dry) = msg.get("dryRun") { + if !dry.is_boolean() { + return Some("agent_target: dryRun must be a boolean".into()); + } + } + if let Some(hide) = msg.get("hideLiveBar") { + if !hide.is_boolean() { + return Some("agent_target: hideLiveBar must be a boolean".into()); + } + } + None +} + +/// Parse the body and check its token; answers the request itself on failure. +fn agent_target_body( + stream: &mut TcpStream, + cors: &[(String, String)], + req: &Request, + token: &str, +) -> Option> { + let Some(msg) = parse_json_body(req) else { + respond(stream, cors, json_res(400, json!({ "error": "Invalid JSON" }))); + return None; + }; + let obj = msg.as_object().cloned().unwrap_or_default(); + if obj.get("token").and_then(Value::as_str) != Some(token) { + respond(stream, cors, json_res(401, json!({ "error": "Unauthorized" }))); + return None; + } + Some(obj) +} + +/// JS: handleAgentTargetPost: hold the response until the overlay answers. +fn handle_agent_target_post( + shared: &Shared, + stream: TcpStream, + cors: &[(String, String)], + req: &Request, + token: &str, + ticket: &mut Ticket, +) { + let mut stream = stream; + let Some(msg) = agent_target_body(&mut stream, cors, req, token) else { + return; + }; + if let Some(error) = validate_agent_target_request(&Value::Object(msg.clone())) { + respond(&mut stream, cors, json_res(400, json!({ "error": error }))); + return; + } + let mut st = lock(shared); + if st.sse_clients.is_empty() { + drop(st); + respond( + &mut stream, + cors, + json_res(200, json!({ "ok": false, "error": "no_browser_connected" })), + ); + return; + } + let mut payload = Map::new(); + payload.insert("selector".into(), msg.get("selector").cloned().unwrap_or(Value::Null)); + if let Some(text) = msg.get("text").and_then(Value::as_str).filter(|t| !t.is_empty()) { + payload.insert("text".into(), json!(text)); + } + if let Some(index) = msg.get("index").and_then(Value::as_i64) { + payload.insert("index".into(), json!(index)); + } + payload.insert("action".into(), msg.get("action").cloned().unwrap_or(Value::Null)); + payload.insert("count".into(), msg.get("count").cloned().unwrap_or(Value::Null)); + if let Some(prompt) = msg.get("prompt").and_then(Value::as_str).filter(|p| !p.is_empty()) { + payload.insert("prompt".into(), json!(prompt)); + } + if msg.get("dryRun").and_then(Value::as_bool) == Some(true) { + payload.insert("dryRun".into(), json!(true)); + } + if msg.get("hideLiveBar").and_then(Value::as_bool) == Some(true) { + payload.insert("hideLiveBar".into(), json!(true)); + // Helper-wide, before the target goes out: every tab hides now, the + // acting one included, and later connections hide on connect. + st.set_live_bar_hidden(true); + } + let (target_id, rx) = st.register_agent_target(payload); + drop(st); + // Registered and broadcast; the response now parks, so let the claims + // and the result through. + ticket.release(); + let result = rx + .recv() + .unwrap_or_else(|_| json!({ "ok": false, "error": "server_stopping" })); + let mut out = Map::new(); + out.insert("targetId".into(), json!(target_id)); + if let Value::Object(fields) = result { + for (k, v) in fields { + out.insert(k, v); + } + } + respond(&mut stream, cors, json_res(200, Value::Object(out))); +} + +/// JS: handleAgentTargetResultPost +fn handle_agent_target_result_post( + shared: &Shared, + stream: &mut TcpStream, + cors: &[(String, String)], + req: &Request, + token: &str, +) { + let Some(msg) = agent_target_body(stream, cors, req, token) else { + return; + }; + let target_id = match msg.get("targetId") { + Some(Value::String(id)) if !id.is_empty() => id.clone(), + _ => { + respond( + stream, + cors, + json_res(400, json!({ "error": "agent_target_result: missing targetId" })), + ); + return; + } + }; + let client_id = match msg.get("clientId") { + Some(Value::String(id)) if !id.is_empty() => id.clone(), + _ => { + respond( + stream, + cors, + json_res(400, json!({ "error": "agent_target_result: missing clientId" })), + ); + return; + } + }; + let mut result = Map::new(); + for (k, v) in msg { + if k != "token" && k != "targetId" && k != "clientId" { + result.insert(k, v); + } + } + match lock(shared).resolve_agent_target_as_holder(&target_id, &client_id, Value::Object(result)) { + Ok(delivered) => respond(stream, cors, json_res(200, json!({ "ok": true, "delivered": delivered }))), + Err(reason) => respond( + stream, + cors, + json_res(409, json!({ "error": "agent_target_result: not the holder", "reason": reason, "targetId": target_id })), + ), + } +} + +/// `POST /live-bar` `{token, hidden}`: the helper-wide bar preference, set +/// by `impeccable live --no-live-bar` at boot so the bar never appears, and +/// by an agent target carrying `hideLiveBar` (see handle_agent_target_post). +fn handle_live_bar_post( + shared: &Shared, + stream: &mut TcpStream, + cors: &[(String, String)], + req: &Request, + token: &str, +) { + let Some(msg) = agent_target_body(stream, cors, req, token) else { + return; + }; + let Some(hidden) = msg.get("hidden").and_then(Value::as_bool) else { + respond( + stream, + cors, + json_res(400, json!({ "error": "live_bar: hidden must be a boolean" })), + ); + return; + }; + lock(shared).set_live_bar_hidden(hidden); + respond(stream, cors, json_res(200, json!({ "ok": true, "hidden": hidden }))); +} + +/// JS: handleAgentTargetClaimPost +fn handle_agent_target_claim_post( + shared: &Shared, + stream: &mut TcpStream, + cors: &[(String, String)], + req: &Request, + token: &str, +) { + let Some(msg) = agent_target_body(stream, cors, req, token) else { + return; + }; + let target_id = msg.get("targetId").and_then(Value::as_str).unwrap_or("").to_string(); + let client_id = msg.get("clientId").and_then(Value::as_str).unwrap_or("").to_string(); + if target_id.is_empty() || client_id.is_empty() { + respond( + stream, + cors, + json_res(400, json!({ "error": "agent_target_claim: missing targetId or clientId" })), + ); + return; + } + let eligible = msg.get("eligible").and_then(Value::as_bool) == Some(true); + let state = msg.get("state").cloned().unwrap_or(Value::Null); + let reason = msg.get("reason").cloned().unwrap_or(Value::Null); + let result = msg.get("result").filter(|r| r.is_object()).cloned(); + let body = lock(shared).claim_agent_target(&target_id, &client_id, eligible, state, reason, result); + respond(stream, cors, json_res(200, body)); +} + #[cfg(test)] mod content_type_tests { use super::*; @@ -2633,6 +2959,12 @@ mod content_type_tests { assert!(!releases_ticket_up_front("/events", "OPTIONS")); assert!(!releases_ticket_up_front("/poll", "POST")); assert!(!releases_ticket_up_front("/stop", "GET")); + // The agent-target routes mutate the roll call and must keep arrival + // order too: a claim answered before the target it claims registers + // would deny a tab that should have been granted. + assert!(!releases_ticket_up_front("/agent-target", "POST")); + assert!(!releases_ticket_up_front("/agent-target-result", "POST")); + assert!(!releases_ticket_up_front("/agent-target-claim", "POST")); } #[test] diff --git a/crates/live/src/project_ignores.rs b/crates/live/src/project_ignores.rs index 1faefb292..c2c75e1c6 100644 --- a/crates/live/src/project_ignores.rs +++ b/crates/live/src/project_ignores.rs @@ -9,6 +9,8 @@ //! ignoreFiles detector.ignoreFiles globs, unioned across roots, so a //! wholly waived page scans to zero findings in the overlay //! just as it reports nothing through the CLI and the hook. +//! ignoreSelectors component opt-outs ({rule, selector, files?}), resolved +//! to the served page by the same browser-side scope matcher. //! roots served-root prefixes derived from the inject config's own //! `files` globs. Never derived from the ignore globs: one //! entry scoped to prototype/library/** would lend @@ -71,6 +73,7 @@ pub fn collect_project_detector_ignores( let mut ignore_files: Vec = Vec::new(); let mut value_keys: Vec = Vec::new(); let mut value_entries: Vec = Vec::new(); + let mut selector_entries: Vec = Vec::new(); for dir in &config_roots { // readConfig merges config.json with the gitignored // config.local.json and type-checks both, exactly as the edit hook @@ -112,6 +115,17 @@ pub fn collect_project_detector_ignores( value_entries.push(Value::Object(serialized)); } } + for entry in &config.ignore_selectors { + let mut serialized = serde_json::json!({ "rule": entry.rule, "selector": entry.selector }); + let mut files = entry.files.clone().unwrap_or_default(); + files.sort(); + if !files.is_empty() { + serialized["files"] = serde_json::json!(files); + } + if !selector_entries.contains(&serialized) { + selector_entries.push(serialized); + } + } } let (roots, page_files) = read_live_served_pages(cwd, env, &config_roots[0], repo_root); @@ -121,6 +135,9 @@ pub fn collect_project_detector_ignores( Value::Array(ignore_rules.into_iter().map(Value::String).collect()), ); out.insert("ignoreValues".into(), Value::Array(value_entries)); + if !selector_entries.is_empty() { + out.insert("ignoreSelectors".into(), Value::Array(selector_entries)); + } out.insert( "ignoreFiles".into(), Value::Array(ignore_files.into_iter().map(Value::String).collect()), @@ -269,6 +286,24 @@ mod tests { out } + #[test] + fn collects_selector_ignores_across_roots_without_private_metadata() { + let repo = Tmp::new(); + let app = format!("{}/site", repo.path()); + repo.write("site/package.json", "{}"); + let entries = json!([ + { "rule": "low-contrast", "selector": ".Card", "files": ["b/**", "a/**"], "reason": "local" } + ]); + repo.write(".impeccable/config.json", &detector_config(json!({ "ignoreSelectors": entries }))); + repo.write("site/.impeccable/config.local.json", &detector_config(json!({ + "ignoreSelectors": [{ "rule": "low-contrast", "selector": ".Card", "files": ["a/**", "b/**"] }] + }))); + let out = collect(&app, Some(&repo.path())); + assert_eq!(out["ignoreSelectors"], json!([ + { "rule": "low-contrast", "selector": ".Card", "files": ["a/**", "b/**"] } + ])); + } + #[test] fn collects_waivers_roots_and_page_files_from_a_single_root() { let app = Tmp::new(); diff --git a/crates/live/src/server_state.rs b/crates/live/src/server_state.rs index 778cf14e1..1de857284 100644 --- a/crates/live/src/server_state.rs +++ b/crates/live/src/server_state.rs @@ -34,11 +34,54 @@ pub struct ParkedPoll { pub tx: Sender, pub lease_ms: i64, pub types: Option>, + /// `GET /poll?id=`: lease only the events of that session (the + /// generate verb picks up its own event without touching another's). + pub event_id: Option, } pub struct SseClient { pub id: u64, pub tx: Sender, + /// The overlay's per-page-load id (`/events?clientId=`), so a disconnect + /// can retire its word in any agent-target roll call it took part in. + pub agent_client_id: Option, +} + +/// One overlay's roll-call report on an agent target: its busy state and why. +/// A generate event refused because its agent target is spoken for; see +/// `ServerState::agent_target_refusal`. +pub struct AgentTargetRefusal { + /// The session that answered the request, when the verdict carried one. + pub session_id: Option, +} + +pub struct AgentTargetReport { + pub client_id: String, + pub state: Value, + pub reason: Value, + /// The overlay's resolution verdict when it declined because its page + /// cannot resolve the target (`reason: no_match`). + pub result: Option, +} + +/// A held-open `POST /agent-target` (the `generate` command): resolved by +/// `POST /agent-target-result`, by a complete busy roll call, by its timeout, +/// or by shutdown. The claim lease decides which overlay acts. +pub struct AgentTargetPending { + pub tx: Sender, + /// The `agent_target` SSE payload, replayed to overlays that connect late. + pub payload: Value, + pub owner: Option, + pub claimed_until: i64, + /// The overlay most recently granted the lease, kept when the lease + /// lapses or its page goes away: its Go may still land late, and it is + /// the only page besides the current holder allowed to open the session. + pub last_holder: Option, + pub reports: Vec, + pub timer_gen: u64, + /// While every report says `no_match`, the roll call stays open until + /// this instant: a page whose element mounts late can still claim. + pub resolve_grace_until: Option, } /// One pre-apply file snapshot entry (`{ exists, content }`). @@ -84,6 +127,21 @@ pub struct ServerState { pub manual_edit_activity: Option, pub next_manual_edit_seq: i64, pub pending_apply_deferreds: Vec<(String, ApplyDeferred)>, + /// Held-open agent targets keyed by targetId, in arrival order. + pub pending_agent_targets: Vec<(String, AgentTargetPending)>, + pub next_agent_target_timer_gen: u64, + /// Every agent target already answered, oldest first (bounded), with + /// the session that answered it when the verdict carried one. A + /// generate event naming a target is welcome only while that target is + /// pending without a rival lease, or when it comes from the session + /// that answered it; anything else, including a target this record no + /// longer holds, is refused, so eviction can never reopen a request. + pub resolved_agent_targets: Vec<(String, Option)>, + /// The generate lane asked this helper to keep the overlay's global bar + /// out of the way (`live --no-live-bar` or an agent target carrying + /// `hideLiveBar`). Helper-wide and for its lifetime: every connected + /// tab hides on the broadcast, every later connection on `connected`. + pub hide_live_bar: bool, pub last_poll_at: i64, pub timed_out_apply_ids: Vec<(String, TimedOutApply)>, pub next_poll_id: u64, @@ -133,12 +191,18 @@ pub fn select_available_pending_event( entries: &[PendingEntry], now: i64, types: Option<&[String]>, + event_id: Option<&str>, ) -> Option { let mut best: Option = None; for (i, entry) in entries.iter().enumerate() { if is_leased_at(entry, now) { continue; } + if let Some(wanted) = event_id { + if entry.event.get("id").and_then(|v| v.as_str()) != Some(wanted) { + continue; + } + } if let Some(allowed) = types { let ty = entry .event @@ -225,8 +289,12 @@ impl ServerState { } } - pub fn find_available_pending_event(&self, types: Option<&[String]>) -> Option { - select_available_pending_event(&self.pending_events, now_i64(), types) + pub fn find_available_pending_event( + &self, + types: Option<&[String]>, + event_id: Option<&str>, + ) -> Option { + select_available_pending_event(&self.pending_events, now_i64(), types, event_id) } /// JS: recordAgentPhase(id, phase, details) @@ -374,9 +442,12 @@ impl ServerState { let mut found: Option<(usize, usize)> = None; let now = now_i64(); for (pi, poll) in self.pending_polls.iter().enumerate() { - if let Some(ei) = - select_available_pending_event(&self.pending_events, now, poll.types.as_deref()) - { + if let Some(ei) = select_available_pending_event( + &self.pending_events, + now, + poll.types.as_deref(), + poll.event_id.as_deref(), + ) { found = Some((pi, ei)); break; } @@ -428,6 +499,15 @@ impl ServerState { } /// JS: broadcast(msg) + /// Flip the helper-wide bar preference and tell every connected tab. + pub fn set_live_bar_hidden(&mut self, hidden: bool) { + if self.hide_live_bar == hidden { + return; + } + self.hide_live_bar = hidden; + self.broadcast(&json!({ "type": "live_bar", "hidden": hidden })); + } + pub fn broadcast(&mut self, msg: &Value) { let data = format!( "data: {}\n\n", @@ -581,6 +661,7 @@ impl ServerState { &mut self, lease_ms: i64, types: Option>, + event_id: Option, ) -> (u64, Receiver) { let (tx, rx) = channel(); let id = self.next_poll_id; @@ -590,6 +671,7 @@ impl ServerState { tx, lease_ms, types, + event_id, }); self.broadcast_agent_polling_if_changed(); self.schedule_lease_flush(); @@ -603,26 +685,460 @@ impl ServerState { before != self.pending_polls.len() } - /// Register an SSE client; returns (id, receiver). - pub fn add_sse_client(&mut self) -> (u64, Receiver, Sender) { + /// Register an SSE client; returns (id, receiver). An overlay that + /// connects after an agent target was broadcast (a reload mid-request is + /// the common case) joins its roll call: every pending target is replayed + /// to it, so it claims or declines like the others instead of silently + /// widening the count the roll call is judged against. + pub fn add_sse_client( + &mut self, + agent_client_id: Option, + ) -> (u64, Receiver, Sender) { let (tx, rx) = channel(); let id = self.next_client_id; self.next_client_id += 1; - self.sse_clients.push(SseClient { id, tx: tx.clone() }); + for (_, pending) in &self.pending_agent_targets { + let _ = tx.send(format!( + "data: {}\n\n", + serde_json::to_string(&pending.payload).unwrap_or_else(|_| "null".into()) + )); + } + self.sse_clients.push(SseClient { + id, + tx: tx.clone(), + agent_client_id, + }); (id, rx, tx) } /// Remove an SSE client; when none remain arm the exit timer (JS - /// `req.on('close')`). + /// `req.on('close')`). A departed overlay's word no longer counts in any + /// agent-target roll call. The overlay, not the connection, is the + /// participant: an EventSource reconnect opens a replacement connection + /// under the same page-level clientId before the old one is seen to + /// close, so its word is retired only once no connection carries that + /// id, while every roll call is still re-judged against the connections + /// that remain. pub fn remove_sse_client(&mut self, id: u64) { let before = self.sse_clients.len(); + let agent_client_id = self + .sse_clients + .iter() + .find(|c| c.id == id) + .and_then(|c| c.agent_client_id.clone()); self.sse_clients.retain(|c| c.id != id); - if before != self.sse_clients.len() && self.sse_clients.is_empty() { - self.clear_exit_timer(); - self.arm_exit_timer(); + if before != self.sse_clients.len() { + let still_connected = agent_client_id + .as_deref() + .map(|cid| self.sse_clients.iter().any(|c| c.agent_client_id.as_deref() == Some(cid))) + .unwrap_or(false); + self.drop_agent_target_client(if still_connected { None } else { agent_client_id.as_deref() }); + if self.sse_clients.is_empty() { + self.clear_exit_timer(); + self.arm_exit_timer(); + } } } + /// Whether a connection carries this overlay's clientId. True as well + /// while any connection sent none (an older overlay build): that + /// overlay cannot be told apart from the id in hand. + fn overlay_connected(&self, client_id: &str) -> bool { + self.sse_clients.iter().any(|c| match c.agent_client_id.as_deref() { + Some(cid) => cid == client_id, + None => true, + }) + } + + /// Connected overlays for a roll call: one per distinct clientId, plus + /// every connection that sent none (an older overlay build), so a + /// reconnect's momentary duplicate connection never waits on a second + /// report from the same tab. + pub fn connected_overlay_count(&self) -> usize { + let mut ids: Vec<&str> = Vec::new(); + let mut anonymous = 0; + for c in &self.sse_clients { + match c.agent_client_id.as_deref() { + Some(cid) => { + if !ids.contains(&cid) { + ids.push(cid); + } + } + None => anonymous += 1, + } + } + ids.len() + anonymous + } + + // --------------------------------------------------------------------- + // Agent-initiated element targeting (the `generate` command) + // --------------------------------------------------------------------- + // + // POST /agent-target lets the AGENT start a variant session: the server + // pushes an `agent_target` SSE message, the overlay resolves the selector, + // scrolls to the element, enters the same picked state a user click + // produces, and fires the normal Go pipeline. The HTTP response is held + // open until the overlay POSTs /agent-target-result (or the timeout + // fires), so the CLI gets a synchronous verdict. No session exists until + // the browser's own generate event creates one. + + /// Browser must answer an agent_target push within this window. The env + /// override exists for tests; real sessions keep the default. + pub fn agent_target_timeout_ms(&self) -> u64 { + env_positive_ms(&self.env, "IMPECCABLE_AGENT_TARGET_TIMEOUT_MS").unwrap_or(15_000) + } + + /// A granted claim is a lease, not a lock: if the winning tab dies before + /// posting its result (reload, crash), the lease lapses and a surviving + /// tab's retry rescues the request instead of letting it wait out the + /// browser timeout. The lease comfortably exceeds a healthy winner's + /// worst case (claim RTT + smooth-scroll settle + Go, under 2s). + pub fn agent_target_lease_ms(&self) -> i64 { + env_positive_ms(&self.env, "IMPECCABLE_AGENT_TARGET_CLAIM_LEASE_MS") + .map(|v| v as i64) + .unwrap_or(3_000) + } + + /// A page's `no_match` is a provisional word: an element can mount after + /// the page first looked (a route still rendering, an HMR swap). When + /// every connected overlay says `no_match`, the roll call stays open for + /// this long after the first such report, so a page that keeps watching + /// can still claim; a busy report answers at once regardless. + pub fn agent_target_resolve_grace_ms(&self) -> i64 { + env_positive_ms(&self.env, "IMPECCABLE_AGENT_TARGET_RESOLVE_GRACE_MS") + .map(|v| v as i64) + .unwrap_or(3_000) + } + + /// Hold a new agent target: mint its id, broadcast the push, arm the + /// timeout. Returns the id and the receiver the route blocks on. + pub fn register_agent_target(&mut self, mut payload: Map) -> (String, Receiver) { + let target_id = crate::random::random_id8(); + payload.insert("targetId".into(), json!(target_id)); + // JS spread order: type, targetId, then the request fields. + let mut ordered = Map::new(); + ordered.insert("type".into(), json!("agent_target")); + ordered.insert("targetId".into(), json!(target_id)); + for (k, v) in payload { + if k != "type" && k != "targetId" { + ordered.insert(k, v); + } + } + let payload = Value::Object(ordered); + let (tx, rx) = channel(); + self.next_agent_target_timer_gen += 1; + let timer_gen = self.next_agent_target_timer_gen; + self.pending_agent_targets.push(( + target_id.clone(), + AgentTargetPending { + tx, + payload: payload.clone(), + owner: None, + claimed_until: 0, + last_holder: None, + reports: Vec::new(), + timer_gen, + resolve_grace_until: None, + }, + )); + self.broadcast(&payload); + let timeout_ms = self.agent_target_timeout_ms(); + let weak = self.self_ref.clone(); + let id = target_id.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(timeout_ms)); + if let Some(shared) = weak.upgrade() { + let mut st = lock(&shared); + let Some((_, pending)) = st + .pending_agent_targets + .iter() + .find(|(k, p)| *k == id && p.timer_gen == timer_gen) + else { + return; + }; + let verdict = if pending.reports.is_empty() { + json!({ "ok": false, "error": "browser_timeout", "timeoutMs": timeout_ms }) + } else { + agent_target_verdict_from_reports(pending) + }; + st.resolve_agent_target(&id, verdict); + } + }); + (target_id, rx) + } + + /// A result post is only honored from the overlay that holds the + /// target's claim: every connected overlay knows the target id and the + /// helper token, so the token alone must not let a bystander answer + /// for the winner. Ok(delivered) when the holder answered (or nothing + /// awaited the target); Err(reason) when the target is pending but the + /// caller is not its holder. + pub fn resolve_agent_target_as_holder( + &mut self, + target_id: &str, + client_id: &str, + result: Value, + ) -> Result { + if let Some((_, pending)) = self + .pending_agent_targets + .iter() + .find(|(k, _)| k == target_id) + { + match &pending.owner { + Some(owner) if owner == client_id => {} + Some(_) => return Err("not_holder"), + None => return Err("unclaimed"), + } + } + Ok(self.resolve_agent_target(target_id, result)) + } + + /// Deliver a verdict to the held request; false when nothing awaits it. + pub fn resolve_agent_target(&mut self, target_id: &str, result: Value) -> bool { + let Some(pos) = self + .pending_agent_targets + .iter() + .position(|(k, _)| k == target_id) + else { + return false; + }; + let (_, pending) = self.pending_agent_targets.remove(pos); + let session = if result.get("ok") == Some(&Value::Bool(true)) { + result + .get("sessionId") + .and_then(Value::as_str) + .map(str::to_string) + } else { + None + }; + self.resolved_agent_targets + .push((target_id.to_string(), session)); + if self.resolved_agent_targets.len() > 256 { + self.resolved_agent_targets.remove(0); + } + let _ = pending.tx.send(result); + true + } + + /// Why a generate event naming `envelope.targetId`, sent by + /// `envelope.clientId` under `session_id`, must not open a session: + /// the target is still pending and this page is not its holder (another + /// page holds the lease, or held it last, or nobody claimed it); the + /// request was already answered, with a different session or with none + /// (a timeout or a failure verdict the CLI has already reported); or the + /// helper neither holds nor remembers the target (never issued here, or + /// long since evicted from the bounded record). None only when the + /// event is welcome: the holder's own Go (its lease may have lapsed, or + /// its page gone away, as long as no rescuer claimed since), or the + /// answering session's own event. + pub fn agent_target_refusal( + &self, + envelope: &Map, + session_id: Option<&str>, + ) -> Option { + let target_id = envelope.get("targetId").and_then(Value::as_str)?; + let client_id = envelope + .get("clientId") + .and_then(Value::as_str) + .unwrap_or(""); + if let Some((_, pending)) = self + .pending_agent_targets + .iter() + .find(|(k, _)| k == target_id) + { + let is_holder = match &pending.owner { + Some(owner) => owner == client_id, + // Lease handed back or the page gone: only the page that + // held it last may still land its Go. + None => pending.last_holder.as_deref() == Some(client_id) && !client_id.is_empty(), + }; + return if is_holder { None } else { Some(AgentTargetRefusal { session_id: None }) }; + } + let Some((_, answered_by)) = self + .resolved_agent_targets + .iter() + .rev() + .find(|(t, _)| t == target_id) + else { + return Some(AgentTargetRefusal { session_id: None }); + }; + if answered_by.as_deref() == session_id && session_id.is_some() { + return None; + } + Some(AgentTargetRefusal { + session_id: answered_by.clone(), + }) + } + + /// Every connected overlay has declined: answer busy now, not at the + /// timeout. Judged against the connections of this moment, so it runs + /// whenever a report lands and whenever an overlay leaves. + pub fn maybe_complete_agent_target_roll_call(&mut self, target_id: &str) { + let connected = self.connected_overlay_count(); + let now = now_i64(); + let verdict = self + .pending_agent_targets + .iter() + .find(|(k, _)| k == target_id) + .and_then(|(_, p)| { + if p.owner.is_some() || p.reports.is_empty() || p.reports.len() < connected { + return None; + } + let all_no_match = p.reports.iter().all(|r| r.reason.as_str() == Some("no_match")); + if all_no_match && p.resolve_grace_until.map(|until| now < until).unwrap_or(false) { + // Every page says no_match, but one may still be + // watching a late mount: the grace timer re-runs this + // check when it lapses. + return None; + } + Some(agent_target_verdict_from_reports(p)) + }); + if let Some(verdict) = verdict { + self.resolve_agent_target(target_id, verdict); + } + } + + /// Each overlay's first `no_match` word extends the resolution grace by + /// the full window, so a page that reports after another page's grace + /// lapsed still gets its watch; the roll call is re-judged when the + /// latest grace lapses (the lapse alone never resolves; the check + /// re-reads the reports, so a claim or a busy word in between takes + /// precedence). The target's timeout bounds the sum. + fn arm_agent_target_resolve_grace(&mut self, target_id: &str) { + let grace_ms = self.agent_target_resolve_grace_ms(); + let Some((_, pending)) = self + .pending_agent_targets + .iter_mut() + .find(|(k, _)| k == target_id) + else { + return; + }; + let until = now_i64() + grace_ms; + if pending.resolve_grace_until.map(|u| u >= until).unwrap_or(false) { + return; + } + pending.resolve_grace_until = Some(until); + let weak = self.self_ref.clone(); + let id = target_id.to_string(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(grace_ms.max(0) as u64 + 5)); + if let Some(shared) = weak.upgrade() { + lock(&shared).maybe_complete_agent_target_roll_call(&id); + } + }); + } + + /// A disconnected overlay's word no longer counts: drop its busy report, + /// hand back a lease it held (a rescuer's next claim is granted at once + /// instead of after the lease lapses), and re-judge each roll call + /// against the overlays that remain. + pub fn drop_agent_target_client(&mut self, client_id: Option<&str>) { + let ids: Vec = self + .pending_agent_targets + .iter() + .map(|(k, _)| k.clone()) + .collect(); + for id in ids { + if let Some(cid) = client_id { + if let Some((_, p)) = self.pending_agent_targets.iter_mut().find(|(k, _)| *k == id) { + p.reports.retain(|r| r.client_id != cid); + if p.owner.as_deref() == Some(cid) { + p.owner = None; + p.claimed_until = 0; + } + } + } + self.maybe_complete_agent_target_roll_call(&id); + } + } + + /// Roll call plus a first-wins lease. Every connected overlay claims once. + /// A busy tab claims with eligible:false and is only counted: the moment + /// every connected overlay has reported busy, the held request answers + /// `busy` without waiting on a timer or guessing about a slower idle tab. + /// An eligible tab is granted when nobody holds the lease, when it + /// already holds it (a renew, which the holder does right before it + /// fires Go, so a lapsed lease can never leave two tabs acting), or when + /// the previous holder's lease lapsed without a result (a rescue). + /// Unknown or resolved targets deny and say so (`pending: false`), which + /// ends a rescuer's retry loop. Returns the response body. + pub fn claim_agent_target( + &mut self, + target_id: &str, + client_id: &str, + eligible: bool, + state: Value, + reason: Value, + result: Option, + ) -> Value { + let lease_ms = self.agent_target_lease_ms(); + let now = now_i64(); + let reporter_connected = eligible || self.overlay_connected(client_id); + let Some((_, pending)) = self + .pending_agent_targets + .iter_mut() + .find(|(k, _)| k == target_id) + else { + return json!({ "ok": true, "granted": false, "pending": false }); + }; + if !eligible { + // A report under an id no connection carries any more (the page + // unloaded between the broadcast and this claim landing) is not + // a participant's word: recorded, it could complete the roll + // call, or set its verdict, against the overlays that remain. + // An eligible claim is left alone: a lease a departed page holds + // lapses and a rescuer takes it, while refusing it would also + // refuse the renew a live overlay sends inside an EventSource + // reconnect gap, whose Go is still welcome. + if !reporter_connected { + return json!({ "ok": true, "granted": false, "pending": true }); + } + let reason_is_no_match = reason.as_str() == Some("no_match"); + // Only an overlay's first no_match word extends the grace: its + // re-reports while watching must not keep the roll call open. + let first_no_match_from_client = !pending + .reports + .iter() + .any(|r| r.client_id == client_id && r.reason.as_str() == Some("no_match")); + pending.reports.retain(|r| r.client_id != client_id); + pending.reports.push(AgentTargetReport { + client_id: client_id.to_string(), + state, + reason, + result, + }); + // A holder that turned busy hands the lease back, so the roll + // call can complete and an eligible tab's retry is granted at + // once instead of waiting for the lease to lapse. + if pending.owner.as_deref() == Some(client_id) { + pending.owner = None; + pending.claimed_until = 0; + } + if reason_is_no_match && first_no_match_from_client { + self.arm_agent_target_resolve_grace(target_id); + } + self.maybe_complete_agent_target_roll_call(target_id); + // `pending` tells a declining overlay whether to keep watching + // for a change of its word (an element that mounts late, a + // session that ends); false once the roll call or a result + // resolved the request. + let still_pending = self.pending_agent_targets.iter().any(|(k, _)| k == target_id); + return json!({ "ok": true, "granted": false, "pending": still_pending }); + } + // An eligible claim is the client's latest word: drop any earlier + // busy report, so a busy verdict only ever counts tabs still busy. + pending.reports.retain(|r| r.client_id != client_id); + let granted = pending.owner.is_none() + || pending.owner.as_deref() == Some(client_id) + || pending.claimed_until <= now; + if granted { + pending.owner = Some(client_id.to_string()); + pending.last_holder = Some(client_id.to_string()); + pending.claimed_until = now + lease_ms; + } + json!({ "ok": true, "granted": granted, "pending": true }) + } + /// JS: generationIsFenced(id) pub fn generation_is_fenced(&self, id: &str) -> bool { if id.is_empty() { @@ -1188,3 +1704,41 @@ pub fn strip_poller_owned_event_fields(event: &mut Map) { event.remove(key); } } + +/// `Number(process.env.X || '') || default`: a positive integer wins, anything +/// else falls back to the default. +fn env_positive_ms(env: &Env, key: &str) -> Option { + env.get(key) + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| *v > 0) +} + +/// The verdict for a held target once every connected overlay declined. A +/// tab that could serve later (mid-session, an apply in flight) outranks a +/// page that simply lacks the element, so the agent retries instead of +/// giving up; only when no page can resolve the target does the resolution +/// verdict (`no_match`, `invalid_selector`, ...) come back. +pub fn agent_target_verdict_from_reports(pending: &AgentTargetPending) -> Value { + let busy = pending + .reports + .iter() + .find(|r| r.reason.as_str() != Some("no_match")) + .or_else(|| pending.reports.first()); + if let Some(r) = busy.filter(|r| r.reason.as_str() != Some("no_match")) { + return json!({ "ok": false, "error": "busy", "state": r.state, "reason": r.reason }); + } + if let Some(result) = pending.reports.iter().find_map(|r| r.result.as_ref()) { + let mut verdict = result.clone(); + if let Some(obj) = verdict.as_object_mut() { + obj.insert("ok".into(), json!(false)); + } + return verdict; + } + let first = pending.reports.first(); + json!({ + "ok": false, + "error": "busy", + "state": first.map(|r| r.state.clone()).unwrap_or(Value::Null), + "reason": first.map(|r| r.reason.clone()).unwrap_or(Value::Null), + }) +} diff --git a/crates/live/src/session.rs b/crates/live/src/session.rs index d6405a635..e7d1b9d0d 100644 --- a/crates/live/src/session.rs +++ b/crates/live/src/session.rs @@ -508,6 +508,12 @@ pub fn apply_event(snapshot: &Map, entry: &Value) -> Map { set!("phase", json!("generate_requested")); + // `origin: "agent"` marks a Go the generate verb fired; the + // accept pipeline bakes those sessions itself. A plain Go + // carries no origin and its snapshot stays exactly as it was. + if let Some(origin) = ev("origin").filter(|v| truthy(v)) { + set!("origin", origin.clone()); + } set_if!("pageUrl", ev("pageUrl")); set_if!("expectedVariants", ev("count")); set_if!("pendingEventSeq", seq.as_ref()); diff --git a/cursor-plugin/skills/impeccable/SKILL.md b/cursor-plugin/skills/impeccable/SKILL.md index 890ba4653..b50ffe20a 100644 --- a/cursor-plugin/skills/impeccable/SKILL.md +++ b/cursor-plugin/skills/impeccable/SKILL.md @@ -63,7 +63,8 @@ Choose the mode from the requested surface, not the product, and persist it only | `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) | | `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) · native: [reference/adapt.native.md](reference/adapt.native.md) | | `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) | -| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) | +| `live` | Iterate | Visual variant mode: pick elements in the browser, iterate on alternatives | [reference/live.md](reference/live.md) | +| `generate [n] [action] [element]` | Iterate | Variants, versions, or alternatives of a named element to choose from in the live browser; no manual picking | [reference/generate.md](reference/generate.md) | Routing: diff --git a/cursor-plugin/skills/impeccable/reference/generate.md b/cursor-plugin/skills/impeccable/reference/generate.md new file mode 100644 index 000000000..b90330731 --- /dev/null +++ b/cursor-plugin/skills/impeccable/reference/generate.md @@ -0,0 +1,101 @@ +> **Additional context needed**: only the target element, when the request does not name one that resolves uniquely on the page. + +Generate is the fast lane into live mode: the user names an element, a direction, and a count in one sentence, and within a minute they are cycling through variants in their browser. One command boots the helper, hands the element to the overlay in the page your harness already shows (it scrolls to it, selects it, and fires the same Go a click fires) and returns the generate event; one edit writes the variants; one call replies and waits for the user's choice, which the helper bakes into source itself. This file owns the lane's plumbing; from the event onward the design work is [live.md](live.md)'s, unchanged, so read it in full now if you have not this session. + +**Web only.** Live mode's browser overlay has no native equivalent; on `ios` / `android` / `adaptive` projects, decline this command and offer `bolder` or `quieter` on the source instead. + +The plumbing is where the lane saves time: one command starts the session around the page your harness already shows, one call replies and waits, and nothing here is a browser you have to babysit. The design work is not where it saves time. Setup runs as for any command (`impeccable context`, this reference, craft-floor.md before the edit), and the variants are planned, written, and accepted exactly the way a live session plans, writes, and accepts them. + +Three prohibitions cover the known ways this command goes wrong: + +- **Never run init or document, and never ask for PRODUCT.md or DESIGN.md.** When they exist, the start command prints them under `boot` and you use them. When they do not, it says so (`contextMissing`, `contextNote`) and you extract the identity from the event (Step 3). A missing file is never a reason to interview the user inside this command; offer `init` in one line after the session ends. +- **Never hand-write a variants wrapper or invent a session id.** Only the browser mints session ids (8 hex characters, at Go). A missing event is fixed by rerunning Step 2, never with a direct source edit. +- **Do not act on hook findings while live markers are in the file**, and do not restyle variants to appease them; the accept verifies the file once the variant is permanent. + +## Step 1: Parse the request + +Three parts, all from the user's sentence: + +- **A number in the request**: that is the count. **No number**: 3. The protocol caps count at 8. +- **The direction wording** maps onto the live action vocabulary; never invent a new action value: + - **bold, bolder, stronger, punchier**: `bolder` + - **quiet, calmer, softer, toned down**: `quieter` + - **simpler, minimal, stripped**: `distill` + - **refined, tightened, polished**: `polish` + - **font and type words**: `typeset` + - **color words**: `colorize` + - **arrangement and spacing words**: `layout` + - **device and breakpoint words**: `adapt` + - **motion words**: `animate` + - **playful words**: `delight` + - **rule-breaking words**: `overdrive` + - **Wording that carries intent but no vocabulary word** ("make it feel like a bank", "warmer", "more premium"): `impeccable`, with the user's wording passed as the prompt. + - **An action fits AND extra intent rides along** ("bolder, but keep it monochrome"): that action, with the rest as the prompt. + - **The wording names no direction at all** ("better", "improve", "nicer", "different", "fresh", "new", "redesign", "fix", "some options", "ideas", "alternatives", or just "variants" with nothing else): Ask the user directly to clarify what you cannot infer. Ask one question, offering the vocabulary: *"Which direction should the variants take? bolder, quieter, simpler (distill), polished, typography (typeset), color (colorize), layout, motion (animate), playful (delight), or rule-breaking (overdrive)."* Map the answer with this list; an answer that is still open ("surprise me", "you pick") is `impeccable` with the user's original wording as the prompt, and Step 2 starts on that answer. +- **The element description** ("the pricing cards", "the hero heading"): Step 2 resolves it to a selector. + +Done when you hold an action from the vocabulary (asked for, when the request named no direction), a count from 1 to 8, and the element description. + +## Step 2: Reuse the page, then start + +**Reuse** the dev server already running and the tab your harness already shows it in; a second server or a second browser window is the failure this step prevents. + +1. **Find the dev server**, cheapest source first, and stop at the first hit: the user's message, a browser tab already on the app (Claude Code: an origin in `tabs_context`), a server your harness started (Claude Code: `preview_list`), a terminal that printed its URL. Its origin is your `--dev-url`. **No hit**: leave `--dev-url` off and run the start command with no wait; the boot probes for a running server and its verdict names the move. `browser_needed` carries the `devUrl` it found: open it as in 2, then rerun with `--dev-url --wait-for-browser 60000`. `no_dev_server` means nothing serves the app: start the dev script the way the verdict says (Claude Code: `preview_start`; Cursor: a background terminal; Codex: an exec you yield from), wait for its URL, then rerun with `--dev-url `. +2. **Open the page that renders the element in your browser, then start.** The route the request names, else the one `--target` serves; `--dev-url` takes only the origin. + - **Cursor** (`browser_navigate`) and **Claude Code** (`navigate`, which opens the Browser pane when it is closed and takes the `tabId` from `tabs_context` when a tab is already on that origin): open the URL, then run the start command with `--dev-url --wait-for-browser 60000`. The boot injects the overlay and the page reloads into it while the command waits. Your browser tool is the only opener on these harnesses; the engine ignores `--open` there. + - **No browser tool** (Codex, others): run the start command with `--open --wait-for-browser 120000`; it opens the system browser, and the longer wait covers the user finding the tab. **`browser_open_failed` back**: tell the user the `url` in one line and rerun with `--wait-for-browser 120000`. + +```bash +"/scripts/impeccable" live-generate --target src/App.jsx --dev-url http://127.0.0.1:5173/ --selector ".pricing-grid" --action bolder --count 3 --boot --wait-for-browser 60000 +``` + +Run it in the foreground in Cursor and Claude Code (it returns within the wait); on Codex, in an exec you yield from, the way Step 3 runs the poll. + +- `--target`: the file that renders the element when the request or the project makes it obvious; skip it otherwise. +- `--dev-url`: the origin from 1; omit it and the boot probes. +- `--selector`: a unique class first, then a landmark tag plus class, an id last (every variant mounts a copy of the element, so an id repeats in the DOM). **The request names a repeated component in plural** ("the pricing cards"): target the container that holds the set, so one scoped stylesheet restyles every instance. One read of the source file that renders the element is allowed when the selector is not obvious; `--dry-run` resolves and reports without starting anything when it is not certain. +- `--boot`: runs the lane's boot (PRODUCT.md and DESIGN.md loaded again for the helper, missing files tolerated, dev URL found, bottom bar hidden for the helper's lifetime) and reuses a helper that is already running. Its result rides along as `boot`. +- Also available: `--prompt`, `--text` (keep only matches whose visible text contains a snippet), `--index` (1-based pick among matches). + +Read the output in this order: `boot` (or `boot.contextMissing` with `boot.contextNote`: the page is the source of truth, per the note), then `event`, the generate event for `sessionId`, with the same `_instructions` a user's Go gets. Every verdict carries `_instructions`, and they win over your recollection of this file; the ones whose move is a decision of yours: + +- **`ambiguous`**: the candidates are listed; target their common container, or rerun with `--text ""` or `--index `. +- **`dev_server_gone`**: the dev server stopped answering while the command waited for the page (on Cursor, a server another chat started dies with that chat). Start it the way the verdict says, then rerun with `--dev-url `. +- **`no_match`**: the tab is on a route that does not render the element (navigate to the right route, rerun), or the selector is wrong (derive a better one from the source, or add `--text`). +- **`config_missing` / `config_invalid`** under `bootError`: follow [live-setup.md](live-setup.md) first, then rerun. +- **`event: null`** with `ok: true`: the event was slower than the wait; run `"/scripts/impeccable" live-poll` once to collect it, then continue. + +Done when the output shows `ok: true`, a `sessionId`, and an `event`, reached with at most one server started and one tab opened by you. + +## Step 3: Generate + +The event is a standard `generate` event: the picked element's context, a preflighted scaffold, and `_instructions` naming the action's reference, the planning section, and the exact splice. Handle it exactly per live.md's **Handle generate**, which owns everything from the identity lock to the done reply: read the action's reference and craft-floor.md as it says, plan per section 4 (identity first, then mode, then three different primary axes, then the squint test), declare knobs per section 7, and deliver per section 6 (a complete replacement of the element per variant, the preview CSS plus every variant in one edit at the scaffold's splice). The lane changes nothing about what a variant may be: the moves a live session would make on this element (a promoted tier, a restructured set, a reordered card, a different surface) are open here too. Never screenshot the page; the overlay preview is the review channel until accept. + +**Reply and wait in one call**, with the file you wrote: + +```bash +"/scripts/impeccable" live-poll --reply EVENT_ID done --file src/App.jsx --then-poll +``` + +This replies done (the browser mounts the variants) and then blocks until the user's choice arrives, so run it the way your harness runs a long wait: **Claude Code** in the foreground with your tool's longest timeout (600000 ms), so you are paused until the choice arrives; **Codex** in a yielded foreground exec; **Cursor** in a background terminal with notify on `"type":"(accept|discard|variant_mount_failed|exit)"`. Never pass a short `--timeout=`. While it runs there is nothing else to do: never sleep and never poll its output on a timer; a harness that backgrounds it wakes you when it returns. `{"type":"timeout"}` means the user has not chosen yet: run `live-poll` again and keep waiting. If the edit fails after the browser flipped to GENERATING, `--reply EVENT_ID error "Short reason"` (without `--then-poll`) so the bar resets. + +Then tell the user, in one line, where their variants are: *"Three [bolder] variants are live on [the pricing cards]: cycle with the floating bar's arrows, adjust the Tune knobs, and Accept the keeper."* + +Outside the replace path, read the matching live.md section before acting: `scaffold.previewMode: "svelte-component"` (Svelte previews are edited as components, and their accept is mechanical), `mode: "insert"`, `variant_mount_failed`, `steer`, `manual_edit_apply`, and any `fallback: "agent-driven"` wrap error. + +## Step 4: Accept and close + +The call from Step 3 returns the user's choice. **`discard`**: nothing to do. **`accept`**: `_acceptResult.carbonize: true` is the normal case, and the cleanup is live.md's **Required after accept**, unchanged: move the accepted variant's rules into the stylesheet that already owns the element with real selectors, bake the chosen knob values in, unwrap the element and drop every `data-impeccable-*` attribute, delete the inline ``, `{/* … */}` comments, `style={{ display: 'contents' }}` on the variant div. -Result `{handled:true, file: rel, carbonize:boolean, todo?:'REQUIRED before next poll: carbonize cleanup in . See reference/live.md "Required after accept".'}`. Discard: replace range with deindented original → `{handled:true, file, carbonize:false}`. After accept with `--page-url`, buffered manual-edit ops whose original/new text appears as an exact text segment in the replaced original block are dropped from `pending-manual-edits.json`. +Result `{handled:true, file: rel, carbonize:boolean, todo?:'REQUIRED before next poll: carbonize cleanup in . See reference/live.md "Required after accept".', bakeSkipped?}`. Discard: replace range with deindented original → `{handled:true, file, carbonize:false}`. + +**Mechanical bake** (`bake.rs`): only on `--bake` (never by default and never on `--no-bake`; the generate lane's accept carbonizes exactly like plain live's, so the agent integrates the accepted variant per live.md), a knob-free HTML/JSX accept is made permanent instead of leaving the carbonize block. Refused (falls back to the carbonize block, with `bakeSkipped:`) when: `--param-values` is non-empty; the accepted variant carries `data-impeccable-*` or `data-p-*` inside it; the preview CSS uses `var(--p-*)`, `data-p-*`, or `data-impeccable-params`; the variant's root is a component (``, ``: what it renders is unknown, and its `className` or `id` prop may never reach that element) or has neither an id nor a static class (`className={expr}`); the anchor cannot be shown to match the accepted element alone (the journaled generate event's `element.anchor` must be the same selector, the id or the tag and class set, and its `element.anchorMatches` must be 1: ` matches N elements on the page; a lasting rule on it would restyle them all`, a different anchor, and a missing descriptor or count each name themselves); a `:scope` cannot be rewritten (sibling combinators, `:scope` not at the front, nested `@scope`); the accepted variant declares no rule; or no destination stylesheet exists. The rewrite: the accepted `@scope ([data-impeccable-variant="N"])` block is flattened and every selector re-anchored on the root tag's selector (`#id`, else `tag.class.class`): `:scope > .x` → `` merged with `.x` (the wrapper's only child is the element itself, so the child compound rides on the anchor, a class the anchor already has once, a type only when it is the anchor's own; `#id` anchors take any type), `:scope .x` → ` .x`, `:scope:hover > .x` → `.x:hover`, bare `:scope` → ``; Astro's `[data-impeccable-variant="N"] > .x` prefix the same way; nested `@media`/`@supports` inside the block keep their prelude; top-level `@keyframes`/`@font-face` are kept, other variants' blocks dropped. Destination: for `.jsx`/`.tsx` the `.css` file under the app root (skipping node_modules/.git/.impeccable/dist/build/coverage/framework caches, depth ≤ 6, `.min.css` and generated or git-ignored files excluded) with the most rules naming the anchor's id or classes, else the only `.css` file; for other files the page's own last `