browsing 0.1.3

Lightweight MCP/API for browser automation: navigate, get content (text), screenshot. Parallelism via RwLock.
Documentation
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Comprehensive tests for agent service and execution logic
//!
//! These tests cover:
//! - Agent creation and configuration
//! - Agent execution flow and decision making
//! - History tracking and state management
//! - Usage tracking (tokens, cost)
//! - Error handling and recovery

use browsing::agent::views::{
    ActionResult, AgentHistory, AgentHistoryList, AgentSettings, AgentState,
};
use browsing::error::BrowsingError;
use browsing::llm::base::{ChatInvokeUsage, ChatMessage};
use browsing::tokens::views::UsageSummary;
use std::collections::HashMap;

// ============================================================================
// Agent Creation Tests
// ============================================================================

#[test]
fn test_agent_task_validation() {
    let valid_tasks = vec![
        "Navigate to example.com and click the first link",
        "Search for 'rust programming' and extract the first result",
        "Fill out the contact form with test data",
        "Extract all product prices from the page",
        "Scroll to the bottom and load more content",
    ];

    for task in valid_tasks {
        assert!(!task.is_empty(), "Agent task should not be empty");
        assert!(task.len() <= 4096, "Agent task should be reasonable length");
    }
}

#[test]
fn test_agent_max_steps_validation() {
    let valid_max_steps = vec![1u32, 10, 50, 100, 500];

    for max_steps in valid_max_steps {
        assert!(max_steps > 0, "Max steps should be positive");
        assert!(max_steps <= 1000, "Max steps should be reasonable");
    }
}

#[test]
fn test_agent_default_state() {
    let _state = AgentState::default();

    // Default state should have no errors
    assert!(true, "AgentState created successfully");
}

#[test]
fn test_agent_settings_default() {
    let _settings = AgentSettings::default();

    // Default settings should be valid
    assert!(true, "AgentSettings created successfully");
}

// ============================================================================
// AgentSettings Tests
// ============================================================================

#[test]
fn test_agent_settings_system_message() {
    let system_messages = vec![
        "You are a helpful assistant.",
        "Navigate the web and complete tasks.",
        "Extract information from web pages efficiently.",
    ];

    for msg in system_messages {
        assert!(!msg.is_empty(), "System message should not be empty");
    }
}

#[test]
fn test_agent_settings_validation() {
    let settings = AgentSettings {
        override_system_message: Some("Custom system message".to_string()),
        ..Default::default()
    };

    assert!(settings.override_system_message.is_some());
}

// ============================================================================
// AgentHistory Tests
// ============================================================================

#[test]
fn test_agent_history_creation() {
    use browsing::browser::views::BrowserStateHistory;

    let history = AgentHistory {
        model_output: None,
        result: vec![ActionResult {
            extracted_content: Some("Test content".to_string()),
            ..Default::default()
        }],
        state: BrowserStateHistory {
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            tabs: vec![],
            interacted_element: vec![],
            screenshot_path: None,
        },
        metadata: None,
        state_message: None,
    };

    assert_eq!(history.result.len(), 1);
    assert!(history.result[0].extracted_content.is_some());
}

#[test]
fn test_agent_history_step_validation() {
    let valid_steps = vec![0u32, 1, 10, 100, 999];

    for step in valid_steps {
        assert!(step < u32::MAX, "Step should be valid");
    }
}

#[test]
fn test_agent_history_list_creation() {
    let history_list = AgentHistoryList {
        history: vec![],
        usage: None,
    };

    assert!(history_list.history.is_empty());
    assert!(history_list.usage.is_none());
}

#[test]
fn test_agent_history_list_with_entries() {
    use browsing::browser::views::BrowserStateHistory;

    let state = BrowserStateHistory {
        url: "https://example.com".to_string(),
        title: "Example".to_string(),
        tabs: vec![],
        interacted_element: vec![],
        screenshot_path: None,
    };

    let history_list = AgentHistoryList {
        history: vec![
            AgentHistory {
                model_output: None,
                result: vec![ActionResult::default()],
                state: state.clone(),
                metadata: None,
                state_message: None,
            },
            AgentHistory {
                model_output: None,
                result: vec![ActionResult::default()],
                state: state.clone(),
                metadata: None,
                state_message: None,
            },
        ],
        usage: None,
    };

    assert_eq!(history_list.history.len(), 2);
}

// ============================================================================
// UsageTracker Tests
// ============================================================================

#[test]
fn test_usage_tracker_initial_state() {
    let prompt_tokens = 0u32;
    let completion_tokens = 0u32;
    let total_tokens = 0u32;

    assert_eq!(prompt_tokens, 0);
    assert_eq!(completion_tokens, 0);
    assert_eq!(total_tokens, 0);
}

#[test]
fn test_usage_tracker_add_usage() {
    let mut total_prompt_tokens = 0u32;
    let mut total_completion_tokens = 0u32;
    let mut total_tokens = 0u32;

    let usage1 = ChatInvokeUsage {
        prompt_tokens: 100,
        prompt_cached_tokens: None,
        prompt_cache_creation_tokens: None,
        prompt_image_tokens: None,
        completion_tokens: 50,
        total_tokens: 150,
    };

    total_prompt_tokens += usage1.prompt_tokens;
    total_completion_tokens += usage1.completion_tokens;
    total_tokens += usage1.total_tokens;

    assert_eq!(total_prompt_tokens, 100);
    assert_eq!(total_completion_tokens, 50);
    assert_eq!(total_tokens, 150);

    let usage2 = ChatInvokeUsage {
        prompt_tokens: 200,
        prompt_cached_tokens: None,
        prompt_cache_creation_tokens: None,
        prompt_image_tokens: None,
        completion_tokens: 100,
        total_tokens: 300,
    };

    total_prompt_tokens += usage2.prompt_tokens;
    total_completion_tokens += usage2.completion_tokens;
    total_tokens += usage2.total_tokens;

    assert_eq!(total_prompt_tokens, 300);
    assert_eq!(total_completion_tokens, 150);
    assert_eq!(total_tokens, 450);
}

#[test]
fn test_agent_usage_tracking() {
    // Test usage tracking structure
    let usage = ChatInvokeUsage {
        prompt_tokens: 100,
        prompt_cached_tokens: None,
        prompt_cache_creation_tokens: None,
        prompt_image_tokens: None,
        completion_tokens: 50,
        total_tokens: 150,
    };

    assert_eq!(usage.prompt_tokens, 100);
    assert_eq!(usage.completion_tokens, 50);
    assert_eq!(usage.total_tokens, 150);
    assert_eq!(
        usage.total_tokens,
        usage.prompt_tokens + usage.completion_tokens
    );

    // Test usage summary
    let summary = UsageSummary {
        prompt_tokens: Some(200),
        completion_tokens: Some(100),
        total_tokens: Some(300),
        cost: Some(0.003),
    };

    assert_eq!(summary.prompt_tokens, Some(200));
    assert_eq!(summary.completion_tokens, Some(100));
    assert!(summary.cost.is_some() && summary.cost.unwrap() > 0.0);
}

#[test]
fn test_agent_with_custom_settings() {
    // Test custom agent settings
    use browsing::agent::views::VisionMode;

    let settings = AgentSettings {
        use_vision: VisionMode::Enabled(true),
        max_failures: 3,
        ..Default::default()
    };

    matches!(settings.use_vision, VisionMode::Enabled(_));
    assert_eq!(settings.max_failures, 3);
}

#[test]
fn test_usage_summary_none_values() {
    let summary = UsageSummary {
        prompt_tokens: None,
        completion_tokens: None,
        total_tokens: None,
        cost: None,
    };

    assert!(summary.prompt_tokens.is_none());
    assert!(summary.completion_tokens.is_none());
    assert!(summary.total_tokens.is_none());
    assert!(summary.cost.is_none());
}

#[test]
fn test_cost_calculation() {
    let prompt_tokens = 1000u32;
    let completion_tokens = 500u32;
    let prompt_price_per_1k = 0.0001; // $0.0001 per 1K prompt tokens
    let completion_price_per_1k = 0.0002; // $0.0002 per 1K completion tokens

    let prompt_cost = (prompt_tokens as f64 / 1000.0) * prompt_price_per_1k;
    let completion_cost = (completion_tokens as f64 / 1000.0) * completion_price_per_1k;
    let total_cost = prompt_cost + completion_cost;

    assert!((prompt_cost - 0.0001).abs() < 0.00001);
    assert!((completion_cost - 0.0001).abs() < 0.00001);
    assert!((total_cost - 0.0002).abs() < 0.00001);
}

// ============================================================================
// ChatMessage Tests
// ============================================================================

#[test]
fn test_chat_message_role_validation() {
    let valid_roles = vec!["system", "user", "assistant", "tool"];

    for role in valid_roles {
        assert!(!role.is_empty(), "Role should not be empty");
        assert!(role.len() <= 20, "Role should be short");
    }
}

#[test]
fn test_chat_message_content_validation() {
    let valid_contents = vec![
        "You are a helpful assistant.",
        "Please navigate to the website and extract information.",
        "The task is complete.",
        "",
    ];

    for content in valid_contents {
        // Empty content is allowed for some message types
        assert!(
            content.len() <= 65536,
            "Content should be reasonable length"
        );
    }
}

#[test]
fn test_chat_message_serialization() {
    let message = ChatMessage {
        role: "user".to_string(),
        content: "Test message".to_string(),
    };

    assert_eq!(message.role, "user");
    assert_eq!(message.content, "Test message");
}

// ============================================================================
// Agent State Management Tests
// ============================================================================

#[test]
fn test_agent_state_transitions() {
    let states = vec!["idle", "running", "paused", "completed", "error"];

    for state in states {
        assert!(!state.is_empty(), "State should not be empty");
    }
}

#[test]
fn test_agent_state_serialization() {
    let state = AgentState {
        agent_id: "test-agent-123".to_string(),
        n_steps: 5,
        ..Default::default()
    };

    assert_eq!(state.agent_id, "test-agent-123");
    assert_eq!(state.n_steps, 5);
}

#[test]
fn test_agent_state_with_selector_map() {
    use browsing::dom::views::DOMInteractedElement;

    let mut selector_map = HashMap::new();
    selector_map.insert(
        1u32,
        DOMInteractedElement {
            index: 1,
            backend_node_id: Some(123),
            tag: "button".to_string(),
            text: Some("Click".to_string()),
            attributes: HashMap::new(),
            selector: None,
        },
    );

    assert_eq!(selector_map.len(), 1);
    assert!(selector_map.contains_key(&1));
}

// ============================================================================
// Agent Decision Making Tests
// ============================================================================

#[test]
fn test_action_model_validation() {
    let valid_actions = vec![
        "search",
        "navigate",
        "click",
        "input",
        "scroll",
        "extract_content",
        "create_tab",
        "switch_tab",
    ];

    for action in valid_actions {
        assert!(!action.is_empty(), "Action should not be empty");
    }
}

#[test]
fn test_action_parameters_validation() {
    let test_cases = vec![
        ("url", "https://example.com"),
        ("query", "search term"),
        ("index", "1"),
        ("text", "input text"),
        ("pages", "1.5"),
    ];

    for (key, value) in test_cases {
        assert!(!key.is_empty(), "Parameter key should not be empty");
        assert!(!value.is_empty(), "Parameter value should not be empty");
    }
}

#[test]
fn test_action_result_validation() {
    let result = ActionResult {
        extracted_content: Some("Content".to_string()),
        long_term_memory: Some("Memory".to_string()),
        is_done: Some(true),
        ..Default::default()
    };

    assert_eq!(result.extracted_content, Some("Content".to_string()));
    assert_eq!(result.long_term_memory, Some("Memory".to_string()));
    assert_eq!(result.is_done, Some(true));
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
fn test_agent_error_max_steps_exceeded() {
    let max_steps = 10u32;
    let current_step = 11u32;

    let exceeded = current_step > max_steps;
    assert!(exceeded, "Should detect max steps exceeded");
}

#[test]
fn test_agent_error_invalid_action() {
    let invalid_action = "invalid_action";
    let valid_actions = vec!["search", "navigate", "click"];

    let is_valid = valid_actions.contains(&invalid_action);
    assert!(!is_valid, "Should detect invalid action");
}

#[test]
fn test_agent_error_missing_parameter() {
    let required_params = vec!["url", "query"];
    let provided_params = vec!["url"];

    let has_all_required = required_params.iter().all(|p| provided_params.contains(p));

    assert!(!has_all_required, "Should detect missing parameter");
}

#[test]
fn test_agent_recovery_from_failure() {
    let retry_attempts = vec![1u32, 2, 3];

    for attempt in retry_attempts {
        assert!(attempt <= 3, "Should limit retry attempts");
    }
}

// ============================================================================
// JSON Extraction Tests
// ============================================================================

#[test]
fn test_json_extraction_valid() {
    let valid_json = r#"{"action": "click", "index": 1}"#;
    let parsed: Result<serde_json::Value, _> = serde_json::from_str(valid_json);

    assert!(parsed.is_ok(), "Should parse valid JSON");
}

#[test]
fn test_json_extraction_invalid() {
    let invalid_json = r#"{action: "click", index: 1}"#;
    let parsed: Result<serde_json::Value, _> = serde_json::from_str(invalid_json);

    assert!(parsed.is_err(), "Should fail to parse invalid JSON");
}

#[test]
fn test_json_extraction_malformed() {
    let malformed_json = r#"{"action": "click", "index": }"#;
    let parsed: Result<serde_json::Value, _> = serde_json::from_str(malformed_json);

    assert!(parsed.is_err(), "Should fail to parse malformed JSON");
}

#[test]
fn test_json_repair_attempt() {
    let broken_json = r#"{action: click, index: 1}"#;
    let repaired = broken_json
        .replace(r#"{"#, r#"{"action":"#)
        .replace(r#":"click"#, r#"","action":"click"#)
        .replace(r#"index: "#, r#""index": "#);

    // The repair logic would fix this
    assert!(!repaired.is_empty());
}

// ============================================================================
// Integration Test Markers
// ============================================================================

#[test]
fn test_agent_execution_flow() {
    // Test agent execution flow structure and validation
    // Verify agent can handle valid task descriptions
    let tasks = vec![
        "Navigate to example.com",
        "Find the search button",
        "Click submit",
    ];

    for task in tasks {
        assert!(!task.is_empty(), "Agent task should not be empty");
        assert!(task.len() > 5, "Agent task should be descriptive");
    }

    // Verify action result structure
    let action_result = ActionResult::default();
    assert!(action_result.extracted_content.is_none());
    assert!(action_result.error.is_none());
}

#[test]
fn test_agent_with_multiple_steps() {
    // Test multi-step agent task tracking
    use browsing::agent::views::{AgentHistory, StepMetadata};
    use browsing::browser::views::BrowserStateHistory;

    let history_list = AgentHistoryList {
        history: vec![
            AgentHistory {
                model_output: None,
                result: vec![],
                state: BrowserStateHistory {
                    url: "https://example.com".to_string(),
                    title: "Example".to_string(),
                    tabs: vec![],
                    interacted_element: vec![],
                    screenshot_path: None,
                },
                metadata: Some(StepMetadata {
                    step_start_time: chrono::Utc::now().timestamp() as f64,
                    step_end_time: chrono::Utc::now().timestamp() as f64,
                    step_number: 1,
                }),
                state_message: Some("Step 1 completed".to_string()),
            },
            AgentHistory {
                model_output: None,
                result: vec![],
                state: BrowserStateHistory {
                    url: "https://example.com".to_string(),
                    title: "Example".to_string(),
                    tabs: vec![],
                    interacted_element: vec![],
                    screenshot_path: None,
                },
                metadata: Some(StepMetadata {
                    step_start_time: chrono::Utc::now().timestamp() as f64,
                    step_end_time: chrono::Utc::now().timestamp() as f64,
                    step_number: 2,
                }),
                state_message: Some("Step 2 completed".to_string()),
            },
        ],
        usage: None,
    };

    // Verify multiple steps are tracked
    assert_eq!(history_list.history.len(), 2);

    // Verify all steps have valid metadata
    for history in &history_list.history {
        assert!(history.metadata.is_some());
    }
}

#[test]
fn test_agent_error_recovery() {
    // Test agent error handling structure
    use browsing::agent::views::{AgentHistory, StepMetadata};
    use browsing::browser::views::BrowserStateHistory;

    let error_messages = vec![
        "Navigation failed".to_string(),
        "Timeout occurred".to_string(),
        "Invalid action".to_string(),
    ];

    for error_msg in error_messages {
        assert!(!error_msg.is_empty());

        // Create history with error state message
        let history = AgentHistory {
            model_output: None,
            result: vec![],
            state: BrowserStateHistory {
                url: "https://example.com".to_string(),
                title: "Example".to_string(),
                tabs: vec![],
                interacted_element: vec![],
                screenshot_path: None,
            },
            metadata: None,
            state_message: Some(error_msg),
        };

        assert!(history.state_message.is_some());
    }
}

#[test]
fn test_agent_state_snapshots() {
    // Test state snapshot creation and serialization
    use browsing::agent::views::{AgentHistory, AgentOutput};
    use browsing::browser::views::BrowserStateHistory;
    use serde_json::json;

    let history = AgentHistory {
        model_output: Some(AgentOutput {
            action: vec![json!({
                "action_type": "navigate",
                "params": {"url": "https://example.com"}
            })],
            thinking: Some("Navigate to example.com".to_string()),
            evaluation_previous_goal: None,
            memory: None,
            next_goal: None,
        }),
        result: vec![ActionResult {
            is_done: Some(false),
            success: Some(true),
            judgement: None,
            error: None,
            attachments: None,
            images: None,
            long_term_memory: None,
            extracted_content: Some("Navigation successful".to_string()),
            include_extracted_content_only_once: false,
            metadata: None,
        }],
        state: BrowserStateHistory {
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            tabs: vec![],
            interacted_element: vec![],
            screenshot_path: None,
        },
        metadata: None,
        state_message: None,
    };

    // Verify snapshot structure
    assert!(history.model_output.is_some());
    assert!(!history.result.is_empty());
    assert_eq!(history.state.url, "https://example.com");
}