1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use ff_rdp_core::{
ConsoleResource, ProtocolError, RdpTransport, TabActor, WatcherActor, WebConsoleActor,
parse_console_notification, parse_console_resources,
};
use serde_json::{Value, json};
use crate::cli::args::Cli;
use crate::error::AppError;
use crate::hints::{HintContext, HintSource};
use crate::output;
use crate::output_controls::{OutputControls, SortDir};
use crate::output_pipeline::OutputPipeline;
use super::connect_tab::{ConnectedTab, connect_and_get_target};
pub fn run(cli: &Cli, level: Option<&str>, pattern: Option<&str>) -> Result<(), AppError> {
let mut ctx = connect_and_get_target(cli)?;
let console_actor = ctx.target.console_actor.clone();
// Start listeners — best-effort; some Firefox builds reject certain listener types.
if let Err(e) = WebConsoleActor::start_listeners(
ctx.transport_mut(),
&console_actor,
&["PageError", "ConsoleAPI"],
) {
eprintln!("warning: startListeners failed: {e}");
}
// Retrieve all cached console messages.
// If the combined request fails (Firefox may reject PageError serialization),
// fall back to ConsoleAPI-only to recover partial results.
let messages = match WebConsoleActor::get_cached_messages(
ctx.transport_mut(),
&console_actor,
&["PageError", "ConsoleAPI"],
) {
Ok(msgs) => msgs,
Err(e) => {
eprintln!(
"debug: getCachedMessages(PageError+ConsoleAPI) failed ({e}), retrying with ConsoleAPI only"
);
WebConsoleActor::get_cached_messages(
ctx.transport_mut(),
&console_actor,
&["ConsoleAPI"],
)
.map_err(AppError::from)?
}
};
// Track pre-filter count for summary.
let raw_total = messages.len();
// Apply filters.
let regex = pattern
.map(|p| {
regex::RegexBuilder::new(p)
.size_limit(1_000_000)
.build()
.map_err(|e| AppError::User(format!("invalid --pattern regex: {e}")))
})
.transpose()?;
let filtered: Vec<_> = messages
.into_iter()
.filter(|msg| {
if let Some(l) = level
&& !msg.level.eq_ignore_ascii_case(l)
{
return false;
}
if let Some(ref re) = regex
&& !re.is_match(&msg.message)
{
return false;
}
true
})
.collect();
// Compute per-level counts over the filtered set (before --limit truncation).
let mut by_level: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
for msg in &filtered {
*by_level.entry(msg.level.clone()).or_insert(0) += 1;
}
let matched = filtered.len();
// Convert to JSON output.
let mut results: Vec<serde_json::Value> = filtered
.iter()
.map(|msg| {
json!({
"level": msg.level,
"message": msg.message,
"source": msg.source,
"line": msg.line,
"timestamp": msg.timestamp,
})
})
.collect();
// Apply output controls: default sort timestamp desc, default limit 50.
let controls = OutputControls::from_cli(cli, SortDir::Desc);
if cli.sort.is_none() {
let dir = controls.sort_dir;
results.sort_by(|a, b| {
let ta = a["timestamp"].as_f64().unwrap_or(0.0);
let tb = b["timestamp"].as_f64().unwrap_or(0.0);
let cmp = ta.partial_cmp(&tb).unwrap_or(std::cmp::Ordering::Equal);
match dir {
SortDir::Asc => cmp,
SortDir::Desc => cmp.reverse(),
}
});
} else {
controls.apply_sort(&mut results);
}
let (limited, total, truncated) = controls.apply_limit(results, Some(50));
let shown = limited.len();
let limited = controls.apply_fields(limited);
let mut meta = json!({"host": cli.host, "port": cli.port});
crate::connection_meta::merge_into(&mut meta, &cli.host, cli.port, None);
let mut envelope =
output::envelope_with_truncation(&json!(limited), shown, total, truncated, &meta);
// Capture error count before consuming by_level.
let error_count = by_level.get("error").copied().unwrap_or(0);
// Insert summary: pre-filter total, post-filter matched, shown after --limit,
// and per-level counts over the filtered (but not truncated) set.
if let Some(obj) = envelope.as_object_mut() {
let by_level_json: serde_json::Map<String, serde_json::Value> =
by_level.into_iter().map(|(k, v)| (k, json!(v))).collect();
obj.insert(
"summary".to_string(),
json!({
"total": raw_total,
"matched": matched,
"shown": shown,
"by_level": by_level_json,
}),
);
}
if total == 0
&& let Some(obj) = envelope.as_object_mut()
{
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\")'"
),
);
}
let hint_ctx = HintContext::new(HintSource::Console).with_has_errors(error_count > 0);
OutputPipeline::from_cli(cli)?
.finalize_with_hints(&envelope, Some(&hint_ctx))
.map_err(AppError::from)
}
/// Stream console messages in real time until the connection is closed.
///
/// Subscribes to `console-message` and `error-message` resource types via the
/// WatcherActor (direct mode) or daemon stream protocol (daemon mode), then
/// loops reading events and printing each matching message as a compact JSON
/// line (NDJSON format) to stdout.
///
/// Exits cleanly when the connection is closed (e.g. Firefox exits or the
/// daemon is killed). Ctrl-C terminates the process, which is acceptable.
pub fn run_follow(cli: &Cli, level: Option<&str>, pattern: Option<&str>) -> Result<(), AppError> {
let mut ctx = connect_and_get_target(cli)?;
let regex = pattern
.map(|p| {
regex::RegexBuilder::new(p)
.size_limit(1_000_000)
.build()
.map_err(|e| AppError::User(format!("invalid --pattern regex: {e}")))
})
.transpose()?;
if ctx.via_daemon {
run_follow_daemon(&mut ctx, level, regex.as_ref(), cli.jq.as_deref())
} else {
run_follow_direct(&mut ctx, level, regex.as_ref(), cli.jq.as_deref())
}
}
fn run_follow_direct(
ctx: &mut ConnectedTab,
level: Option<&str>,
regex: Option<®ex::Regex>,
jq_filter: Option<&str>,
) -> Result<(), AppError> {
// Activate the console actor's internal listeners before subscribing via
// the Watcher. Firefox requires the console actor to be "listening" for
// the watcher's console-message subscription to deliver events; without
// this call, console.log() calls made via eval produce no events.
// Best-effort: some Firefox builds reject certain listener types.
let console_actor = ctx.target.console_actor.clone();
if let Err(e) = WebConsoleActor::start_listeners(
ctx.transport_mut(),
&console_actor,
&["PageError", "ConsoleAPI"],
) {
eprintln!("warning: startListeners failed: {e}");
}
let tab_actor = ctx.target_tab_actor().clone();
let watcher_actor =
TabActor::get_watcher(ctx.transport_mut(), &tab_actor).map_err(AppError::from)?;
WatcherActor::watch_resources(
ctx.transport_mut(),
&watcher_actor,
&["console-message", "error-message"],
)
.map_err(AppError::from)?;
let result = follow_loop(ctx.transport_mut(), level, regex, jq_filter);
// Best-effort cleanup — ignore errors since we may be exiting anyway.
let _ = WatcherActor::unwatch_resources(
ctx.transport_mut(),
&watcher_actor,
&["console-message", "error-message"],
);
result
}
fn run_follow_daemon(
ctx: &mut ConnectedTab,
level: Option<&str>,
regex: Option<®ex::Regex>,
jq_filter: Option<&str>,
) -> Result<(), AppError> {
use crate::daemon::client::{start_daemon_stream, stop_daemon_stream};
start_daemon_stream(ctx.transport_mut(), "console-message").map_err(AppError::from)?;
start_daemon_stream(ctx.transport_mut(), "error-message").map_err(AppError::from)?;
let result = follow_loop(ctx.transport_mut(), level, regex, jq_filter);
// Best-effort cleanup — ignore errors since we may be exiting anyway.
let _ = stop_daemon_stream(ctx.transport_mut(), "console-message");
let _ = stop_daemon_stream(ctx.transport_mut(), "error-message");
result
}
/// Inner loop: read events from the transport and emit matching console
/// messages as compact JSON lines (NDJSON).
///
/// Each message is a single compact JSON object on its own line so that
/// consumers can process the stream with tools like `jq` or `jq -c`.
/// If `jq_filter` is set, it is applied to each message before printing.
///
/// Firefox delivers console messages via two channels:
///
/// 1. **Watcher stream** (`resources-available-array`): new console messages
/// generated by page scripts that the Watcher actor observes.
///
/// 2. **Direct console actor push** (`consoleAPICall` / `pageError`): Firefox
/// 149+ pushes these directly to the console actor when `startListeners` is
/// active. This path fires when `console.log()` is called via
/// `evaluateJSAsync`, so without handling it the follow mode silently drops
/// all eval-triggered log output.
///
/// Both channels must be handled to ensure complete coverage.
fn follow_loop(
transport: &mut RdpTransport,
level: Option<&str>,
regex: Option<®ex::Regex>,
jq_filter: Option<&str>,
) -> Result<(), AppError> {
use std::io::Write;
loop {
match transport.recv() {
Ok(msg) => {
let msg_type = msg.get("type").and_then(Value::as_str).unwrap_or_default();
// Collect resources from whichever channel delivered this message.
let resources: Vec<ConsoleResource> = if msg_type == "resources-available-array" {
// Watcher stream: batch of console/error-message resources.
parse_console_resources(&msg)
} else if let Some(notification) = parse_console_notification(&msg) {
// Direct push from the console actor (consoleAPICall / pageError).
// Convert ConsoleMessage → ConsoleResource so both paths share
// the same filtering and emission logic below.
vec![ConsoleResource {
level: notification.level,
message: notification.message,
source: notification.source,
line: notification.line,
column: notification.column,
timestamp: notification.timestamp,
resource_id: None,
}]
} else {
// Unrecognised message type — skip silently.
continue;
};
for res in resources {
if let Some(l) = level
&& !res.level.eq_ignore_ascii_case(l)
{
continue;
}
if let Some(re) = regex
&& !re.is_match(&res.message)
{
continue;
}
let entry = json!({
"level": res.level,
"message": res.message,
"source": res.source,
"line": res.line,
"timestamp": res.timestamp,
});
if let Some(filter) = jq_filter {
let values =
output::apply_jq_filter(&entry, filter).map_err(AppError::from)?;
for v in values {
println!(
"{}",
serde_json::to_string(&v)
.map_err(|e| AppError::Internal(e.into()))?
);
}
} else {
println!(
"{}",
serde_json::to_string(&entry)
.map_err(|e| AppError::Internal(e.into()))?
);
}
// Flush stdout so each message appears immediately in tail-like usage.
let _ = std::io::stdout().flush();
}
}
Err(ProtocolError::Timeout) => {
// Normal poll timeout — keep waiting for more events.
}
Err(ProtocolError::RecvFailed(ref e))
if e.kind() == std::io::ErrorKind::UnexpectedEof
|| e.kind() == std::io::ErrorKind::ConnectionReset
|| e.kind() == std::io::ErrorKind::BrokenPipe =>
{
// Connection closed cleanly (Firefox exited, daemon stopped, etc.).
return Ok(());
}
Err(e) => return Err(AppError::from(e)),
}
}
}
#[cfg(test)]
mod tests {
/// Verify that a normal pattern compiles successfully under the size limit.
#[test]
fn accepts_reasonable_regex() {
let result = regex::RegexBuilder::new(r"(?i)error|warn")
.size_limit(1_000_000)
.build();
assert!(result.is_ok());
}
/// Verify that a pattern exceeding a small compiled-regex size limit is rejected.
#[test]
fn rejects_oversized_regex() {
let oversized = (0..100)
.map(|i| format!("literal_{i}"))
.collect::<Vec<_>>()
.join("|");
let result = regex::RegexBuilder::new(&oversized).size_limit(64).build();
assert!(result.is_err(), "expected oversized pattern to be rejected");
}
}