diff --git a/crates/ff-rdp-cli/src/cli/args.rs b/crates/ff-rdp-cli/src/cli/args.rs index ce6d556b..ae015136 100644 --- a/crates/ff-rdp-cli/src/cli/args.rs +++ b/crates/ff-rdp-cli/src/cli/args.rs @@ -717,6 +717,7 @@ pass --no-isolate, to get the script completion value back. Declaration-free scripts are untouched by this rule; they never enter the wrap. Output: {\"results\": , \"total\": 1, \"meta\": {...}} +With --format text, eval prints just the value and no hint line: a plain object or array as JSON of its own enumerable properties (up to 6 levels and 200 objects, with a stderr warning when cut), non-JSON values (functions, Date, BigInt, Symbol, DOM nodes) as \"[Kind]\" placeholders; use --stringify for exact JSON.stringify output. Errors: a script that throws, or whose resulting Promise rejects, exits 1 with {\"error\": \"\", \"error_type\": \"User\", \"stack\": \"...\"}; a rejection @@ -806,7 +807,7 @@ The command primes Firefox's message cache (startListeners) before reading it, so messages a separate earlier `ff-rdp eval 'console.log(...)'` emitted are visible on this fresh connection. Use --follow to stream live messages. -Output: {\"results\": [{\"level\": \"...\", \"message\": \"...\", \"source\": \"...\", \"line\": N, \"timestamp\": N}], \"summary\": {\"total\": N, \"shown\": Z, \"by_level\": {...}, \"matched\": M}, \"total\": N, \"meta\": {...}}")] +Output: {\"results\": [{\"level\": \"...\", \"message\": \"...\", \"source\": \"...\", \"line\": N, \"timestamp\": N}], \"summary\": {\"total\": ALL, \"shown\": Z, \"by_level\": {...}, \"matched\": M}, \"total\": M, \"meta\": {...}} — ALL counts every captured message, M those matching --level/--pattern (by_level counts them too), Z those shown after --limit")] Console(ConsoleArgs), /// Show network requests captured by the WatcherActor. /// diff --git a/crates/ff-rdp-cli/src/commands/console.rs b/crates/ff-rdp-cli/src/commands/console.rs index f05ec0e1..e4a1ea98 100644 --- a/crates/ff-rdp-cli/src/commands/console.rs +++ b/crates/ff-rdp-cli/src/commands/console.rs @@ -158,10 +158,7 @@ pub fn run(cli: &Cli, level: Option<&str>, pattern: Option<&str>) -> Result<(), { obj.insert( "hint".to_string(), - json!( - "No console messages captured. Use --follow to stream live messages, \ - or generate some with: ff-rdp eval 'console.log(\"test\")'" - ), + json!(empty_result_hint(raw_total, level, pattern)), ); } @@ -169,6 +166,45 @@ pub fn run(cli: &Cli, level: Option<&str>, pattern: Option<&str>) -> Result<(), OutputPipeline::from_cli(cli)?.finalize_with_hints(&envelope, Some(&hint_ctx)) } +/// The `hint` for a `console` read that matched nothing. `raw_total` is every +/// cached message before `--level`/`--pattern`: when it is non-zero the +/// filters removed them all, which is a different situation (and a different +/// fix) from a page that logged nothing. +fn empty_result_hint(raw_total: usize, level: Option<&str>, pattern: Option<&str>) -> String { + if raw_total == 0 { + return "No console messages captured. Use --follow to stream live messages, \ + or generate some with: ff-rdp eval 'console.log(\"test\")'" + .to_owned(); + } + let mut filters = Vec::new(); + if let Some(l) = level { + if !l.is_empty() && l.chars().all(|c| c.is_ascii_alphanumeric()) { + filters.push(format!("--level {l}")); + } else { + filters.push(format!("--level {}", sh_single_quote(l))); + } + } + if let Some(p) = pattern { + filters.push(format!("--pattern {}", sh_single_quote(p))); + } + let noun = if raw_total == 1 { + "message" + } else { + "messages" + }; + format!( + "{raw_total} console {noun} captured, none matched {}. \ + Run without the filter to see them.", + filters.join(" ") + ) +} + +/// POSIX single-quote `s` so the hint's flag can be pasted back into a shell: +/// each `'` becomes `'\''`. +fn sh_single_quote(s: &str) -> String { + format!("'{}'", s.replace('\'', r"'\''")) +} + /// Prime the WebConsole actor's message cache so a following /// `getCachedMessages` sees `console.log` / page-error output that was emitted /// before this connection was opened. @@ -586,6 +622,33 @@ impl ConsoleDeliveries { mod tests { use super::*; + #[test] + fn empty_result_hint_distinguishes_filtered_out_from_nothing_captured() { + assert!(empty_result_hint(0, None, None).starts_with("No console messages captured")); + assert!( + empty_result_hint(0, Some("error"), Some("x")) + .starts_with("No console messages captured") + ); + assert!( + empty_result_hint(2, Some(""), None).contains("none matched --level ''."), + "an empty --level must stay visible" + ); + assert_eq!( + empty_result_hint(2, Some("a b"), Some("it's")), + r"2 console messages captured, none matched --level 'a b' --pattern 'it'\''s'. Run without the filter to see them." + ); + assert_eq!( + empty_result_hint(3, None, Some("nomatch")), + "3 console messages captured, none matched --pattern 'nomatch'. \ + Run without the filter to see them." + ); + assert_eq!( + empty_result_hint(1, Some("error"), Some("boom")), + "1 console message captured, none matched --level error --pattern 'boom'. \ + Run without the filter to see them." + ); + } + #[test] fn console_identity_excludes_only_grip_handles() { let events: Vec = serde_json::from_str(include_str!( diff --git a/crates/ff-rdp-cli/src/commands/eval.rs b/crates/ff-rdp-cli/src/commands/eval.rs index 1d2f3abf..2c91d368 100644 --- a/crates/ff-rdp-cli/src/commands/eval.rs +++ b/crates/ff-rdp-cli/src/commands/eval.rs @@ -2,8 +2,8 @@ use std::io::Read; use anyhow::Context as _; use ff_rdp_core::{ - ActorId, EvaluateScope, Grip, LongStringActor, ObjectActor, TargetEvent, WebConsoleActor, - sanitize_for_terminal, + ActorId, EvaluateScope, Grip, LongStringActor, ObjectActor, PropertyDescriptor, RdpTransport, + TargetEvent, WebConsoleActor, sanitize_for_terminal, }; use serde_json::json; @@ -1476,6 +1476,12 @@ pub fn run( ) -> Result<(), AppError> { let script = load_script(script, file, use_stdin)?; let scope = cli_scope.to_scope(); + // `--format text` (without --jq) prints the bare value. It does NOT change + // what runs: the script is sent exactly as in JSON mode, and a plain + // Object/Array grip is turned into its JSON value on this side afterwards + // (see [`plain_value`]), so `--no-isolate`, completion values and + // non-JSON results (DOM nodes, BigInt, `window`) behave as in JSON mode. + let text_value = !stringify && cli.format == "text" && cli.jq.is_none(); // iter-165: `--no-isolate` is honoured again. By default a script that // declares something at top level runs inside a per-call IIFE, so its // `const`/`let`/`class` never leak into the next `eval`; `--no-isolate` @@ -1593,6 +1599,36 @@ pub fn run( return Err(err); } + // `--format text`: a plain Object/Array grip prints as its JSON value, + // read through the object actors while they are still alive. Anything + // else (a DOM node, Map, `window`, a failed read) keeps the grip output. + if text_value + && let Grip::Object { ref class, .. } = eval_result.result + && is_plain_container(class) + { + let mut budget = TextValueBudget::new(); + match plain_value( + ctx.transport_mut(), + &eval_result.result, + TEXT_VALUE_MAX_DEPTH, + &mut budget, + ) { + Ok(value) => { + if budget.truncated { + // stderr-ok: (b) the value printed is incomplete; say so + // without touching stdout's JSON. + eprintln!("{TEXT_VALUE_TRUNCATED_WARNING}"); + } + return print_text_value(&value); + } + Err(e) => { + // stderr-ok: (b) best-effort, warn-and-continue — the grip + // output below is still a correct (if less useful) answer. + eprintln!("warning: could not read the object's values: {e}"); + } + } + } + // For object grips, enrich the output with the list of own property names. // Best-effort: if the actor is gone or the request fails, we skip silently. // @@ -1601,7 +1637,7 @@ pub fn run( if let Grip::Object { ref actor, .. } = eval_result.result { match ObjectActor::prototype_and_properties(ctx.transport_mut(), actor.as_ref()) { Ok(pap) => { - let names: Vec<&str> = pap.own_properties.keys().map(String::as_str).collect(); + let names: Vec<&str> = pap.own_properties.iter().map(|(k, _)| k.as_str()).collect(); result_json["propertyNames"] = json!(names); } Err(e) => { @@ -1657,15 +1693,24 @@ pub fn run( None, cli.is_verbose(), ); - let envelope = output::envelope(&result_json, 1, &meta); + let mut envelope = output::envelope(&result_json, 1, &meta); + let grip_hint_suppressed = + stringify || cli.no_hints || cli.jq.is_some() || cli.format == "text"; + if wants_grip_hint(&eval_result.result, grip_hint_suppressed) + && let Some(obj) = envelope.as_object_mut() + { + obj.insert("hint".to_owned(), json!(OBJECT_GRIP_HINT)); + } let hint_ctx = HintContext::new(HintSource::Eval); let pipeline = OutputPipeline::from_cli(cli)?; // When the caller passes `--stringify`, they're extracting a raw value; // appending the trailing "-> ff-rdp …" hint line would pollute their // captured stdout (dogfood-49 #6). Suppress hints unconditionally in - // that mode — symmetric with `--jq` and `--no-hints`. - let pipeline = if stringify { + // that mode — symmetric with `--jq` and `--no-hints`. `--format text` is + // the same request for a bare value, and the generic "check console + // errors" tip has nothing to do with the value asked for. + let pipeline = if stringify || cli.format == "text" { pipeline.without_hints() } else { pipeline @@ -1673,6 +1718,217 @@ pub fn run( pipeline.finalize_with_hints(&envelope, Some(&hint_ctx)) } +/// Top-level `hint` on a default (JSON) result that is a plain Object/Array +/// grip: the grip carries actor metadata and a shallow preview (nested arrays +/// show only `length`), not the value, and agents otherwise wrap +/// `JSON.stringify` themselves and get a JSON string inside JSON. +const OBJECT_GRIP_HINT: &str = "results is a Firefox object grip (actor metadata, not the value); \ + re-run with --stringify to get the value as JSON"; + +/// Whether the envelope gets [`OBJECT_GRIP_HINT`]: only for a plain +/// Object/Array grip (JSON.stringify of a DOM node or `window` is no better +/// than the grip), and never when `suppressed` — under `--stringify` (the +/// value is already there), `--no-hints`, `--jq` (keeps the envelope shape +/// existing filters see) or `--format text`. +fn wants_grip_hint(result: &Grip, suppressed: bool) -> bool { + !suppressed && matches!(result, Grip::Object { class, .. } if is_plain_container(class)) +} + +/// How deep `--format text` follows nested objects/arrays before printing a +/// `"[Class]"` placeholder; bounds the requests (and cycles). +const TEXT_VALUE_MAX_DEPTH: usize = 6; +/// How many object actors `--format text` reads in total for one result. +const TEXT_VALUE_MAX_FETCHES: usize = 200; +/// Longest array `--format text` prints, holes included. +const TEXT_VALUE_MAX_ARRAY_LEN: usize = 100_000; + +/// Grip classes `--format text` turns into a JSON value. +fn is_plain_container(class: &str) -> bool { + class == "Object" || class == "Array" +} + +/// Where [`plain_value`] reads object properties and long strings from — the +/// live RDP transport, or a canned map in unit tests. +trait GripReader { + fn own_properties( + &mut self, + actor: &str, + ) -> Result, AppError>; + fn long_string(&mut self, actor: &str, length: u64) -> Result; +} + +impl GripReader for RdpTransport { + fn own_properties( + &mut self, + actor: &str, + ) -> Result, AppError> { + Ok(ObjectActor::prototype_and_properties(self, actor)?.own_properties) + } + + fn long_string(&mut self, actor: &str, length: u64) -> Result { + Ok(LongStringActor::full_string(self, actor, length)?) + } +} + +/// The read budget for one `--format text` value, and whether any cap cut it. +struct TextValueBudget { + fetches: usize, + truncated: bool, +} + +impl TextValueBudget { + fn new() -> Self { + Self { + fetches: TEXT_VALUE_MAX_FETCHES, + truncated: false, + } + } +} + +/// The stderr warning when a `--format text` value hit a cap. +const TEXT_VALUE_TRUNCATED_WARNING: &str = "warning: --format text stopped reading the value at \ + its caps (6 levels deep, 200 objects, 100000 array items); values past them print as \ + \"[Object]\"/\"[Array]\"/\"[truncated]\" — use --stringify for the full value"; + +/// A `"[Kind]"` placeholder for a typed non-object grip (BigInt, Symbol, …), +/// so actor metadata never leaks into `--format text` output. +fn typed_value_placeholder(v: &serde_json::Value) -> Option { + let kind = v.get("type")?.as_str()?; + Some(match kind { + "BigInt" => match v.get("text").and_then(serde_json::Value::as_str) { + Some(text) => format!("[BigInt {text}]"), + None => "[BigInt]".to_owned(), + }, + "symbol" => match v.get("name").and_then(serde_json::Value::as_str) { + Some(name) => format!("[Symbol {name}]"), + None => "[Symbol]".to_owned(), + }, + other => format!("[{other}]"), + }) +} + +/// Turn a grip into JSON for `--format text`. This is NOT `JSON.stringify`: +/// plain Objects and Arrays are read through their actors (own enumerable +/// properties, in Firefox's order) down to `depth` levels within `budget`; +/// every other value that is not JSON — functions, Date, Map, DOM nodes, +/// BigInt, Symbol — becomes a `"[Kind]"` placeholder, an accessor becomes +/// `"[Getter]"`, and anything past a cap becomes `"[Object]"`/`"[Array]"` +/// with `budget.truncated` set. `undefined` drops out of an object and is +/// `null` in an array; NaN/±Infinity are `null`. +fn plain_value( + reader: &mut impl GripReader, + grip: &Grip, + depth: usize, + budget: &mut TextValueBudget, +) -> Result { + use serde_json::Value; + Ok(match grip { + Grip::Null | Grip::Undefined | Grip::Inf | Grip::NegInf | Grip::NaN => Value::Null, + Grip::NegZero => json!(0), + Grip::LongString { actor, length, .. } => { + Value::String(reader.long_string(actor.as_ref(), *length)?) + } + Grip::Value(v) => typed_value_placeholder(v).map_or_else(|| v.clone(), Value::String), + Grip::Object { actor, class, .. } => { + if !is_plain_container(class) { + return Ok(Value::String(format!("[{class}]"))); + } + if depth == 0 || budget.fetches == 0 { + budget.truncated = true; + return Ok(Value::String(format!("[{class}]"))); + } + budget.fetches -= 1; + let props = reader.own_properties(actor.as_ref())?; + if class == "Array" { + plain_array(reader, &props, depth, budget)? + } else { + let mut map = serde_json::Map::new(); + for (key, desc) in &props { + match desc { + PropertyDescriptor::Data { + value, enumerable, .. + } if *enumerable && !matches!(value, Grip::Undefined) => { + map.insert(key.clone(), plain_value(reader, value, depth - 1, budget)?); + } + PropertyDescriptor::Accessor { enumerable, .. } if *enumerable => { + map.insert(key.clone(), json!("[Getter]")); + } + _ => {} + } + } + Value::Object(map) + } + } + }) +} + +/// The array half of [`plain_value`]: index properties in order, holes as +/// `null`, padded with `null` up to `length`, an accessor index as +/// `"[Getter]"`. Never longer than [`TEXT_VALUE_MAX_ARRAY_LEN`] (then it ends +/// in `"[truncated]"`), so neither `new Array(1e9)` nor `a[1e9] = 1` can +/// allocate a billion slots. +fn plain_array( + reader: &mut impl GripReader, + props: &[(String, PropertyDescriptor)], + depth: usize, + budget: &mut TextValueBudget, +) -> Result { + let length = props + .iter() + .find_map(|(key, desc)| match desc { + PropertyDescriptor::Data { + value: Grip::Value(v), + .. + } if key == "length" => v.as_u64(), + _ => None, + }) + .and_then(|n| usize::try_from(n).ok()) + .unwrap_or(0); + let mut indexed: Vec<(usize, &PropertyDescriptor)> = props + .iter() + .filter_map(|(key, desc)| { + key.parse::() + .ok() + .filter(|i| i.to_string() == *key) + .map(|i| (i, desc)) + }) + .collect(); + indexed.sort_by_key(|(i, _)| *i); + let mut items = Vec::with_capacity(indexed.len()); + let mut cut = false; + for (i, desc) in indexed { + if i >= TEXT_VALUE_MAX_ARRAY_LEN { + cut = true; + break; + } + items.resize(i, serde_json::Value::Null); + items.push(match desc { + PropertyDescriptor::Data { value, .. } => { + plain_value(reader, value, depth - 1, budget)? + } + PropertyDescriptor::Accessor { .. } => json!("[Getter]"), + }); + } + if length > TEXT_VALUE_MAX_ARRAY_LEN { + cut = true; + } + if cut { + items.push(json!("[truncated]")); + budget.truncated = true; + } else if items.len() < length { + items.resize(length, serde_json::Value::Null); + } + Ok(serde_json::Value::Array(items)) +} + +/// Print a `--format text` value: pretty JSON, no envelope and no hint line. +fn print_text_value(value: &serde_json::Value) -> Result<(), AppError> { + let pretty = serde_json::to_string_pretty(value) + .map_err(|e| AppError::Internal(anyhow::Error::new(e)))?; + println!("{pretty}"); + Ok(()) +} + /// Prefix of the string a captured Promise rejection resolves to; the rest is /// `{"name","message","stack"}` as JSON. See [`capture_rejection`]. const REJECTION_SENTINEL: &str = "__ffrdp_promise_rejected__:"; @@ -1797,6 +2053,168 @@ fn try_unwrap_json_string(value: &mut serde_json::Value) -> bool { mod tests { use super::*; + /// Canned `prototypeAndProperties` replies keyed by actor id. + #[derive(Default)] + struct FakeReader { + objects: std::collections::HashMap>, + reads: usize, + } + + impl GripReader for FakeReader { + fn own_properties( + &mut self, + actor: &str, + ) -> Result, AppError> { + self.reads += 1; + self.objects + .get(actor) + .cloned() + .ok_or_else(|| AppError::User(format!("no such actor {actor}"))) + } + + fn long_string(&mut self, _actor: &str, length: u64) -> Result { + Ok("x".repeat(usize::try_from(length).unwrap())) + } + } + + fn obj(actor: &str, class: &str) -> Grip { + Grip::Object { + actor: ActorId::from(actor.to_owned()), + class: class.to_owned(), + preview: None, + } + } + + fn data(value: Grip, enumerable: bool) -> PropertyDescriptor { + PropertyDescriptor::Data { + value, + writable: true, + enumerable, + configurable: true, + } + } + + fn val(v: serde_json::Value) -> Grip { + Grip::Value(v) + } + + #[test] + fn plain_value_reads_nested_objects_and_arrays_in_order() { + let getter = || PropertyDescriptor::Accessor { + get: None, + set: None, + enumerable: true, + configurable: true, + }; + let mut reader = FakeReader::default(); + reader.objects.insert( + "root".into(), + vec![ + ("z".into(), data(val(json!(1)), true)), + ("a".into(), data(obj("arr", "Array"), true)), + ("hidden".into(), data(val(json!(2)), false)), + ("gone".into(), data(Grip::Undefined, true)), + ("node".into(), data(obj("body", "HTMLBodyElement"), true)), + ("acc".into(), getter()), + ( + "big".into(), + data(val(json!({"type": "BigInt", "text": "10"})), true), + ), + ( + "sym".into(), + data( + val(json!({"type": "symbol", "actor": "s1", "name": "k"})), + true, + ), + ), + ], + ); + reader.objects.insert( + "arr".into(), + vec![ + ("0".into(), data(val(json!(1)), true)), + ("1".into(), getter()), + ("2".into(), data(Grip::NaN, true)), + ("length".into(), data(val(json!(5)), false)), + ], + ); + let mut budget = TextValueBudget::new(); + let v = plain_value(&mut reader, &obj("root", "Object"), 6, &mut budget).unwrap(); + assert_eq!( + serde_json::to_string(&v).unwrap(), + r#"{"z":1,"a":[1,"[Getter]",null,null,null],"node":"[HTMLBodyElement]","acc":"[Getter]","big":"[BigInt 10]","sym":"[Symbol k]"}"# + ); + assert_eq!(reader.reads, 2, "the DOM node is not read"); + assert!( + !budget.truncated, + "a placeholder for a non-plain value is not a cap" + ); + } + + #[test] + fn plain_value_stops_at_the_depth_cap_on_a_cycle() { + let mut reader = FakeReader::default(); + reader.objects.insert( + "self".into(), + vec![("me".into(), data(obj("self", "Object"), true))], + ); + let mut budget = TextValueBudget::new(); + let v = plain_value(&mut reader, &obj("self", "Object"), 2, &mut budget).unwrap(); + assert_eq!(v, json!({"me": {"me": "[Object]"}})); + assert_eq!(reader.reads, 2); + assert!(budget.truncated, "hitting the depth cap must be reported"); + } + + #[test] + fn plain_value_reports_an_exhausted_read_budget() { + let mut reader = FakeReader::default(); + reader.objects.insert( + "root".into(), + vec![("a".into(), data(obj("inner", "Object"), true))], + ); + let mut budget = TextValueBudget { + fetches: 1, + truncated: false, + }; + let v = plain_value(&mut reader, &obj("root", "Object"), 6, &mut budget).unwrap(); + assert_eq!(v, json!({"a": "[Object]"})); + assert!(budget.truncated); + } + + #[test] + fn plain_array_caps_a_far_sparse_index_and_a_huge_length() { + let mut reader = FakeReader::default(); + let props = vec![ + ("0".into(), data(val(json!("a")), true)), + ("01".into(), data(val(json!("not an index")), true)), + ("4000000000".into(), data(val(json!("far")), true)), + ]; + let mut budget = TextValueBudget::new(); + let v = plain_array(&mut reader, &props, 3, &mut budget).unwrap(); + assert_eq!(v, json!(["a", "[truncated]"])); + assert!(budget.truncated); + + let props = vec![("length".into(), data(val(json!(1_000_000_000_u64)), false))]; + let mut budget = TextValueBudget::new(); + let v = plain_array(&mut reader, &props, 3, &mut budget).unwrap(); + assert_eq!( + v, + json!(["[truncated]"]), + "new Array(1e9) must not allocate" + ); + assert!(budget.truncated); + } + + #[test] + fn grip_hint_only_for_plain_containers_when_not_suppressed() { + assert!(wants_grip_hint(&obj("o", "Object"), false)); + assert!(wants_grip_hint(&obj("o", "Array"), false)); + assert!(!wants_grip_hint(&obj("o", "HTMLBodyElement"), false)); + assert!(!wants_grip_hint(&obj("o", "Window"), false)); + assert!(!wants_grip_hint(&obj("o", "Object"), true)); + assert!(!wants_grip_hint(&val(json!(2)), false)); + } + // ── dogfooding session 64 #3: rejected Promises ──────────────────────── #[test] diff --git a/crates/ff-rdp-cli/tests/e2e/console.rs b/crates/ff-rdp-cli/tests/e2e/console.rs index 59ddda6e..d181c096 100644 --- a/crates/ff-rdp-cli/tests/e2e/console.rs +++ b/crates/ff-rdp-cli/tests/e2e/console.rs @@ -208,6 +208,82 @@ fn console_no_match_returns_empty() { assert_eq!(json["results"].as_array().unwrap().len(), 0); } +/// `--pattern nomatch` with 3 messages cached: top-level `total` is the +/// matched count (0), `summary.total` is every message (3), and the hint says +/// the filter removed them rather than "No console messages captured". +#[test] +fn console_pattern_no_match_hint_names_the_filter() { + let server = console_server(); + let port = server.port(); + let handle = std::thread::spawn(move || server.serve_one()); + + let mut args = base_args(port); + args.extend([ + "console".to_owned(), + "--pattern".to_owned(), + "nomatch".to_owned(), + ]); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!(output.status.success()); + + let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(json["total"], 0); + assert_eq!(json["summary"]["total"], 3); + assert_eq!(json["summary"]["matched"], 0); + assert_eq!( + json["hint"], + "3 console messages captured, none matched --pattern 'nomatch'. \ + Run without the filter to see them." + ); +} + +/// An empty cache keeps the "No console messages captured" hint. +#[test] +fn console_nothing_captured_hint() { + let mut empty = load_fixture("get_cached_messages_response.json"); + empty["messages"] = json!([]); + let server = MockRdpServer::new() + .on("listTabs", load_fixture("list_tabs_response.json")) + .on("getTarget", load_fixture("get_target_response.json")) + .on( + "startListeners", + load_fixture("start_listeners_response.json"), + ) + .on("getCachedMessages", empty); + let port = server.port(); + let handle = std::thread::spawn(move || server.serve_one()); + + let mut args = base_args(port); + args.push("console".to_owned()); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!(output.status.success()); + + let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(json["total"], 0); + assert_eq!(json["summary"]["total"], 0); + assert!( + json["hint"] + .as_str() + .unwrap_or_default() + .starts_with("No console messages captured"), + "envelope: {json}" + ); +} + #[test] fn console_handles_page_error_messages() { // Verify that pageError-type messages are parsed alongside consoleAPICall messages. diff --git a/crates/ff-rdp-cli/tests/e2e/eval.rs b/crates/ff-rdp-cli/tests/e2e/eval.rs index 2fa34bf5..d215350b 100644 --- a/crates/ff-rdp-cli/tests/e2e/eval.rs +++ b/crates/ff-rdp-cli/tests/e2e/eval.rs @@ -130,6 +130,11 @@ fn eval_object_result() { json["results"]["propertyNames"], serde_json::json!(["a", "b"]) ); + let hint = json["hint"].as_str().unwrap_or_default(); + assert!( + hint.contains("object grip") && hint.contains("--stringify"), + "an object-grip result must carry a hint naming --stringify; envelope: {json}" + ); let requests = request_log.lock().unwrap(); let property_requests: Vec<_> = requests @@ -647,6 +652,219 @@ fn eval_stringify_text_suppresses_hints() { ); } +/// `eval --format text '1+1'` prints the bare value and no `-> ff-rdp …` +/// hint line (the generic "check console errors" tip has nothing to do with +/// the value the caller asked for). +#[test] +fn eval_text_scalar_has_no_hint_line() { + let server = eval_server("eval_result_number.json"); + let port = server.port(); + let handle = std::thread::spawn(move || server.serve_one()); + + let mut args = base_args(port); + args.extend([ + "eval".to_owned(), + "--format".to_owned(), + "text".to_owned(), + "1 + 41".to_owned(), + ]); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!( + output.status.success(), + "expected success, stderr: {}", + support::output_note(&output) + ); + assert_eq!(String::from_utf8_lossy(&output.stdout), "42\n"); +} + +/// Mock for `eval '({z: 1, a: [2, {b: "x"}]})'`: the recorded eval result +/// plus the recorded `prototypeAndProperties` replies for the object, its +/// array and the object inside that, served in the order the CLI asks. +fn nested_object_server() -> MockRdpServer { + let pap = |name: &str| (load_fixture(name), Vec::new()); + let target = load_fixture("get_target_response.json"); + // The evaluationResult event is matched by its `from`; this recording + // came from another session's console actor, so re-address it to the one + // `get_target_response.json` hands out — the same replay adaptation the + // mock applies to replies (iter-136). + let mut result = load_fixture("eval_result_object_nested.json"); + result["from"] = target["frame"]["consoleActor"].clone(); + MockRdpServer::new() + .on("listTabs", load_fixture("list_tabs_response.json")) + .on("getTarget", target) + .on_with_followup( + "evaluateJSAsync", + load_fixture("eval_immediate_object_nested.json"), + result, + ) + .on_sequence( + "prototypeAndProperties", + vec![ + pap("prototype_and_properties_object_nested.json"), + pap("prototype_and_properties_array_nested.json"), + pap("prototype_and_properties_inner_nested.json"), + ], + ) +} + +/// `eval --format text` on a plain object prints its value as JSON, read +/// from the object actors on this side. The script is sent as in JSON mode, +/// without the --stringify wrap, so text mode does not change what runs. +#[test] +fn eval_text_object_prints_json_value() { + let server = nested_object_server(); + let port = server.port(); + let request_log = server.request_log(); + let handle = std::thread::spawn(move || server.serve_one()); + + let script = "({z: 1, a: [2, {b: 'x'}]})"; + let mut args = base_args(port); + args.extend([ + "eval".to_owned(), + "--format".to_owned(), + "text".to_owned(), + script.to_owned(), + ]); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!( + output.status.success(), + "expected success, stderr: {}", + support::output_note(&output) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let value: serde_json::Value = + serde_json::from_str(&stdout).expect("text output must be one JSON value"); + assert_eq!( + serde_json::to_string(&value).unwrap(), + r#"{"z":1,"a":[2,{"b":"x"}]}"#, + "keys keep Firefox's order" + ); + + let requests = request_log.lock().unwrap(); + let eval_request = requests + .iter() + .find(|r| r["type"] == "evaluateJSAsync") + .expect("an evaluateJSAsync request"); + assert!( + !eval_request["text"] + .as_str() + .unwrap_or_default() + .contains("circular reference detected"), + "--format text must not add the --stringify wrap; request: {eval_request}" + ); +} + +/// `--format text --jq` keeps the JSON envelope (the grip), so the filter +/// sees the same fields as in JSON mode. +#[test] +fn eval_text_with_jq_keeps_the_grip() { + let server = eval_server("eval_result_object.json").on( + "prototypeAndProperties", + load_fixture("prototype_and_properties_response.json"), + ); + let port = server.port(); + let handle = std::thread::spawn(move || server.serve_one()); + + let mut args = base_args(port); + args.extend([ + "eval".to_owned(), + "--format".to_owned(), + "text".to_owned(), + "--jq".to_owned(), + ".results.class".to_owned(), + "({a: 1, b: [2,3]})".to_owned(), + ]); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!( + output.status.success(), + "expected success, stderr: {}", + support::output_note(&output) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Object"), "got: {stdout:?}"); +} + +/// `--no-hints` drops the object-grip `hint` from the JSON envelope. +#[test] +fn eval_object_no_hints_drops_grip_hint() { + let server = eval_server("eval_result_object.json").on( + "prototypeAndProperties", + load_fixture("prototype_and_properties_response.json"), + ); + let port = server.port(); + let handle = std::thread::spawn(move || server.serve_one()); + + let mut args = base_args(port); + args.extend([ + "--no-hints".to_owned(), + "eval".to_owned(), + "({a: 1, b: [2,3]})".to_owned(), + ]); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!( + output.status.success(), + "expected success, stderr: {}", + support::output_note(&output) + ); + let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(json["results"]["class"], "Object"); + assert!(json.get("hint").is_none(), "envelope: {json}"); +} + +/// A `--stringify` result is the value, so it carries no grip hint. +#[test] +fn eval_stringify_json_has_no_grip_hint() { + let server = eval_server("eval_result_stringify.json"); + let port = server.port(); + let handle = std::thread::spawn(move || server.serve_one()); + + let mut args = base_args(port); + args.extend([ + "eval".to_owned(), + "--stringify".to_owned(), + "[1]".to_owned(), + ]); + + let output = std::process::Command::new(ff_rdp_bin()) + .args(&args) + .output() + .expect("failed to spawn ff-rdp"); + + handle.join().unwrap(); + + assert!(output.status.success()); + let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(json.get("hint").is_none(), "envelope: {json}"); +} + // --------------------------------------------------------------------------- // iter-161 Theme E: meta.eval_path is gone // --------------------------------------------------------------------------- diff --git a/crates/ff-rdp-cli/tests/fixtures/eval_immediate_object_nested.json b/crates/ff-rdp-cli/tests/fixtures/eval_immediate_object_nested.json new file mode 100644 index 00000000..95717d92 --- /dev/null +++ b/crates/ff-rdp-cli/tests/fixtures/eval_immediate_object_nested.json @@ -0,0 +1,4 @@ +{ + "resultID": "0", + "from": "server1.conn0.child0/consoleActor3" +} diff --git a/crates/ff-rdp-cli/tests/fixtures/eval_result_object_nested.json b/crates/ff-rdp-cli/tests/fixtures/eval_result_object_nested.json new file mode 100644 index 00000000..9877056b --- /dev/null +++ b/crates/ff-rdp-cli/tests/fixtures/eval_result_object_nested.json @@ -0,0 +1,50 @@ +{ + "type": "evaluationResult", + "resultID": "0", + "hasException": false, + "input": "({z: 1, a: [2, {b: 'x'}]})", + "result": { + "type": "object", + "actor": "server1.conn0.child0/obj19", + "class": "Object", + "ownPropertyLength": 2, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "Object", + "ownProperties": { + "z": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": 1 + }, + "a": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": { + "type": "object", + "actor": "server1.conn0.child0/obj20", + "class": "Array", + "ownPropertyLength": 3, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "ArrayLike", + "length": 2 + } + } + } + }, + "ownPropertiesLength": 2 + } + }, + "startTime": 1795736201313.045, + "timestamp": 1795736201315.869, + "from": "server1.conn0.child0/consoleActor3" +} diff --git a/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_array_nested.json b/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_array_nested.json new file mode 100644 index 00000000..ff74b796 --- /dev/null +++ b/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_array_nested.json @@ -0,0 +1,61 @@ +{ + "prototype": { + "type": "object", + "actor": "server1.conn0.child0/obj25", + "class": "Array", + "ownPropertyLength": 40, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "ArrayLike", + "length": 0, + "items": [] + } + }, + "ownProperties": { + "0": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": 2 + }, + "1": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": { + "type": "object", + "actor": "server1.conn0.child0/obj24", + "class": "Object", + "ownPropertyLength": 1, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "Object", + "ownProperties": { + "b": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": "x" + } + }, + "ownPropertiesLength": 1 + } + } + }, + "length": { + "configurable": false, + "enumerable": false, + "writable": true, + "value": 2 + } + }, + "ownSymbols": [], + "safeGetterValues": {}, + "from": "server1.conn0.child0/obj21" +} diff --git a/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_inner_nested.json b/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_inner_nested.json new file mode 100644 index 00000000..f6b3ee28 --- /dev/null +++ b/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_inner_nested.json @@ -0,0 +1,28 @@ +{ + "prototype": { + "type": "object", + "actor": "server1.conn0.child0/obj26", + "class": "Object", + "ownPropertyLength": 12, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "Object", + "ownProperties": {}, + "ownPropertiesLength": 12 + } + }, + "ownProperties": { + "b": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": "x" + } + }, + "ownSymbols": [], + "safeGetterValues": {}, + "from": "server1.conn0.child0/obj24" +} diff --git a/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_object_nested.json b/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_object_nested.json new file mode 100644 index 00000000..b6a8e6e7 --- /dev/null +++ b/crates/ff-rdp-cli/tests/fixtures/prototype_and_properties_object_nested.json @@ -0,0 +1,60 @@ +{ + "prototype": { + "type": "object", + "actor": "server1.conn0.child0/obj23", + "class": "Object", + "ownPropertyLength": 12, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "Object", + "ownProperties": {}, + "ownPropertiesLength": 12 + } + }, + "ownProperties": { + "z": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": 1 + }, + "a": { + "configurable": true, + "enumerable": true, + "writable": true, + "value": { + "type": "object", + "actor": "server1.conn0.child0/obj21", + "class": "Array", + "ownPropertyLength": 3, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false, + "preview": { + "kind": "ArrayLike", + "length": 2, + "items": [ + 2, + { + "type": "object", + "actor": "server1.conn0.child0/obj22", + "class": "Object", + "ownPropertyLength": 1, + "extensible": true, + "frozen": false, + "sealed": false, + "isError": false + } + ] + } + } + } + }, + "ownSymbols": [], + "safeGetterValues": {}, + "from": "server1.conn0.child0/obj19" +} diff --git a/crates/ff-rdp-cli/tests/live/live_eval_text_values.rs b/crates/ff-rdp-cli/tests/live/live_eval_text_values.rs new file mode 100644 index 00000000..0e438eed --- /dev/null +++ b/crates/ff-rdp-cli/tests/live/live_eval_text_values.rs @@ -0,0 +1,182 @@ +//! Live test: `eval --format text` prints the bare value without changing what +//! runs. A plain Object/Array prints as its JSON value (read through the +//! object actors), every other result prints as in JSON mode, and the script +//! is sent exactly as in JSON mode — so `--no-isolate` scope sharing and +//! statement completion values keep working, and results `JSON.stringify` +//! cannot represent (`document.body`, `10n`, `window`) still print. +//! +//! # Running +//! +//! FF_RDP_LIVE_TESTS=1 cargo test -p ff-rdp-cli \ +//! --test live live_eval_text_values -- --include-ignored + +use std::process::{Command, Output}; + +use crate::common::{LiveFirefox, base_args, ff_rdp_bin, output_note}; + +fn run(port: u16, args: &[&str]) -> Output { + Command::new(ff_rdp_bin()) + .args(base_args(port)) + .args(args) + .output() + .unwrap_or_else(|e| panic!("spawn ff-rdp {args:?}: {e}")) +} + +/// Run `ff-rdp `, assert exit 0 and no `-> ff-rdp` hint line, return stdout. +fn text_ok(port: u16, args: &[&str]) -> String { + let out = run(port, args); + assert!(out.status.success(), "{args:?}: {}", output_note(&out)); + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!( + !stdout.contains("-> ff-rdp"), + "{args:?} must print no hint line; got: {stdout:?}" + ); + stdout +} + +fn json_ok(port: u16, args: &[&str]) -> serde_json::Value { + let out = run(port, args); + assert!(out.status.success(), "{args:?}: {}", output_note(&out)); + let stdout = String::from_utf8_lossy(&out.stdout); + serde_json::from_str(stdout.trim()) + .unwrap_or_else(|e| panic!("{args:?} stdout is not JSON: {e}\n{stdout}")) +} + +#[test] +#[ignore = "requires a live Firefox instance — set FF_RDP_LIVE_TESTS=1"] +fn live_eval_text_values() { + if std::env::var("FF_RDP_LIVE_TESTS").is_err() { + eprintln!("live_eval_text_values: set FF_RDP_LIVE_TESTS=1 to run"); + return; + } + + let ff = LiveFirefox::headless_on_random_port(); + let port = ff.port(); + let nav = run( + port, + &[ + "--allow-unsafe-urls", + "navigate", + "data:text/html,T

x

", + ], + ); + assert!(nav.status.success(), "navigate: {}", output_note(&nav)); + + // A plain object prints as its JSON value, keys in insertion order. + let out = text_ok( + port, + &["eval", "--format", "text", "({z: 1, a: [1, {b: 'x'}]})"], + ); + let value: serde_json::Value = serde_json::from_str(&out) + .unwrap_or_else(|e| panic!("object text output is not JSON: {e}\n{out}")); + assert_eq!( + serde_json::to_string(&value).unwrap(), + r#"{"z":1,"a":[1,{"b":"x"}]}"# + ); + + // Nested non-JSON values print as "[Kind]" placeholders, never as actor + // metadata; arrays pad to `length`. + let out = text_ok( + port, + &[ + "eval", + "--format", + "text", + "({n: 10n, s: Symbol('k'), d: new Date(0), f(){}, h: new Array(2)})", + ], + ); + let value: serde_json::Value = serde_json::from_str(&out) + .unwrap_or_else(|e| panic!("placeholder text output is not JSON: {e}\n{out}")); + assert_eq!( + value, + serde_json::json!({ + "n": "[BigInt 10]", + "s": "[Symbol k]", + "d": "[Date]", + "f": "[Function]", + "h": [null, null] + }) + ); + + // Past the depth cap the value is cut, and stderr says so. + let deep = run( + port, + &[ + "eval", + "--format", + "text", + "({a:{a:{a:{a:{a:{a:{a:1}}}}}}})", + ], + ); + assert!(deep.status.success(), "deep: {}", output_note(&deep)); + let stderr = String::from_utf8_lossy(&deep.stderr); + assert!( + stderr.contains("caps") && stderr.contains("--stringify"), + "a cut value must warn on stderr; got: {}", + output_note(&deep) + ); + assert!(String::from_utf8_lossy(&deep.stdout).contains("\"[Object]\"")); + + assert_eq!(text_ok(port, &["eval", "--format", "text", "1+1"]), "2\n"); + + // Statement completion value: the script is not re-wrapped. + assert_eq!( + text_ok(port, &["eval", "--format", "text", "if (1) { 2 }"]), + "2\n" + ); + + // --no-isolate shares one scope across calls in text mode too. + assert_eq!( + text_ok( + port, + &[ + "eval", + "--no-isolate", + "--format", + "text", + "let k402 = 7; k402" + ] + ), + "7\n" + ); + assert_eq!( + text_ok(port, &["eval", "--no-isolate", "--format", "text", "k402"]), + "7\n" + ); + + // Results JSON.stringify cannot represent keep their grip output. + let body = text_ok(port, &["eval", "--format", "text", "document.body"]); + assert!(body.contains("HTMLBodyElement"), "document.body: {body}"); + let big = text_ok(port, &["eval", "--format", "text", "10n"]); + assert!(big.contains("10"), "10n: {big}"); + let win = text_ok(port, &["eval", "--format", "text", "window"]); + assert!(win.contains("Window"), "window: {win}"); + + // --jq filters the JSON envelope (the grip), as in JSON mode. + let jq = text_ok( + port, + &[ + "eval", + "--format", + "text", + "--jq", + ".results.class", + "({a: 1})", + ], + ); + assert!(jq.contains("Object"), "--format text --jq: {jq}"); + + // JSON mode: a plain object grip names --stringify; --no-hints and a + // DOM node do not. + let grip = json_ok(port, &["eval", "({a: [1, 2]})"]); + assert!( + grip["hint"] + .as_str() + .is_some_and(|h| h.contains("--stringify")), + "object grip hint: {grip}" + ); + let quiet = json_ok(port, &["--no-hints", "eval", "({a: [1, 2]})"]); + assert!(quiet.get("hint").is_none(), "--no-hints: {quiet}"); + let node = json_ok(port, &["eval", "document.body"]); + assert!(node.get("hint").is_none(), "DOM node: {node}"); +} diff --git a/crates/ff-rdp-cli/tests/live/main.rs b/crates/ff-rdp-cli/tests/live/main.rs index de7a1c75..71b4a8c9 100644 --- a/crates/ff-rdp-cli/tests/live/main.rs +++ b/crates/ff-rdp-cli/tests/live/main.rs @@ -119,6 +119,7 @@ mod live_dom_stats_perf_audit_parity; mod live_emulation; mod live_eval_csp; mod live_eval_scope; +mod live_eval_text_values; mod live_navigate_default_fast; mod live_navigate_readiness; mod live_navigate_real_site; diff --git a/crates/ff-rdp-core/src/actors/object.rs b/crates/ff-rdp-core/src/actors/object.rs index 7c88988d..8f0825df 100644 --- a/crates/ff-rdp-core/src/actors/object.rs +++ b/crates/ff-rdp-core/src/actors/object.rs @@ -1,5 +1,3 @@ -use std::collections::BTreeMap; - use serde_json::{Value, json}; use crate::actor::actor_request; @@ -65,7 +63,9 @@ pub enum PropertyDescriptor { #[derive(Debug)] pub struct PrototypeAndProperties { pub prototype: Grip, - pub own_properties: BTreeMap, + /// Own properties in the order Firefox sent them (integer keys ascending, + /// then insertion order) — the order `JSON.stringify` uses. + pub own_properties: Vec<(String, PropertyDescriptor)>, } /// Operations on a Firefox object grip actor. @@ -450,8 +450,21 @@ mod tests { }; assert_eq!(class, "Object"); assert_eq!(pap.own_properties.len(), 2); - assert!(pap.own_properties.contains_key("a")); - assert!(pap.own_properties.contains_key("b")); + let keys: Vec<&str> = pap.own_properties.iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!(keys, ["a", "b"]); + } + + #[test] + fn parse_prototype_and_properties_keeps_firefox_order() { + let data = |v: i64| json!({"value": v, "writable": true, "enumerable": true, "configurable": true}); + let response = json!({ + "from": "server1.conn0.child2/obj1", + "prototype": {"type": "null"}, + "ownProperties": {"zeta": data(1), "alpha": data(2), "mid": data(3)} + }); + let pap = parse_prototype_and_properties(&response); + let keys: Vec<&str> = pap.own_properties.iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!(keys, ["zeta", "alpha", "mid"]); } #[test] diff --git a/crates/ff-rdp-core/tests/live_record_fixtures.rs b/crates/ff-rdp-core/tests/live_record_fixtures.rs index f3f0f12a..d2d2aa68 100644 --- a/crates/ff-rdp-core/tests/live_record_fixtures.rs +++ b/crates/ff-rdp-core/tests/live_record_fixtures.rs @@ -700,6 +700,81 @@ fn live_eval_object() { ); } +/// `eval --format text` reads a plain Object/Array grip through its actors: +/// record the eval result plus the `prototypeAndProperties` replies for the +/// object, its nested array and the object inside that, in the order the CLI +/// requests them. +#[test] +#[ignore = "requires a live Firefox instance — set FF_RDP_LIVE_TESTS=1"] +fn live_eval_object_nested_properties() { + fn props(transport: &mut RdpTransport, actor: &str, fixture: &str) -> Value { + transport + .send(&json!({"to": actor, "type": "prototypeAndProperties"})) + .expect("send prototypeAndProperties"); + let reply = recv_from_actor(transport, actor); + if should_record() { + save_cli_fixture(fixture, &reply); + } + reply + } + + if !should_run_live() { + return; + } + let mut conn = connect(); + let transport = conn.transport_mut(); + navigate_to_example_com(transport); + let console = get_console_actor(transport); + + let (_imm, result) = record_eval( + transport, + &console, + "({z: 1, a: [2, {b: 'x'}]})", + Some("eval_immediate_object_nested.json"), + Some("eval_result_object_nested.json"), + ); + let root = result["result"]["actor"] + .as_str() + .expect("object result has an actor") + .to_owned(); + + let root_reply = props( + transport, + &root, + "prototype_and_properties_object_nested.json", + ); + let keys: Vec<&str> = root_reply["ownProperties"] + .as_object() + .expect("ownProperties") + .keys() + .map(String::as_str) + .collect(); + assert_eq!( + keys, + ["z", "a"], + "Firefox sends own properties in insertion order" + ); + + let array = root_reply["ownProperties"]["a"]["value"]["actor"] + .as_str() + .expect("nested array actor") + .to_owned(); + let array_reply = props( + transport, + &array, + "prototype_and_properties_array_nested.json", + ); + let inner = array_reply["ownProperties"]["1"]["value"]["actor"] + .as_str() + .expect("nested object actor") + .to_owned(); + props( + transport, + &inner, + "prototype_and_properties_inner_nested.json", + ); +} + #[test] #[ignore = "requires a live Firefox instance — set FF_RDP_LIVE_TESTS=1"] fn live_eval_exception() { diff --git a/kb/backlog.md b/kb/backlog.md index 56d58397..dc122996 100644 --- a/kb/backlog.md +++ b/kb/backlog.md @@ -193,8 +193,8 @@ Reporter: an agent driving ff-rdp 0.4.3 (aarch64 musl) against Firefox ESR in a - [ ] **gap** `eval` gives no hint which document it ran in: on an error page or the JSON viewer (`document.contentType` = `application/json`, DOM is the viewer's), `document.title` returns `""` and selectors return `null`, exit 0. Add a stderr warning plus a `meta` field when the location is an `about:` error page or the content type is not HTML. The reporter's "no document at all" on ESR was not reproduced (the 158 JSON viewer supplies one) (sandbox feedback 2026-11-14) - [ ] **gap** `cookies` is read-only: add `cookies set NAME=VALUE --domain … [--path --secure --http-only --same-site --expires]` and `cookies delete`, usable before the origin was ever visited (StorageActor `addItem`/`editItem`/`removeItem`, or `Services.cookies.add` from the chrome console). Today's workaround is `document.cookie` from a blank page served on another localhost port — cost the reporter ~30 min (sandbox feedback 2026-11-14) - [ ] **polish** `console` is flooded by `level:"timeStamp"` entries (React dev builds call `console.timeStamp` for each render): a page that makes 30 `timeStamp` calls and 1 `console.error` gives 30 of 32 results as `timeStamp`. Hide `timeStamp` by default, keep it counted in `summary.by_level`, and show it with `--level timeStamp` (sandbox feedback 2026-11-14) -- [ ] **polish** `eval` output for scalars: by default `1+1` prints a 4-line pretty envelope; `--format text` prints a bare `2` but adds the generic `-> ff-rdp console --level error` hint, and for an object it prints the raw grip (actor id, preview, propertyNames) instead of the value. Drop the hint from eval text output, print text-mode objects as plain JSON like `--stringify` does, and mention `--format text` in `eval --help` (sandbox feedback 2026-11-14) — 2026-11-26 agent feedback: the default JSON object result is the same grip (nested arrays show only `length`), and `--stringify` is first mentioned at line 108 of `eval --help`, so agents wrap `JSON.stringify` themselves and get a JSON string inside JSON; also add a `hint` naming `--stringify` when the result is an object grip -- [ ] **wrong** `console --pattern X` envelope: top-level `total` is the matched count while `summary.total` is every message (`--pattern nomatch` → `total: 0`, `summary.total: 3`), but `console --help` documents both as `N`; and with 0 matches of 3 the `hint` says "No console messages captured". Fix the help shape, and give the zero-match case its own hint (verified on 0.5.1, agent feedback 2026-11-26) +- [x] **polish** `eval` output for scalars: by default `1+1` prints a 4-line pretty envelope; `--format text` prints a bare `2` but adds the generic `-> ff-rdp console --level error` hint, and for an object it prints the raw grip (actor id, preview, propertyNames) instead of the value. Drop the hint from eval text output, print text-mode objects as plain JSON like `--stringify` does, and mention `--format text` in `eval --help` (sandbox feedback 2026-11-14) — 2026-11-26 agent feedback: the default JSON object result is the same grip (nested arrays show only `length`), and `--stringify` is first mentioned at line 108 of `eval --help`, so agents wrap `JSON.stringify` themselves and get a JSON string inside JSON; also add a `hint` naming `--stringify` when the result is an object grip — fix/console-totals-eval-grip ([#402](https://github.com/ractive/ff-rdp/pull/402)): `--format text` (no `--jq`) prints a plain Object/Array as its JSON value, read through the object actors (script unchanged, depth 6), other results as before, and no hint line; a JSON Object/Array grip result carries a `hint` naming `--stringify` (off with `--no-hints`); one help sentence after `Output:` +- [x] **wrong** `console --pattern X` envelope: top-level `total` is the matched count while `summary.total` is every message (`--pattern nomatch` → `total: 0`, `summary.total: 3`), but `console --help` documents both as `N`; and with 0 matches of 3 the `hint` says "No console messages captured". Fix the help shape, and give the zero-match case its own hint (verified on 0.5.1, agent feedback 2026-11-26) — fix/console-totals-eval-grip ([#402](https://github.com/ractive/ff-rdp/pull/402)): help `Output:` names `summary.total` (all captured) vs top-level `total` (matched); 0-of-N matched gets "N console messages captured, none matched --pattern …" - [ ] **polish** long `--help` buries the option list under prose: `launch --help` has ~45 lines (URL handling, window size, launch timeout) before `Options:`, `eval --help` ~110; the prose carries internal history (110 `iter-NNN` mentions in `cli/args.rs`, `eval`'s "from iter-93 to iter-164 … even though this help claimed otherwise"). Cut `long_about` to usage and contract, drop iteration numbers and fixed-bug history (agent feedback 2026-11-26) ## Done