cli/pkg/webview/webview_test.go

336 lines
9.4 KiB
Go
Raw Normal View History

feat: BugSETI app, WebSocket hub, browser automation, and MCP tools (#336) * feat: add security logging and fix framework regressions This commit implements comprehensive security event logging and resolves critical regressions in the core framework. Security Logging: - Enhanced `pkg/log` with a `Security` level and helper. - Added `log.Username()` to consistently identify the executing user. - Instrumented GitHub CLI auth, Agentic configuration, filesystem sandbox, MCP handlers, and MCP TCP transport with security logs. - Added `SecurityStyle` to the CLI for consistent visual representation of security events. UniFi Security (CodeQL): - Refactored `pkg/unifi` to remove hardcoded `InsecureSkipVerify`, resolving a high-severity alert. - Added a `--verify-tls` flag and configuration option to control TLS verification. - Updated command handlers to support the new verification parameter. Framework Fixes: - Restored original signatures for `MustServiceFor`, `Config()`, and `Display()` in `pkg/framework/core`, which had been corrupted during a merge. - Fixed `pkg/framework/framework.go` and `pkg/framework/core/runtime_pkg.go` to match the restored signatures. - These fixes resolve project-wide compilation errors caused by the signature mismatches. I encountered significant blockers due to a corrupted state of the `dev` branch after a merge, which introduced breaking changes in the core framework's DI system. I had to manually reconcile these signatures with the expected usage across the codebase to restore build stability. * feat(mcp): add RAG tools (query, ingest, collections) Add vector database tools to the MCP server for RAG operations: - rag_query: Search for relevant documentation using semantic similarity - rag_ingest: Ingest files or directories into the vector database - rag_collections: List available collections Uses existing internal/cmd/rag exports (QueryDocs, IngestDirectory, IngestFile) and pkg/rag for Qdrant client access. Default collection is "hostuk-docs" with topK=5 for queries. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(mcp): add metrics tools (record, query) Add MCP tools for recording and querying AI/security metrics events. The metrics_record tool writes events to daily JSONL files, and the metrics_query tool provides aggregated statistics by type, repo, and agent. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add 'core mcp serve' command Add CLI command to start the MCP server for AI tool integration. - Create internal/cmd/mcpcmd package with serve subcommand - Support --workspace flag for directory restriction - Handle SIGINT/SIGTERM for clean shutdown - Register in full.go build variant Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(ws): add WebSocket hub package for real-time streaming Add pkg/ws package implementing a hub pattern for WebSocket connections: - Hub manages client connections, broadcasts, and channel subscriptions - Client struct represents connected WebSocket clients - Message types: process_output, process_status, event, error, ping/pong - Channel-based subscription system (subscribe/unsubscribe) - SendProcessOutput and SendProcessStatus for process streaming integration - Full test coverage including concurrency tests Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(mcp): add process management and WebSocket MCP tools Add MCP tools for process management: - process_start: Start a new external process - process_stop: Gracefully stop a running process - process_kill: Force kill a process - process_list: List all managed processes - process_output: Get captured process output - process_input: Send input to process stdin Add MCP tools for WebSocket: - ws_start: Start WebSocket server for real-time streaming - ws_info: Get hub statistics (clients, channels) Update Service struct with optional process.Service and ws.Hub fields, new WithProcessService and WithWSHub options, getter methods, and Shutdown method for cleanup. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(webview): add browser automation package via Chrome DevTools Protocol Add pkg/webview package for browser automation: - webview.go: Main interface with Connect, Navigate, Click, Type, QuerySelector, Screenshot, Evaluate - cdp.go: Chrome DevTools Protocol WebSocket client implementation - actions.go: DOM action types (Click, Type, Hover, Scroll, etc.) and ActionSequence builder - console.go: Console message capture and filtering with ConsoleWatcher and ExceptionWatcher - angular.go: Angular-specific helpers for router navigation, component access, and Zone.js stability Add MCP tools for webview: - webview_connect/disconnect: Connection management - webview_navigate: Page navigation - webview_click/type/query/wait: DOM interaction - webview_console: Console output capture - webview_eval: JavaScript execution - webview_screenshot: Screenshot capture Add documentation: - docs/mcp/angular-testing.md: Guide for Angular application testing Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: document new packages and BugSETI application - Update CLAUDE.md with documentation for: - pkg/ws (WebSocket hub for real-time streaming) - pkg/webview (Browser automation via CDP) - pkg/mcp (MCP server tools: process, ws, webview) - BugSETI application overview - Add comprehensive README for BugSETI with: - Installation and configuration guide - Usage workflow documentation - Architecture overview - Contributing guidelines Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(bugseti): add BugSETI system tray app with auto-update BugSETI - Distributed Bug Fixing like SETI@home but for code Features: - System tray app with Wails v3 - GitHub issue fetching with label filters - Issue queue with priority management - AI context seeding via seed-agent-developer skill - Automated PR submission flow - Stats tracking and leaderboard - Cross-platform notifications - Self-updating with stable/beta/nightly channels Includes: - cmd/bugseti: Main application with Angular frontend - internal/bugseti: Core services (fetcher, queue, seeder, submit, config, stats, notify) - internal/bugseti/updater: Auto-update system (checker, downloader, installer) - .github/workflows/bugseti-release.yml: CI/CD for all platforms Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: resolve import cycle and code duplication - Remove pkg/log import from pkg/io/local to break import cycle (pkg/log/rotation.go imports pkg/io, creating circular dependency) - Use stderr logging for security events in sandbox escape detection - Remove unused sync/atomic import from core.go - Fix duplicate LogSecurity function declarations in cli/log.go - Update workspace/service.go Crypt() call to match interface Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: update tests for new function signatures and format code - Update core_test.go: Config(), Display() now panic instead of returning error - Update runtime_pkg_test.go: sr.Config() now panics instead of returning error - Update MustServiceFor tests to use assert.Panics - Format BugSETI, MCP tools, and webview packages with gofmt Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Snider <631881+Snider@users.noreply.github.com> Co-authored-by: Claude <developers@lethean.io> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 17:22:05 +00:00
package webview
import (
"testing"
"time"
)
// TestConsoleMessage_Good verifies the ConsoleMessage struct has expected fields.
func TestConsoleMessage_Good(t *testing.T) {
msg := ConsoleMessage{
Type: "error",
Text: "Test error message",
Timestamp: time.Now(),
URL: "https://example.com/script.js",
Line: 42,
Column: 10,
}
if msg.Type != "error" {
t.Errorf("Expected type 'error', got %q", msg.Type)
}
if msg.Text != "Test error message" {
t.Errorf("Expected text 'Test error message', got %q", msg.Text)
}
if msg.Line != 42 {
t.Errorf("Expected line 42, got %d", msg.Line)
}
}
// TestElementInfo_Good verifies the ElementInfo struct has expected fields.
func TestElementInfo_Good(t *testing.T) {
elem := ElementInfo{
NodeID: 123,
TagName: "DIV",
Attributes: map[string]string{
"id": "container",
"class": "main-content",
},
InnerHTML: "<span>Hello</span>",
InnerText: "Hello",
BoundingBox: &BoundingBox{
X: 100,
Y: 200,
Width: 300,
Height: 400,
},
}
if elem.NodeID != 123 {
t.Errorf("Expected nodeId 123, got %d", elem.NodeID)
}
if elem.TagName != "DIV" {
t.Errorf("Expected tagName 'DIV', got %q", elem.TagName)
}
if elem.Attributes["id"] != "container" {
t.Errorf("Expected id 'container', got %q", elem.Attributes["id"])
}
if elem.BoundingBox == nil {
t.Fatal("Expected bounding box to be set")
}
if elem.BoundingBox.Width != 300 {
t.Errorf("Expected width 300, got %f", elem.BoundingBox.Width)
}
}
// TestBoundingBox_Good verifies the BoundingBox struct has expected fields.
func TestBoundingBox_Good(t *testing.T) {
box := BoundingBox{
X: 10.5,
Y: 20.5,
Width: 100.0,
Height: 50.0,
}
if box.X != 10.5 {
t.Errorf("Expected X 10.5, got %f", box.X)
}
if box.Y != 20.5 {
t.Errorf("Expected Y 20.5, got %f", box.Y)
}
if box.Width != 100.0 {
t.Errorf("Expected width 100.0, got %f", box.Width)
}
if box.Height != 50.0 {
t.Errorf("Expected height 50.0, got %f", box.Height)
}
}
// TestWithTimeout_Good verifies the WithTimeout option sets timeout correctly.
func TestWithTimeout_Good(t *testing.T) {
// We can't fully test without a real Chrome connection,
// but we can verify the option function works
wv := &Webview{}
opt := WithTimeout(60 * time.Second)
err := opt(wv)
if err != nil {
t.Fatalf("WithTimeout returned error: %v", err)
}
if wv.timeout != 60*time.Second {
t.Errorf("Expected timeout 60s, got %v", wv.timeout)
}
}
// TestWithConsoleLimit_Good verifies the WithConsoleLimit option sets limit correctly.
func TestWithConsoleLimit_Good(t *testing.T) {
wv := &Webview{}
opt := WithConsoleLimit(500)
err := opt(wv)
if err != nil {
t.Fatalf("WithConsoleLimit returned error: %v", err)
}
if wv.consoleLimit != 500 {
t.Errorf("Expected consoleLimit 500, got %d", wv.consoleLimit)
}
}
// TestNew_Bad_NoDebugURL verifies New fails without a debug URL.
func TestNew_Bad_NoDebugURL(t *testing.T) {
_, err := New()
if err == nil {
t.Error("Expected error when creating Webview without debug URL")
}
}
// TestNew_Bad_InvalidDebugURL verifies New fails with invalid debug URL.
func TestNew_Bad_InvalidDebugURL(t *testing.T) {
_, err := New(WithDebugURL("http://localhost:99999"))
if err == nil {
t.Error("Expected error when connecting to invalid debug URL")
}
}
// TestActionSequence_Good verifies action sequence building works.
func TestActionSequence_Good(t *testing.T) {
seq := NewActionSequence().
Navigate("https://example.com").
WaitForSelector("#main").
Click("#button").
Type("#input", "hello").
Wait(100 * time.Millisecond)
if len(seq.actions) != 5 {
t.Errorf("Expected 5 actions, got %d", len(seq.actions))
}
}
// TestClickAction_Good verifies ClickAction struct.
func TestClickAction_Good(t *testing.T) {
action := ClickAction{Selector: "#submit"}
if action.Selector != "#submit" {
t.Errorf("Expected selector '#submit', got %q", action.Selector)
}
}
// TestTypeAction_Good verifies TypeAction struct.
func TestTypeAction_Good(t *testing.T) {
action := TypeAction{Selector: "#email", Text: "test@example.com"}
if action.Selector != "#email" {
t.Errorf("Expected selector '#email', got %q", action.Selector)
}
if action.Text != "test@example.com" {
t.Errorf("Expected text 'test@example.com', got %q", action.Text)
}
}
// TestNavigateAction_Good verifies NavigateAction struct.
func TestNavigateAction_Good(t *testing.T) {
action := NavigateAction{URL: "https://example.com"}
if action.URL != "https://example.com" {
t.Errorf("Expected URL 'https://example.com', got %q", action.URL)
}
}
// TestWaitAction_Good verifies WaitAction struct.
func TestWaitAction_Good(t *testing.T) {
action := WaitAction{Duration: 5 * time.Second}
if action.Duration != 5*time.Second {
t.Errorf("Expected duration 5s, got %v", action.Duration)
}
}
// TestWaitForSelectorAction_Good verifies WaitForSelectorAction struct.
func TestWaitForSelectorAction_Good(t *testing.T) {
action := WaitForSelectorAction{Selector: ".loading"}
if action.Selector != ".loading" {
t.Errorf("Expected selector '.loading', got %q", action.Selector)
}
}
// TestScrollAction_Good verifies ScrollAction struct.
func TestScrollAction_Good(t *testing.T) {
action := ScrollAction{X: 0, Y: 500}
if action.X != 0 {
t.Errorf("Expected X 0, got %d", action.X)
}
if action.Y != 500 {
t.Errorf("Expected Y 500, got %d", action.Y)
}
}
// TestFocusAction_Good verifies FocusAction struct.
func TestFocusAction_Good(t *testing.T) {
action := FocusAction{Selector: "#input"}
if action.Selector != "#input" {
t.Errorf("Expected selector '#input', got %q", action.Selector)
}
}
// TestBlurAction_Good verifies BlurAction struct.
func TestBlurAction_Good(t *testing.T) {
action := BlurAction{Selector: "#input"}
if action.Selector != "#input" {
t.Errorf("Expected selector '#input', got %q", action.Selector)
}
}
// TestClearAction_Good verifies ClearAction struct.
func TestClearAction_Good(t *testing.T) {
action := ClearAction{Selector: "#input"}
if action.Selector != "#input" {
t.Errorf("Expected selector '#input', got %q", action.Selector)
}
}
// TestSelectAction_Good verifies SelectAction struct.
func TestSelectAction_Good(t *testing.T) {
action := SelectAction{Selector: "#dropdown", Value: "option1"}
if action.Selector != "#dropdown" {
t.Errorf("Expected selector '#dropdown', got %q", action.Selector)
}
if action.Value != "option1" {
t.Errorf("Expected value 'option1', got %q", action.Value)
}
}
// TestCheckAction_Good verifies CheckAction struct.
func TestCheckAction_Good(t *testing.T) {
action := CheckAction{Selector: "#checkbox", Checked: true}
if action.Selector != "#checkbox" {
t.Errorf("Expected selector '#checkbox', got %q", action.Selector)
}
if !action.Checked {
t.Error("Expected checked to be true")
}
}
// TestHoverAction_Good verifies HoverAction struct.
func TestHoverAction_Good(t *testing.T) {
action := HoverAction{Selector: "#menu-item"}
if action.Selector != "#menu-item" {
t.Errorf("Expected selector '#menu-item', got %q", action.Selector)
}
}
// TestDoubleClickAction_Good verifies DoubleClickAction struct.
func TestDoubleClickAction_Good(t *testing.T) {
action := DoubleClickAction{Selector: "#editable"}
if action.Selector != "#editable" {
t.Errorf("Expected selector '#editable', got %q", action.Selector)
}
}
// TestRightClickAction_Good verifies RightClickAction struct.
func TestRightClickAction_Good(t *testing.T) {
action := RightClickAction{Selector: "#context-menu-trigger"}
if action.Selector != "#context-menu-trigger" {
t.Errorf("Expected selector '#context-menu-trigger', got %q", action.Selector)
}
}
// TestPressKeyAction_Good verifies PressKeyAction struct.
func TestPressKeyAction_Good(t *testing.T) {
action := PressKeyAction{Key: "Enter"}
if action.Key != "Enter" {
t.Errorf("Expected key 'Enter', got %q", action.Key)
}
}
// TestSetAttributeAction_Good verifies SetAttributeAction struct.
func TestSetAttributeAction_Good(t *testing.T) {
action := SetAttributeAction{
Selector: "#element",
Attribute: "data-value",
Value: "test",
}
if action.Selector != "#element" {
t.Errorf("Expected selector '#element', got %q", action.Selector)
}
if action.Attribute != "data-value" {
t.Errorf("Expected attribute 'data-value', got %q", action.Attribute)
}
if action.Value != "test" {
t.Errorf("Expected value 'test', got %q", action.Value)
}
}
// TestRemoveAttributeAction_Good verifies RemoveAttributeAction struct.
func TestRemoveAttributeAction_Good(t *testing.T) {
action := RemoveAttributeAction{
Selector: "#element",
Attribute: "disabled",
}
if action.Selector != "#element" {
t.Errorf("Expected selector '#element', got %q", action.Selector)
}
if action.Attribute != "disabled" {
t.Errorf("Expected attribute 'disabled', got %q", action.Attribute)
}
}
// TestSetValueAction_Good verifies SetValueAction struct.
func TestSetValueAction_Good(t *testing.T) {
action := SetValueAction{
Selector: "#input",
Value: "new value",
}
if action.Selector != "#input" {
t.Errorf("Expected selector '#input', got %q", action.Selector)
}
if action.Value != "new value" {
t.Errorf("Expected value 'new value', got %q", action.Value)
}
}
// TestScrollIntoViewAction_Good verifies ScrollIntoViewAction struct.
func TestScrollIntoViewAction_Good(t *testing.T) {
action := ScrollIntoViewAction{Selector: "#target"}
if action.Selector != "#target" {
t.Errorf("Expected selector '#target', got %q", action.Selector)
}
}