cli/pkg/webview/console.go
Vi 4debdc1449 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

509 lines
12 KiB
Go

package webview
import (
"context"
"fmt"
"sync"
"time"
)
// ConsoleWatcher provides advanced console message watching capabilities.
type ConsoleWatcher struct {
mu sync.RWMutex
wv *Webview
messages []ConsoleMessage
filters []ConsoleFilter
limit int
handlers []ConsoleHandler
}
// ConsoleFilter filters console messages.
type ConsoleFilter struct {
Type string // Filter by type (log, warn, error, info, debug), empty for all
Pattern string // Filter by text pattern (substring match)
}
// ConsoleHandler is called when a matching console message is received.
type ConsoleHandler func(msg ConsoleMessage)
// NewConsoleWatcher creates a new console watcher for the webview.
func NewConsoleWatcher(wv *Webview) *ConsoleWatcher {
cw := &ConsoleWatcher{
wv: wv,
messages: make([]ConsoleMessage, 0, 100),
filters: make([]ConsoleFilter, 0),
limit: 1000,
handlers: make([]ConsoleHandler, 0),
}
// Subscribe to console events from the webview's client
wv.client.OnEvent("Runtime.consoleAPICalled", func(params map[string]any) {
cw.handleConsoleEvent(params)
})
return cw
}
// AddFilter adds a filter to the watcher.
func (cw *ConsoleWatcher) AddFilter(filter ConsoleFilter) {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.filters = append(cw.filters, filter)
}
// ClearFilters removes all filters.
func (cw *ConsoleWatcher) ClearFilters() {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.filters = cw.filters[:0]
}
// AddHandler adds a handler for console messages.
func (cw *ConsoleWatcher) AddHandler(handler ConsoleHandler) {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.handlers = append(cw.handlers, handler)
}
// SetLimit sets the maximum number of messages to retain.
func (cw *ConsoleWatcher) SetLimit(limit int) {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.limit = limit
}
// Messages returns all captured messages.
func (cw *ConsoleWatcher) Messages() []ConsoleMessage {
cw.mu.RLock()
defer cw.mu.RUnlock()
result := make([]ConsoleMessage, len(cw.messages))
copy(result, cw.messages)
return result
}
// FilteredMessages returns messages matching the current filters.
func (cw *ConsoleWatcher) FilteredMessages() []ConsoleMessage {
cw.mu.RLock()
defer cw.mu.RUnlock()
if len(cw.filters) == 0 {
result := make([]ConsoleMessage, len(cw.messages))
copy(result, cw.messages)
return result
}
result := make([]ConsoleMessage, 0)
for _, msg := range cw.messages {
if cw.matchesFilter(msg) {
result = append(result, msg)
}
}
return result
}
// Errors returns all error messages.
func (cw *ConsoleWatcher) Errors() []ConsoleMessage {
cw.mu.RLock()
defer cw.mu.RUnlock()
result := make([]ConsoleMessage, 0)
for _, msg := range cw.messages {
if msg.Type == "error" {
result = append(result, msg)
}
}
return result
}
// Warnings returns all warning messages.
func (cw *ConsoleWatcher) Warnings() []ConsoleMessage {
cw.mu.RLock()
defer cw.mu.RUnlock()
result := make([]ConsoleMessage, 0)
for _, msg := range cw.messages {
if msg.Type == "warning" {
result = append(result, msg)
}
}
return result
}
// Clear clears all captured messages.
func (cw *ConsoleWatcher) Clear() {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.messages = cw.messages[:0]
}
// WaitForMessage waits for a message matching the filter.
func (cw *ConsoleWatcher) WaitForMessage(ctx context.Context, filter ConsoleFilter) (*ConsoleMessage, error) {
// First check existing messages
cw.mu.RLock()
for _, msg := range cw.messages {
if cw.matchesSingleFilter(msg, filter) {
cw.mu.RUnlock()
return &msg, nil
}
}
cw.mu.RUnlock()
// Set up a channel for new messages
msgCh := make(chan ConsoleMessage, 1)
handler := func(msg ConsoleMessage) {
if cw.matchesSingleFilter(msg, filter) {
select {
case msgCh <- msg:
default:
}
}
}
cw.AddHandler(handler)
defer func() {
cw.mu.Lock()
// Remove handler (simple implementation - in production you'd want a handle-based removal)
cw.handlers = cw.handlers[:len(cw.handlers)-1]
cw.mu.Unlock()
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg := <-msgCh:
return &msg, nil
}
}
// WaitForError waits for an error message.
func (cw *ConsoleWatcher) WaitForError(ctx context.Context) (*ConsoleMessage, error) {
return cw.WaitForMessage(ctx, ConsoleFilter{Type: "error"})
}
// HasErrors returns true if there are any error messages.
func (cw *ConsoleWatcher) HasErrors() bool {
cw.mu.RLock()
defer cw.mu.RUnlock()
for _, msg := range cw.messages {
if msg.Type == "error" {
return true
}
}
return false
}
// Count returns the number of captured messages.
func (cw *ConsoleWatcher) Count() int {
cw.mu.RLock()
defer cw.mu.RUnlock()
return len(cw.messages)
}
// ErrorCount returns the number of error messages.
func (cw *ConsoleWatcher) ErrorCount() int {
cw.mu.RLock()
defer cw.mu.RUnlock()
count := 0
for _, msg := range cw.messages {
if msg.Type == "error" {
count++
}
}
return count
}
// handleConsoleEvent processes incoming console events.
func (cw *ConsoleWatcher) handleConsoleEvent(params map[string]any) {
msgType, _ := params["type"].(string)
// Extract args
args, _ := params["args"].([]any)
var text string
for i, arg := range args {
if argMap, ok := arg.(map[string]any); ok {
if val, ok := argMap["value"]; ok {
if i > 0 {
text += " "
}
text += fmt.Sprint(val)
}
}
}
// Extract stack trace info
stackTrace, _ := params["stackTrace"].(map[string]any)
var url string
var line, column int
if callFrames, ok := stackTrace["callFrames"].([]any); ok && len(callFrames) > 0 {
if frame, ok := callFrames[0].(map[string]any); ok {
url, _ = frame["url"].(string)
lineFloat, _ := frame["lineNumber"].(float64)
colFloat, _ := frame["columnNumber"].(float64)
line = int(lineFloat)
column = int(colFloat)
}
}
msg := ConsoleMessage{
Type: msgType,
Text: text,
Timestamp: time.Now(),
URL: url,
Line: line,
Column: column,
}
cw.addMessage(msg)
}
// addMessage adds a message to the store and notifies handlers.
func (cw *ConsoleWatcher) addMessage(msg ConsoleMessage) {
cw.mu.Lock()
// Enforce limit
if len(cw.messages) >= cw.limit {
cw.messages = cw.messages[len(cw.messages)-cw.limit+100:]
}
cw.messages = append(cw.messages, msg)
// Copy handlers to call outside lock
handlers := make([]ConsoleHandler, len(cw.handlers))
copy(handlers, cw.handlers)
cw.mu.Unlock()
// Call handlers
for _, handler := range handlers {
handler(msg)
}
}
// matchesFilter checks if a message matches any filter.
func (cw *ConsoleWatcher) matchesFilter(msg ConsoleMessage) bool {
if len(cw.filters) == 0 {
return true
}
for _, filter := range cw.filters {
if cw.matchesSingleFilter(msg, filter) {
return true
}
}
return false
}
// matchesSingleFilter checks if a message matches a specific filter.
func (cw *ConsoleWatcher) matchesSingleFilter(msg ConsoleMessage, filter ConsoleFilter) bool {
if filter.Type != "" && msg.Type != filter.Type {
return false
}
if filter.Pattern != "" {
// Simple substring match
if !containsString(msg.Text, filter.Pattern) {
return false
}
}
return true
}
// containsString checks if s contains substr (case-sensitive).
func containsString(s, substr string) bool {
return len(substr) == 0 || (len(s) >= len(substr) && findString(s, substr) >= 0)
}
// findString finds substr in s, returns -1 if not found.
func findString(s, substr string) int {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return i
}
}
return -1
}
// ExceptionInfo represents information about a JavaScript exception.
type ExceptionInfo struct {
Text string `json:"text"`
LineNumber int `json:"lineNumber"`
ColumnNumber int `json:"columnNumber"`
URL string `json:"url"`
StackTrace string `json:"stackTrace"`
Timestamp time.Time `json:"timestamp"`
}
// ExceptionWatcher watches for JavaScript exceptions.
type ExceptionWatcher struct {
mu sync.RWMutex
wv *Webview
exceptions []ExceptionInfo
handlers []func(ExceptionInfo)
}
// NewExceptionWatcher creates a new exception watcher.
func NewExceptionWatcher(wv *Webview) *ExceptionWatcher {
ew := &ExceptionWatcher{
wv: wv,
exceptions: make([]ExceptionInfo, 0),
handlers: make([]func(ExceptionInfo), 0),
}
// Subscribe to exception events
wv.client.OnEvent("Runtime.exceptionThrown", func(params map[string]any) {
ew.handleException(params)
})
return ew
}
// Exceptions returns all captured exceptions.
func (ew *ExceptionWatcher) Exceptions() []ExceptionInfo {
ew.mu.RLock()
defer ew.mu.RUnlock()
result := make([]ExceptionInfo, len(ew.exceptions))
copy(result, ew.exceptions)
return result
}
// Clear clears all captured exceptions.
func (ew *ExceptionWatcher) Clear() {
ew.mu.Lock()
defer ew.mu.Unlock()
ew.exceptions = ew.exceptions[:0]
}
// HasExceptions returns true if there are any exceptions.
func (ew *ExceptionWatcher) HasExceptions() bool {
ew.mu.RLock()
defer ew.mu.RUnlock()
return len(ew.exceptions) > 0
}
// Count returns the number of exceptions.
func (ew *ExceptionWatcher) Count() int {
ew.mu.RLock()
defer ew.mu.RUnlock()
return len(ew.exceptions)
}
// AddHandler adds a handler for exceptions.
func (ew *ExceptionWatcher) AddHandler(handler func(ExceptionInfo)) {
ew.mu.Lock()
defer ew.mu.Unlock()
ew.handlers = append(ew.handlers, handler)
}
// WaitForException waits for an exception to be thrown.
func (ew *ExceptionWatcher) WaitForException(ctx context.Context) (*ExceptionInfo, error) {
// Check existing exceptions first
ew.mu.RLock()
if len(ew.exceptions) > 0 {
exc := ew.exceptions[len(ew.exceptions)-1]
ew.mu.RUnlock()
return &exc, nil
}
ew.mu.RUnlock()
// Set up a channel for new exceptions
excCh := make(chan ExceptionInfo, 1)
handler := func(exc ExceptionInfo) {
select {
case excCh <- exc:
default:
}
}
ew.AddHandler(handler)
defer func() {
ew.mu.Lock()
ew.handlers = ew.handlers[:len(ew.handlers)-1]
ew.mu.Unlock()
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case exc := <-excCh:
return &exc, nil
}
}
// handleException processes exception events.
func (ew *ExceptionWatcher) handleException(params map[string]any) {
exceptionDetails, ok := params["exceptionDetails"].(map[string]any)
if !ok {
return
}
text, _ := exceptionDetails["text"].(string)
lineNum, _ := exceptionDetails["lineNumber"].(float64)
colNum, _ := exceptionDetails["columnNumber"].(float64)
url, _ := exceptionDetails["url"].(string)
// Extract stack trace
var stackTrace string
if st, ok := exceptionDetails["stackTrace"].(map[string]any); ok {
if frames, ok := st["callFrames"].([]any); ok {
for _, f := range frames {
if frame, ok := f.(map[string]any); ok {
funcName, _ := frame["functionName"].(string)
frameURL, _ := frame["url"].(string)
frameLine, _ := frame["lineNumber"].(float64)
frameCol, _ := frame["columnNumber"].(float64)
stackTrace += fmt.Sprintf(" at %s (%s:%d:%d)\n", funcName, frameURL, int(frameLine), int(frameCol))
}
}
}
}
// Try to get exception value description
if exc, ok := exceptionDetails["exception"].(map[string]any); ok {
if desc, ok := exc["description"].(string); ok && desc != "" {
text = desc
}
}
info := ExceptionInfo{
Text: text,
LineNumber: int(lineNum),
ColumnNumber: int(colNum),
URL: url,
StackTrace: stackTrace,
Timestamp: time.Now(),
}
ew.mu.Lock()
ew.exceptions = append(ew.exceptions, info)
handlers := make([]func(ExceptionInfo), len(ew.handlers))
copy(handlers, ew.handlers)
ew.mu.Unlock()
// Call handlers
for _, handler := range handlers {
handler(info)
}
}
// FormatConsoleOutput formats console messages for display.
func FormatConsoleOutput(messages []ConsoleMessage) string {
var output string
for _, msg := range messages {
prefix := ""
switch msg.Type {
case "error":
prefix = "[ERROR]"
case "warning":
prefix = "[WARN]"
case "info":
prefix = "[INFO]"
case "debug":
prefix = "[DEBUG]"
default:
prefix = "[LOG]"
}
timestamp := msg.Timestamp.Format("15:04:05.000")
output += fmt.Sprintf("%s %s %s\n", timestamp, prefix, msg.Text)
}
return output
}