mirror of
https://github.com/Tencent/BrowserSkill.git
synced 2026-09-10 13:01:23 +08:00
feat: add bsk network read-only command
Add `bsk network` as a sibling of the `console` command from #7, reading the buffered network responses / failures for a tab. Fills the remaining half of the request in #2 (console landed in #7; network did not). Mirrors the console command's conventions exactly: bsk network --session <id> [--tab-id N] [--since C] [--limit N] [--max-text-chars N] The extension enables `Network` on attach (best-effort) and buffers `responseReceived` / `loadingFailed` events per tab with a monotonic sequence, correlating them to `requestWillBeSent` for method/URL. Reads are cursor-paginated (`since` -> `next_since`) and bounded (`limit`, `max_text_chars`) for agent-context safety, same as console. Entries carry the real HTTP status code (response) or the CDP failure reason (failure) — things `performance.getEntriesByType('resource')` can't give. Classified read-only (pass-through under the pending-interrupt gate); defaults to the Agent Window's active tab. Wires bsk-protocol (Method + params/result/entry structs + schema), bsk-cli (network subcommand + daemon dispatch allow-list) and the extension (handler + dispatcher route), with unit / parse / IPC tests paralleling the console command. Refs #2.
This commit is contained in:
1 parent
3d6c95c22a
commit
259b4826b7
19 files changed
+1156
-3
No files matched your search
@@ -18,6 +18,7 @@ pub mod install_skill;
|
||||
pub mod interaction;
|
||||
pub mod logs;
|
||||
pub mod navigate;
|
||||
pub mod network;
|
||||
pub mod render_error;
|
||||
pub mod screenshot;
|
||||
pub mod session;
|
||||
@@ -37,6 +38,7 @@ use crate::cli::human_loop::RequestHelpArgs;
|
||||
use crate::cli::install_skill::InstallSkillArgs;
|
||||
use crate::cli::interaction::{ClickArgs, FillArgs, PressArgs, SelectArgs};
|
||||
use crate::cli::navigate::{NavigateCommand, NavigateHistoryArgs, ReloadArgs};
|
||||
use crate::cli::network::NetworkArgs;
|
||||
use crate::cli::screenshot::ScreenshotArgs;
|
||||
use crate::cli::session::SessionCmd;
|
||||
use crate::cli::snapshot::SnapshotArgs;
|
||||
@@ -120,6 +122,9 @@ pub enum Command {
|
||||
/// Read buffered console/log/exception messages.
|
||||
Console(ConsoleArgs),
|
||||
|
||||
/// Read buffered network responses / failures.
|
||||
Network(NetworkArgs),
|
||||
|
||||
/// Dump raw HTML for a tab or a snapshot ref.
|
||||
#[command(name = "get-html")]
|
||||
GetHtml(GetHtmlArgs),
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! `bsk network` — read buffered page network responses / failures.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use bsk_protocol::Method;
|
||||
use bsk_protocol::tools::{NetworkEntry, NetworkParams, NetworkResult};
|
||||
use clap::Args;
|
||||
|
||||
use crate::cli::TOOL_IPC_TIMEOUT;
|
||||
use crate::cli::ensure_daemon::ensure_daemon;
|
||||
use crate::cli::error::{CliError, Format};
|
||||
|
||||
#[derive(Debug, Clone, Args)]
|
||||
pub struct NetworkArgs {
|
||||
/// Session id (must be active).
|
||||
#[arg(long)]
|
||||
pub session: String,
|
||||
|
||||
/// Target tab. Defaults to the Agent Window's active tab.
|
||||
#[arg(long = "tab-id")]
|
||||
pub tab_id: Option<i64>,
|
||||
|
||||
/// Return entries with sequence greater than this cursor.
|
||||
#[arg(long)]
|
||||
pub since: Option<u64>,
|
||||
|
||||
/// Maximum number of entries to return. Defaults to 50; extension caps at 200.
|
||||
#[arg(long, value_parser = clap::value_parser!(u32).range(1..))]
|
||||
pub limit: Option<u32>,
|
||||
|
||||
/// Maximum characters per URL / error text. Defaults to 1000; extension caps at 4096.
|
||||
#[arg(long = "max-text-chars", value_parser = clap::value_parser!(u32).range(1..))]
|
||||
pub max_text_chars: Option<u32>,
|
||||
}
|
||||
|
||||
pub fn dispatch(args: NetworkArgs, format: Format) -> Result<(), CliError> {
|
||||
let info = ensure_daemon().context("ensure daemon is running")?;
|
||||
run(info.sock_path, args, format)
|
||||
}
|
||||
|
||||
fn run(sock: PathBuf, args: NetworkArgs, format: Format) -> Result<(), CliError> {
|
||||
let params = NetworkParams {
|
||||
session_id: args.session,
|
||||
tab_id: args.tab_id,
|
||||
since: args.since,
|
||||
limit: args.limit,
|
||||
max_text_chars: args.max_text_chars,
|
||||
};
|
||||
let reply: NetworkResult = call(sock, params)?;
|
||||
render(&reply, format)
|
||||
}
|
||||
|
||||
fn call(sock: PathBuf, params: NetworkParams) -> Result<NetworkResult, CliError> {
|
||||
crate::cli::business_rpc::call::<NetworkParams, NetworkResult>(
|
||||
sock,
|
||||
"network",
|
||||
Method::ToolNetwork,
|
||||
Some(params),
|
||||
TOOL_IPC_TIMEOUT,
|
||||
)
|
||||
}
|
||||
|
||||
fn render(reply: &NetworkResult, format: Format) -> Result<(), CliError> {
|
||||
match format {
|
||||
Format::Json => {
|
||||
let json = serde_json::to_string_pretty(reply)
|
||||
.map_err(|e| CliError::Local(anyhow::anyhow!(e)))?;
|
||||
println!("{json}");
|
||||
}
|
||||
Format::Human => {
|
||||
if reply.entries.is_empty() {
|
||||
println!("(no network activity captured)");
|
||||
} else {
|
||||
for entry in &reply.entries {
|
||||
println!("{}", render_entry(entry));
|
||||
}
|
||||
}
|
||||
if reply.truncated {
|
||||
eprintln!(
|
||||
"warning: network output truncated (next_since={}). Use --since / --limit / --max-text-chars to request a different slice.",
|
||||
reply.next_since
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render_entry(entry: &NetworkEntry) -> String {
|
||||
let method = entry.method.as_deref().unwrap_or("?");
|
||||
match entry.kind {
|
||||
bsk_protocol::tools::NetworkEntryKind::Failure => {
|
||||
let err = entry.error_text.as_deref().unwrap_or("failed");
|
||||
format!("#{} FAILED {method} {} — {err}", entry.sequence, entry.url)
|
||||
}
|
||||
bsk_protocol::tools::NetworkEntryKind::Response => {
|
||||
let status = entry
|
||||
.status
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| "?".to_string());
|
||||
format!("#{} {status} {method} {}", entry.sequence, entry.url)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,7 @@ pub fn full_handler(status: DaemonStatus, state: Arc<DaemonState>) -> RpcHandler
|
||||
| Method::ToolTabReturn
|
||||
| Method::ToolScreenshot
|
||||
| Method::ToolConsole
|
||||
| Method::ToolNetwork
|
||||
| Method::ToolSnapshot
|
||||
| Method::ToolGetHtml
|
||||
| Method::ToolNavigate
|
||||
|
||||
@@ -83,6 +83,7 @@ fn dispatch(cli: Cli, format: Format) -> Result<(), CliError> {
|
||||
Command::Screenshot(args) => cli::screenshot::dispatch(args, format),
|
||||
Command::Snapshot(args) => cli::snapshot::dispatch(args, format),
|
||||
Command::Console(args) => cli::console::dispatch(args, format),
|
||||
Command::Network(args) => cli::network::dispatch(args, format),
|
||||
Command::GetHtml(args) => cli::get_html::dispatch(args, format),
|
||||
Command::Navigate(args) => cli::navigate::dispatch_navigate_command(args, format),
|
||||
Command::NavigateBack(args) => cli::navigate::dispatch_navigate_back(args, format),
|
||||
|
||||
@@ -104,6 +104,41 @@ fn rejects_zero_console_bounds() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_network_command_with_context_safety_flags() {
|
||||
let cli = parse(&[
|
||||
"bsk",
|
||||
"network",
|
||||
"--session",
|
||||
"s1",
|
||||
"--tab-id",
|
||||
"9",
|
||||
"--since",
|
||||
"12",
|
||||
"--limit",
|
||||
"75",
|
||||
"--max-text-chars",
|
||||
"2048",
|
||||
]);
|
||||
let Command::Network(args) = cli.command else {
|
||||
panic!("expected network command");
|
||||
};
|
||||
assert_eq!(args.session, "s1");
|
||||
assert_eq!(args.tab_id, Some(9));
|
||||
assert_eq!(args.since, Some(12));
|
||||
assert_eq!(args.limit, Some(75));
|
||||
assert_eq!(args.max_text_chars, Some(2048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_network_bounds() {
|
||||
assert!(Cli::try_parse_from(["bsk", "network", "--session", "s1", "--limit", "0"]).is_err());
|
||||
assert!(
|
||||
Cli::try_parse_from(["bsk", "network", "--session", "s1", "--max-text-chars", "0"])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_install_skill_subcommand() {
|
||||
let cli = parse(&["bsk", "install-skill", "--list"]);
|
||||
|
||||
@@ -11,8 +11,9 @@ use bsk::ipc_client::IpcClient;
|
||||
use bsk_protocol::system::{HandshakeParams, HandshakeResult};
|
||||
use bsk_protocol::tools::{
|
||||
ConsoleEntry, ConsoleEntryKind, ConsoleParams, ConsoleResult, GetHtmlParams, GetHtmlResult,
|
||||
ScreenshotParams, ScreenshotResult, SessionStartParams, SessionStartResult, SnapshotParams,
|
||||
SnapshotResult, TabInfo, TabListParams, TabListResult, TabScope,
|
||||
NetworkEntry, NetworkEntryKind, NetworkParams, NetworkResult, ScreenshotParams,
|
||||
ScreenshotResult, SessionStartParams, SessionStartResult, SnapshotParams, SnapshotResult,
|
||||
TabInfo, TabListParams, TabListResult, TabScope,
|
||||
};
|
||||
use bsk_protocol::{
|
||||
BrowserPeerInfo, ErrorCode, Frame, Method, RequestFrame, ResponseBody, ResponseFrame, RpcError,
|
||||
@@ -365,6 +366,62 @@ async fn console_returns_buffered_entries() {
|
||||
handle.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn network_returns_buffered_entries() {
|
||||
let (handle, sock) = spawn_daemon().await;
|
||||
let mut ws = connect_ext(handle.ws_addr()).await;
|
||||
let _ = do_handshake(&mut ws).await;
|
||||
|
||||
run_extension(ws, |req| {
|
||||
assert_eq!(req.method, Method::ToolNetwork);
|
||||
let params: NetworkParams = serde_json::from_value(req.params.clone().unwrap()).unwrap();
|
||||
assert_eq!(params.tab_id, Some(7));
|
||||
assert_eq!(params.since, Some(3));
|
||||
assert_eq!(params.limit, Some(50));
|
||||
assert_eq!(params.max_text_chars, Some(1000));
|
||||
ResponseBody::Ok(
|
||||
serde_json::to_value(NetworkResult {
|
||||
tab_id: 7,
|
||||
entries: vec![NetworkEntry {
|
||||
sequence: 4,
|
||||
kind: NetworkEntryKind::Response,
|
||||
method: Some("GET".into()),
|
||||
url: "https://example.test/api".into(),
|
||||
status: Some(404),
|
||||
status_text: Some("Not Found".into()),
|
||||
mime_type: Some("application/json".into()),
|
||||
resource_type: Some("Fetch".into()),
|
||||
error_text: None,
|
||||
timestamp: None,
|
||||
truncated: false,
|
||||
}],
|
||||
next_since: 4,
|
||||
truncated: false,
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
});
|
||||
|
||||
let session_id = ipc_session_start(&sock).await;
|
||||
let result: NetworkResult = ipc_tool_call(
|
||||
&sock,
|
||||
Method::ToolNetwork,
|
||||
NetworkParams {
|
||||
session_id,
|
||||
tab_id: Some(7),
|
||||
since: Some(3),
|
||||
limit: Some(50),
|
||||
max_text_chars: Some(1000),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("network ok");
|
||||
assert_eq!(result.tab_id, 7);
|
||||
assert_eq!(result.next_since, 4);
|
||||
assert_eq!(result.entries[0].status, Some(404));
|
||||
handle.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn snapshot_returns_text_and_ref_count() {
|
||||
let (handle, sock) = spawn_daemon().await;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NetworkEntry",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"sequence",
|
||||
"url"
|
||||
],
|
||||
"properties": {
|
||||
"error_text": {
|
||||
"description": "CDP failure reason (`failure` entries only).",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"kind": {
|
||||
"$ref": "#/definitions/NetworkEntryKind"
|
||||
},
|
||||
"method": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"mime_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"resource_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sequence": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"status": {
|
||||
"description": "HTTP status code (`response` entries only).",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"status_text": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"timestamp": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
],
|
||||
"format": "double"
|
||||
},
|
||||
"truncated": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"NetworkEntryKind": {
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "A response was received (`Network.responseReceived`).",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"response"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "The request failed before completing (`Network.loadingFailed`).",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"failure"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NetworkParams",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"session_id"
|
||||
],
|
||||
"properties": {
|
||||
"limit": {
|
||||
"description": "Maximum number of entries to return. Extension applies safe defaults and caps.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"max_text_chars": {
|
||||
"description": "Maximum characters returned per URL / error text. Extension applies safe defaults and caps.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"session_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"since": {
|
||||
"description": "Return entries with sequence strictly greater than this cursor.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"tab_id": {
|
||||
"description": "Optional target tab. Defaults to the Agent Window's currently active tab.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "int64"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "NetworkResult",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"next_since",
|
||||
"tab_id"
|
||||
],
|
||||
"properties": {
|
||||
"entries": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/NetworkEntry"
|
||||
}
|
||||
},
|
||||
"next_since": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"tab_id": {
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
"truncated": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"NetworkEntry": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"sequence",
|
||||
"url"
|
||||
],
|
||||
"properties": {
|
||||
"error_text": {
|
||||
"description": "CDP failure reason (`failure` entries only).",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"kind": {
|
||||
"$ref": "#/definitions/NetworkEntryKind"
|
||||
},
|
||||
"method": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"mime_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"resource_type": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sequence": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"status": {
|
||||
"description": "HTTP status code (`response` entries only).",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0.0
|
||||
},
|
||||
"status_text": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"timestamp": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
],
|
||||
"format": "double"
|
||||
},
|
||||
"truncated": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"NetworkEntryKind": {
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "A response was received (`Network.responseReceived`).",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"response"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "The request failed before completing (`Network.loadingFailed`).",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"failure"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,9 @@ fn main() {
|
||||
dump!(ConsoleResult, "tool_console_result");
|
||||
dump!(ConsoleEntry, "tool_console_entry");
|
||||
dump!(ConsoleStackFrame, "tool_console_stack_frame");
|
||||
dump!(NetworkParams, "tool_network_params");
|
||||
dump!(NetworkResult, "tool_network_result");
|
||||
dump!(NetworkEntry, "tool_network_entry");
|
||||
|
||||
dump!(EvaluateParams, "tool_evaluate_params");
|
||||
dump!(EvaluateResult, "tool_evaluate_result");
|
||||
|
||||
@@ -64,6 +64,8 @@ pub enum Method {
|
||||
ToolScreenshot,
|
||||
#[serde(rename = "tool.console")]
|
||||
ToolConsole,
|
||||
#[serde(rename = "tool.network")]
|
||||
ToolNetwork,
|
||||
#[serde(rename = "tool.evaluate")]
|
||||
ToolEvaluate,
|
||||
#[serde(rename = "tool.wait_for_navigation")]
|
||||
@@ -127,6 +129,7 @@ impl Method {
|
||||
| Method::ToolGetHtml
|
||||
| Method::ToolScreenshot
|
||||
| Method::ToolConsole
|
||||
| Method::ToolNetwork
|
||||
| Method::ToolWaitForNavigation
|
||||
| Method::ToolWaitMs
|
||||
| Method::ToolRequestHelp => false,
|
||||
@@ -169,6 +172,13 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(method).unwrap(), json!("tool.console"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_method_round_trips() {
|
||||
let method: Method = serde_json::from_value(json!("tool.network")).unwrap();
|
||||
assert_eq!(method, Method::ToolNetwork);
|
||||
assert_eq!(serde_json::to_value(method).unwrap(), json!("tool.network"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_params_and_result_round_trip() {
|
||||
let params: CancelParams = serde_json::from_value(json!({ "rpc_id": "wait-1" })).unwrap();
|
||||
@@ -187,6 +197,7 @@ mod tests {
|
||||
assert!(!Method::ToolGetHtml.is_mutating());
|
||||
assert!(!Method::ToolScreenshot.is_mutating());
|
||||
assert!(!Method::ToolConsole.is_mutating());
|
||||
assert!(!Method::ToolNetwork.is_mutating());
|
||||
assert!(!Method::ToolWaitForNavigation.is_mutating());
|
||||
assert!(!Method::ToolWaitMs.is_mutating());
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod dialog;
|
||||
pub mod human_loop;
|
||||
pub mod interaction;
|
||||
pub mod navigation;
|
||||
pub mod network;
|
||||
pub mod observation;
|
||||
pub mod script;
|
||||
pub mod session;
|
||||
@@ -16,6 +17,7 @@ pub use dialog::*;
|
||||
pub use human_loop::*;
|
||||
pub use interaction::*;
|
||||
pub use navigation::*;
|
||||
pub use network::*;
|
||||
pub use observation::*;
|
||||
pub use script::*;
|
||||
pub use session::*;
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! `tool.network` — read buffered network responses / failures.
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct NetworkParams {
|
||||
pub session_id: String,
|
||||
/// Optional target tab. Defaults to the Agent Window's currently active tab.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tab_id: Option<i64>,
|
||||
/// Return entries with sequence strictly greater than this cursor.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub since: Option<u64>,
|
||||
/// Maximum number of entries to return. Extension applies safe defaults and caps.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(range(min = 1))]
|
||||
pub limit: Option<u32>,
|
||||
/// Maximum characters returned per URL / error text. Extension applies safe defaults and caps.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(range(min = 1))]
|
||||
pub max_text_chars: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum NetworkEntryKind {
|
||||
/// A response was received (`Network.responseReceived`).
|
||||
Response,
|
||||
/// The request failed before completing (`Network.loadingFailed`).
|
||||
Failure,
|
||||
}
|
||||
|
||||
impl NetworkEntryKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Response => "response",
|
||||
Self::Failure => "failure",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct NetworkEntry {
|
||||
pub sequence: u64,
|
||||
pub kind: NetworkEntryKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub method: Option<String>,
|
||||
pub url: String,
|
||||
/// HTTP status code (`response` entries only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub status: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub status_text: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mime_type: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub resource_type: Option<String>,
|
||||
/// CDP failure reason (`failure` entries only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error_text: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub timestamp: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct NetworkResult {
|
||||
pub tab_id: i64,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub entries: Vec<NetworkEntry>,
|
||||
pub next_since: u64,
|
||||
#[serde(default)]
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn network_params_omit_optional_fields() {
|
||||
let params = NetworkParams {
|
||||
session_id: "aa11".into(),
|
||||
tab_id: None,
|
||||
since: None,
|
||||
limit: None,
|
||||
max_text_chars: None,
|
||||
};
|
||||
let value = serde_json::to_value(¶ms).unwrap();
|
||||
assert_eq!(value["session_id"], "aa11");
|
||||
assert!(value.get("tab_id").is_none());
|
||||
assert!(value.get("since").is_none());
|
||||
assert!(value.get("limit").is_none());
|
||||
assert!(value.get("max_text_chars").is_none());
|
||||
let round: NetworkParams = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(round, params);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_result_round_trips_response_and_failure() {
|
||||
let result = NetworkResult {
|
||||
tab_id: 7,
|
||||
entries: vec![
|
||||
NetworkEntry {
|
||||
sequence: 3,
|
||||
kind: NetworkEntryKind::Response,
|
||||
method: Some("GET".into()),
|
||||
url: "https://example.test/api".into(),
|
||||
status: Some(404),
|
||||
status_text: Some("Not Found".into()),
|
||||
mime_type: Some("application/json".into()),
|
||||
resource_type: Some("Fetch".into()),
|
||||
error_text: None,
|
||||
timestamp: Some(1234.5),
|
||||
truncated: false,
|
||||
},
|
||||
NetworkEntry {
|
||||
sequence: 4,
|
||||
kind: NetworkEntryKind::Failure,
|
||||
method: Some("GET".into()),
|
||||
url: "https://example.test/blocked".into(),
|
||||
status: None,
|
||||
status_text: None,
|
||||
mime_type: None,
|
||||
resource_type: Some("Script".into()),
|
||||
error_text: Some("net::ERR_BLOCKED_BY_CLIENT".into()),
|
||||
timestamp: Some(1240.0),
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
next_since: 4,
|
||||
truncated: false,
|
||||
};
|
||||
let value = serde_json::to_value(&result).unwrap();
|
||||
assert_eq!(value["entries"][0]["kind"], json!("response"));
|
||||
assert_eq!(value["entries"][0]["status"], json!(404));
|
||||
assert_eq!(value["entries"][1]["kind"], json!("failure"));
|
||||
assert_eq!(
|
||||
value["entries"][1]["error_text"],
|
||||
json!("net::ERR_BLOCKED_BY_CLIENT")
|
||||
);
|
||||
let round: NetworkResult = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(round, result);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user