Implementing an RPC monitoring solution with a web-ui as implementation example. (#244)

* bd sync: 2025-10-30 12:12:27

* Working on frontend

* bd sync: 2025-11-06 16:55:55

* feat: finish bd monitor human viewer

* Merge conflicts resolved and added tests

* bd sync: 2025-11-06 17:23:41

* bd sync: 2025-11-06 17:34:52

* feat: Add reload button and multiselect status filter to monitor

- Changed status filter from single select to multiselect with 'Open' selected by default
- Added reload button with visual feedback (hover/active states)
- Updated filterIssues() to handle multiple selected statuses
- Added reloadData() function that reloads both stats and issues
- Improved responsive design for mobile devices
- Filter controls now use flexbox layout with better spacing

* fix: Update monitor statistics to show Total, In Progress, Open, Closed

- Replaced 'Ready to Work' stat with 'In Progress' stat
- Reordered stats to show logical progression: Total -> In Progress -> Open -> Closed
- Updated loadStats() to fetch in-progress count from stats API
- Removed unnecessary separate API call for ready count

* fix: Correct API field names in monitor stats JavaScript

The JavaScript was using incorrect field names (stats.total, stats.by_status)
that don't match the actual types.Statistics struct which uses flat fields
with underscores (total_issues, in_progress_issues, etc).

Fixed by updating loadStats() to use correct field names:
- stats.total -> stats.total_issues
- stats.by_status?.['in-progress'] -> stats.in_progress_issues
- stats.by_status?.open -> stats.open_issues
- stats.by_status?.closed -> stats.closed_issues

Fixes beads-9

* bd sync: 2025-11-06 17:51:24

* bd sync: 2025-11-06 17:56:09

* fix: Make monitor require daemon to prevent SQLite locking

Implemented Option 1 from beads-eel: monitor now requires daemon and never
opens direct SQLite connection.

Changes:
- Added 'monitor' to noDbCommands list in main.go to skip normal DB initialization
- Added validateDaemonForMonitor() PreRun function that:
  - Finds database path using beads.FindDatabasePath()
  - Validates daemon is running and healthy
  - Fails gracefully with clear error message if no daemon
  - Only uses RPC connection, never opens SQLite directly

Benefits:
- Eliminates SQLite locking conflicts between monitor and daemon
- Users can now close/update issues via CLI while monitor runs
- Clear error messages guide users to start daemon first

Fixes beads-eel

* bd sync: 2025-11-06 18:03:50

* docs: Add bd daemons restart subcommand documentation

Added documentation for the 'bd daemons restart' subcommand across all documentation files:

- commands/daemons.md: Added full restart subcommand section with synopsis, description, arguments, flags, and examples
- README.md: Added restart examples to daemon management section
- AGENTS.md: Added restart examples with --json flag for agents

The restart command gracefully stops and starts a specific daemon by workspace path or PID,
useful after upgrading bd or when a daemon needs refreshing.

Fixes beads-11

* bd sync: 2025-11-06 18:13:16

* Separated the web ui from the general monitoring functionality

---------

Co-authored-by: Steve Yegge <stevey@sourcegraph.com>
This commit is contained in:
Markus Flür
2025-11-07 18:49:12 +01:00
committed by GitHub
parent 19da81caea
commit e7f532db93
18 changed files with 1982 additions and 23 deletions

View File

@@ -0,0 +1,272 @@
# Monitor WebUI - Real-time Issue Tracking Dashboard
A standalone web-based monitoring interface for beads that provides real-time issue tracking through a clean, responsive web UI.
## Overview
The Monitor WebUI is a separate runtime that connects to the beads daemon via RPC to provide:
- **Real-time updates** via WebSocket connections
- **Responsive design** with desktop table view and mobile card view
- **Issue filtering** by status and priority
- **Statistics dashboard** showing issue counts by status
- **Detailed issue views** with full metadata
- **Clean, modern UI** styled with Milligram CSS
## Architecture
The Monitor WebUI demonstrates how to build custom interfaces on top of beads using:
- **RPC Protocol**: Connects to the daemon's Unix socket for database operations
- **WebSocket Broadcasting**: Polls mutation events and broadcasts to connected clients
- **Embedded Web Assets**: HTML, CSS, and JavaScript served from the binary
- **Standalone Binary**: Runs independently from the `bd` CLI
## Prerequisites
Before running the monitor, you must have:
1. A beads database initialized (run `bd init` in your project)
2. The beads daemon running (run `bd daemon`)
## Building
From this directory:
```bash
go build
```
Or using bun (if available):
```bash
bun run go build
```
This creates a `monitor-webui` binary in the current directory.
## Usage
### Basic Usage
Start the monitor on default port 8080:
```bash
./monitor-webui
```
Then open your browser to http://localhost:8080
### Custom Port
Start on a different port:
```bash
./monitor-webui -port 3000
```
### Bind to All Interfaces
To access from other machines on your network:
```bash
./monitor-webui -host 0.0.0.0 -port 8080
```
### Custom Database Path
If your database is not in the current directory:
```bash
./monitor-webui -db /path/to/your/beads.db
```
### Custom Socket Path
If you need to specify a custom daemon socket:
```bash
./monitor-webui -socket /path/to/beads.db.sock
```
## Command-Line Flags
- `-port` - Port for web server (default: 8080)
- `-host` - Host to bind to (default: "localhost")
- `-db` - Path to beads database (optional, will auto-detect)
- `-socket` - Path to daemon socket (optional, will auto-detect)
## API Endpoints
The monitor exposes several HTTP endpoints:
### Web UI
- `GET /` - Main HTML interface
- `GET /static/*` - Static assets (CSS, JavaScript)
### REST API
- `GET /api/issues` - List all issues as JSON
- `GET /api/issues/:id` - Get specific issue details
- `GET /api/ready` - Get ready work (no blockers)
- `GET /api/stats` - Get issue statistics
### WebSocket
- `WS /ws` - WebSocket endpoint for real-time updates
## Features
### Real-time Updates
The monitor polls the daemon every 2 seconds for mutation events and broadcasts them to all connected WebSocket clients. This provides instant updates when issues are created, modified, or closed.
### Responsive Design
- **Desktop**: Full table view with sortable columns
- **Mobile**: Card-based view optimized for small screens
- **Tablet**: Adapts to medium screen sizes
### Filtering
- **Status Filter**: Multi-select for Open, In Progress, and Closed
- **Priority Filter**: Single-select for P1, P2, P3, or All
### Statistics
Real-time statistics showing:
- Total issues
- In-progress issues
- Open issues
- Closed issues
## Development
### Project Structure
```
monitor-webui/
├── main.go # Main application with HTTP server and RPC client
├── go.mod # Go module dependencies
├── go.sum # (generated) Dependency checksums
├── README.md # This file
└── web/ # Web assets (embedded in binary)
├── index.html # Main HTML page
└── static/
├── css/
│ └── styles.css # Custom styles
└── js/
└── app.js # JavaScript application logic
```
### Modifying the Web Assets
The HTML, CSS, and JavaScript files are embedded into the binary using Go's `embed` package. After making changes to files in the `web/` directory, rebuild the binary to see your changes.
### Extending the API
To add new API endpoints:
1. Define a new handler function in `main.go`
2. Register it with `http.HandleFunc()` in the `main()` function
3. Use `daemonClient` to make RPC calls to the daemon
4. Return JSON responses using `json.NewEncoder(w).Encode()`
## Deployment
### As a Standalone Service
You can run the monitor as a systemd service. Example service file:
```ini
[Unit]
Description=Beads Monitor WebUI
After=network.target
[Service]
Type=simple
User=youruser
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/monitor-webui -host 0.0.0.0 -port 8080
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
```
Save as `/etc/systemd/system/beads-monitor.service` and enable:
```bash
sudo systemctl enable beads-monitor
sudo systemctl start beads-monitor
```
### Behind a Reverse Proxy
Example nginx configuration:
```nginx
server {
listen 80;
server_name monitor.example.com;
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
## Troubleshooting
### "No beads database found"
Make sure you've initialized a beads database with `bd init` or specify the database path with `-db`.
### "Daemon is not running"
The monitor requires the daemon to avoid SQLite locking conflicts. Start the daemon first:
```bash
bd daemon
```
### WebSocket disconnects frequently
Check if there's a reverse proxy or firewall between the client and server that might be closing idle connections. Consider adjusting timeout settings.
### Port already in use
If port 8080 is already in use, specify a different port:
```bash
./monitor-webui -port 3001
```
## Security Considerations
### Production Deployment
When deploying to production:
1. **Restrict Origins**: Update the `CheckOrigin` function in `main.go` to validate WebSocket origins
2. **Use HTTPS**: Deploy behind a reverse proxy with TLS (nginx, Caddy, etc.)
3. **Authentication**: Add authentication middleware if exposing publicly
4. **Firewall**: Use firewall rules to restrict access to trusted networks
### Current Security Model
The current implementation:
- Allows WebSocket connections from any origin
- Provides read-only access to issue data
- Does not include authentication
- Connects to local daemon socket only
This is appropriate for local development but requires additional security measures for production use.
## License
Same as the main beads project.

View File

@@ -0,0 +1,35 @@
module github.com/steveyegge/beads/examples/monitor-webui
go 1.24.0
require (
github.com/gorilla/websocket v1.5.3
github.com/steveyegge/beads v0.0.0
)
require (
github.com/anthropics/anthropic-sdk-go v1.16.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/ncruces/go-sqlite3 v0.29.1 // indirect
github.com/ncruces/julianday v1.0.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/spf13/viper v1.21.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tetratelabs/wazero v1.9.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.29.0 // indirect
golang.org/x/sys v0.36.0 // indirect
golang.org/x/text v0.29.0 // indirect
)
replace github.com/steveyegge/beads => ../..

View File

@@ -0,0 +1,69 @@
github.com/anthropics/anthropic-sdk-go v1.16.0 h1:nRkOFDqYXsHteoIhjdJr/5dsiKbFF3rflSv8ax50y8o=
github.com/anthropics/anthropic-sdk-go v1.16.0/go.mod h1:WTz31rIUHUHqai2UslPpw5CwXrQP3geYBioRV4WOLvE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/ncruces/go-sqlite3 v0.29.1 h1:NIi8AISWBToRHyoz01FXiTNvU147Tqdibgj2tFzJCqM=
github.com/ncruces/go-sqlite3 v0.29.1/go.mod h1:PpccBNNhvjwUOwDQEn2gXQPFPTWdlromj0+fSkd5KSg=
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,382 @@
package main
import (
"embed"
"encoding/json"
"flag"
"fmt"
"io/fs"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/rpc"
"github.com/steveyegge/beads/internal/types"
)
//go:embed web
var webFiles embed.FS
var (
// Command-line flags
port = flag.Int("port", 8080, "Port for web server")
host = flag.String("host", "localhost", "Host to bind to")
dbPath = flag.String("db", "", "Path to beads database (optional, will auto-detect)")
socketPath = flag.String("socket", "", "Path to daemon socket (optional, will auto-detect)")
// WebSocket upgrader
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
// Allow all origins for simplicity (consider restricting in production)
return true
},
}
// WebSocket client management
wsClients = make(map[*websocket.Conn]bool)
wsClientsMu sync.Mutex
wsBroadcast = make(chan []byte, 256)
// RPC client for daemon communication
daemonClient *rpc.Client
)
func main() {
flag.Parse()
// Find database path if not specified
dbPathResolved := *dbPath
if dbPathResolved == "" {
if foundDB := beads.FindDatabasePath(); foundDB != "" {
dbPathResolved = foundDB
} else {
fmt.Fprintf(os.Stderr, "Error: no beads database found\n")
fmt.Fprintf(os.Stderr, "Hint: run 'bd init' to create a database in the current directory\n")
fmt.Fprintf(os.Stderr, "Or specify database path with -db flag\n")
os.Exit(1)
}
}
// Resolve socket path
socketPathResolved := *socketPath
if socketPathResolved == "" {
socketPathResolved = getSocketPath(dbPathResolved)
}
// Connect to daemon
if err := connectToDaemon(socketPathResolved, dbPathResolved); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Start WebSocket broadcaster
go handleWebSocketBroadcast()
// Start mutation polling
go pollMutations()
// Set up HTTP routes
http.HandleFunc("/", handleIndex)
http.HandleFunc("/api/issues", handleAPIIssues)
http.HandleFunc("/api/issues/", handleAPIIssueDetail)
http.HandleFunc("/api/ready", handleAPIReady)
http.HandleFunc("/api/stats", handleAPIStats)
http.HandleFunc("/ws", handleWebSocket)
// Serve static files
webFS, err := fs.Sub(webFiles, "web")
if err != nil {
fmt.Fprintf(os.Stderr, "Error accessing web files: %v\n", err)
os.Exit(1)
}
http.Handle("/static/", http.StripPrefix("/", http.FileServer(http.FS(webFS))))
addr := fmt.Sprintf("%s:%d", *host, *port)
fmt.Printf("🖥️ bd monitor-webui starting on http://%s\n", addr)
fmt.Printf("📊 Open your browser to view real-time issue tracking\n")
fmt.Printf("🔌 WebSocket endpoint available at ws://%s/ws\n", addr)
fmt.Printf("Press Ctrl+C to stop\n\n")
if err := http.ListenAndServe(addr, nil); err != nil {
fmt.Fprintf(os.Stderr, "Error starting server: %v\n", err)
os.Exit(1)
}
}
// getSocketPath returns the Unix socket path for the daemon
func getSocketPath(dbPath string) string {
// Use the database directory to determine socket path
dbDir := filepath.Dir(dbPath)
dbName := filepath.Base(dbPath)
socketName := dbName + ".sock"
return filepath.Join(dbDir, ".beads", socketName)
}
// connectToDaemon establishes connection to the daemon
func connectToDaemon(socketPath, dbPath string) error {
client, err := rpc.TryConnect(socketPath)
if err != nil || client == nil {
return fmt.Errorf("bd monitor-webui requires the daemon to be running\n\n"+
"The monitor uses the daemon's RPC interface to avoid database locking conflicts.\n"+
"Please start the daemon first:\n\n"+
" bd daemon\n\n"+
"Then start the monitor:\n\n"+
" %s\n", os.Args[0])
}
// Check daemon health
health, err := client.Health()
if err != nil || health.Status != "healthy" {
_ = client.Close()
if err != nil {
return fmt.Errorf("daemon health check failed: %v", err)
}
errMsg := fmt.Sprintf("daemon is not healthy (status: %s)", health.Status)
if health.Error != "" {
errMsg += fmt.Sprintf("\nError: %s", health.Error)
}
return fmt.Errorf("%s\n\nTry restarting the daemon:\n bd daemon --stop\n bd daemon", errMsg)
}
// Set database path
absDBPath, _ := filepath.Abs(dbPath)
client.SetDatabasePath(absDBPath)
daemonClient = client
fmt.Printf("✓ Connected to daemon (version %s)\n", health.Version)
return nil
}
// handleIndex serves the main HTML page
func handleIndex(w http.ResponseWriter, r *http.Request) {
// Only serve index for root path
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
webFS, err := fs.Sub(webFiles, "web")
if err != nil {
http.Error(w, "Error accessing web files", http.StatusInternalServerError)
return
}
data, err := fs.ReadFile(webFS, "index.html")
if err != nil {
http.Error(w, "Error reading index.html", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(data)
}
// handleAPIIssues returns all issues as JSON
func handleAPIIssues(w http.ResponseWriter, r *http.Request) {
var issues []*types.Issue
if daemonClient == nil {
http.Error(w, "Daemon client not initialized", http.StatusInternalServerError)
return
}
// Use RPC to get issues from daemon
resp, err := daemonClient.List(&rpc.ListArgs{})
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching issues via RPC: %v", err), http.StatusInternalServerError)
return
}
if err := json.Unmarshal(resp.Data, &issues); err != nil {
http.Error(w, fmt.Sprintf("Error unmarshaling issues: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(issues)
}
// handleAPIIssueDetail returns a single issue's details
func handleAPIIssueDetail(w http.ResponseWriter, r *http.Request) {
// Extract issue ID from URL path (e.g., /api/issues/bd-1)
issueID := r.URL.Path[len("/api/issues/"):]
if issueID == "" {
http.Error(w, "Issue ID required", http.StatusBadRequest)
return
}
if daemonClient == nil {
http.Error(w, "Daemon client not initialized", http.StatusInternalServerError)
return
}
var issue *types.Issue
// Use RPC to get issue from daemon
resp, err := daemonClient.Show(&rpc.ShowArgs{ID: issueID})
if err != nil {
http.Error(w, fmt.Sprintf("Issue not found: %v", err), http.StatusNotFound)
return
}
if err := json.Unmarshal(resp.Data, &issue); err != nil {
http.Error(w, fmt.Sprintf("Error unmarshaling issue: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(issue)
}
// handleAPIReady returns ready work (no blockers)
func handleAPIReady(w http.ResponseWriter, r *http.Request) {
var issues []*types.Issue
if daemonClient == nil {
http.Error(w, "Daemon client not initialized", http.StatusInternalServerError)
return
}
// Use RPC to get ready work from daemon
resp, err := daemonClient.Ready(&rpc.ReadyArgs{})
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching ready work via RPC: %v", err), http.StatusInternalServerError)
return
}
if err := json.Unmarshal(resp.Data, &issues); err != nil {
http.Error(w, fmt.Sprintf("Error unmarshaling issues: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(issues)
}
// handleAPIStats returns issue statistics
func handleAPIStats(w http.ResponseWriter, r *http.Request) {
var stats *types.Statistics
if daemonClient == nil {
http.Error(w, "Daemon client not initialized", http.StatusInternalServerError)
return
}
// Use RPC to get stats from daemon
resp, err := daemonClient.Stats()
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching statistics via RPC: %v", err), http.StatusInternalServerError)
return
}
if err := json.Unmarshal(resp.Data, &stats); err != nil {
http.Error(w, fmt.Sprintf("Error unmarshaling statistics: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(stats)
}
// handleWebSocket upgrades HTTP connection to WebSocket and manages client lifecycle
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
// Upgrade connection to WebSocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Error upgrading to WebSocket: %v\n", err)
return
}
// Register client
wsClientsMu.Lock()
wsClients[conn] = true
wsClientsMu.Unlock()
fmt.Printf("WebSocket client connected (total: %d)\n", len(wsClients))
// Handle client disconnection
defer func() {
wsClientsMu.Lock()
delete(wsClients, conn)
wsClientsMu.Unlock()
conn.Close()
fmt.Printf("WebSocket client disconnected (total: %d)\n", len(wsClients))
}()
// Keep connection alive and handle client messages
for {
_, _, err := conn.ReadMessage()
if err != nil {
break
}
}
}
// handleWebSocketBroadcast sends messages to all connected WebSocket clients
func handleWebSocketBroadcast() {
for {
// Wait for message to broadcast
message := <-wsBroadcast
// Send to all connected clients
wsClientsMu.Lock()
for client := range wsClients {
err := client.WriteMessage(websocket.TextMessage, message)
if err != nil {
// Client disconnected, will be cleaned up by handleWebSocket
fmt.Fprintf(os.Stderr, "Error writing to WebSocket client: %v\n", err)
client.Close()
delete(wsClients, client)
}
}
wsClientsMu.Unlock()
}
}
// pollMutations polls the daemon for mutations and broadcasts them to WebSocket clients
func pollMutations() {
lastPollTime := int64(0) // Start from beginning
ticker := time.NewTicker(2 * time.Second) // Poll every 2 seconds
defer ticker.Stop()
for range ticker.C {
if daemonClient == nil {
continue
}
// Call GetMutations RPC
resp, err := daemonClient.GetMutations(&rpc.GetMutationsArgs{
Since: lastPollTime,
})
if err != nil {
// Daemon might be down or restarting, just skip this poll
continue
}
var mutations []rpc.MutationEvent
if err := json.Unmarshal(resp.Data, &mutations); err != nil {
fmt.Fprintf(os.Stderr, "Error unmarshaling mutations: %v\n", err)
continue
}
// Broadcast each mutation to WebSocket clients
for _, mutation := range mutations {
data, _ := json.Marshal(mutation)
wsBroadcast <- data
// Update last poll time to this mutation's timestamp
mutationTimeMillis := mutation.Timestamp.UnixMilli()
if mutationTimeMillis > lastPollTime {
lastPollTime = mutationTimeMillis
}
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,108 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>bd monitor - Issue Tracker</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.min.css">
<link rel="stylesheet" href="/static/css/styles.css">
</head>
<body>
<div class="loading-overlay" id="loading-overlay">
<div class="spinner"></div>
</div>
<div class="header">
<div>
<h1>bd monitor</h1>
<p>Real-time issue tracking dashboard</p>
</div>
<div class="connection-status disconnected" id="connection-status">
<span class="connection-dot disconnected" id="connection-dot"></span>
<span id="connection-text">Connecting...</span>
</div>
</div>
<div class="error-message" id="error-message"></div>
<div class="stats">
<h2>Statistics</h2>
<div class="stats-grid" id="stats-grid">
<div class="stat-card">
<div class="stat-value" id="stat-total">-</div>
<div class="stat-label">Total Issues</div>
</div>
<div class="stat-card">
<div class="stat-value" id="stat-in-progress">-</div>
<div class="stat-label">In Progress</div>
</div>
<div class="stat-card">
<div class="stat-value" id="stat-open">-</div>
<div class="stat-label">Open</div>
</div>
<div class="stat-card">
<div class="stat-value" id="stat-closed">-</div>
<div class="stat-label">Closed</div>
</div>
</div>
</div>
<div class="filter-controls">
<label>
Status (multi-select):
<select id="filter-status" multiple>
<option value="open" selected>Open</option>
<option value="in-progress">In Progress</option>
<option value="closed">Closed</option>
</select>
</label>
<label>
Priority:
<select id="filter-priority">
<option value="">All</option>
<option value="1">P1</option>
<option value="2">P2</option>
<option value="3">P3</option>
</select>
</label>
<button class="reload-button" id="reload-button" title="Reload all data">
🔄 Reload
</button>
</div>
<h2>Issues</h2>
<table id="issues-table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Priority</th>
<th>Type</th>
<th>Assignee</th>
</tr>
</thead>
<tbody id="issues-tbody">
<tr><td colspan="6"><div class="spinner"></div></td></tr>
</tbody>
</table>
<!-- Mobile card view -->
<div class="issues-card-view" id="issues-card-view">
<div class="spinner"></div>
</div>
<!-- Modal for issue details -->
<div id="issue-modal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2 id="modal-title">Issue Details</h2>
<div id="modal-body">
<p>Loading...</p>
</div>
</div>
</div>
<script src="/static/js/app.js"></script>
</body>
</html>

View File

@@ -0,0 +1,222 @@
body { padding: 2rem; }
.header {
margin-bottom: 2rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.connection-status {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border-radius: 0.4rem;
font-size: 1.2rem;
}
.connection-status.connected {
background: #d4edda;
color: #155724;
}
.connection-status.disconnected {
background: #f8d7da;
color: #721c24;
}
.connection-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.connection-dot.connected {
background: #28a745;
animation: pulse 2s infinite;
}
.connection-dot.disconnected {
background: #dc3545;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.stats { margin-bottom: 2rem; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; }
.stat-card { padding: 1rem; background: #f4f5f6; border-radius: 0.4rem; }
.stat-value { font-size: 2.4rem; font-weight: bold; color: #9b4dca; }
.stat-label { font-size: 1.2rem; color: #606c76; }
/* Loading spinner */
.spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #9b4dca;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 2rem auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.8);
z-index: 999;
justify-content: center;
align-items: center;
}
.loading-overlay.active {
display: flex;
}
/* Error message */
.error-message {
display: none;
padding: 1rem;
margin: 1rem 0;
background: #f8d7da;
border: 1px solid #f5c6cb;
border-radius: 0.4rem;
color: #721c24;
}
.error-message.active {
display: block;
}
/* Empty state */
.empty-state {
text-align: center;
padding: 4rem 2rem;
color: #606c76;
}
.empty-state-icon {
font-size: 4rem;
margin-bottom: 1rem;
}
/* Table styles */
table { width: 100%; }
tbody tr { cursor: pointer; }
tbody tr:hover { background: #f4f5f6; }
.status-open { color: #0074d9; }
.status-closed { color: #2ecc40; }
.status-in-progress { color: #ff851b; }
.priority-1 { color: #ff4136; font-weight: bold; }
.priority-2 { color: #ff851b; }
.priority-3 { color: #ffdc00; }
/* Modal styles */
.modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); }
.modal-content { background-color: #fefefe; margin: 5% auto; padding: 2rem; border-radius: 0.4rem; width: 80%; max-width: 800px; }
.close { color: #aaa; float: right; font-size: 2.8rem; font-weight: bold; line-height: 2rem; cursor: pointer; }
.close:hover, .close:focus { color: #000; }
.filter-controls {
margin-bottom: 2rem;
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: flex-end;
}
.filter-controls label {
flex: 0 0 auto;
}
.filter-controls select { margin-right: 0; }
.filter-controls select[multiple] {
height: auto;
min-height: 100px;
}
.reload-button {
padding: 0.6rem 1.2rem;
background: #9b4dca;
color: white;
border: none;
border-radius: 0.4rem;
cursor: pointer;
font-size: 1.4rem;
transition: background 0.2s;
}
.reload-button:hover {
background: #8b3dba;
}
.reload-button:active {
transform: translateY(1px);
}
/* Responsive design for mobile */
@media screen and (max-width: 768px) {
body { padding: 1rem; }
.header {
flex-direction: column;
align-items: flex-start;
}
.connection-status {
margin-top: 1rem;
}
.stats-grid {
grid-template-columns: repeat(2, 1fr);
}
.filter-controls {
flex-direction: column;
align-items: stretch;
}
.filter-controls label {
width: 100%;
}
.filter-controls select {
width: 100%;
}
.reload-button {
width: 100%;
}
/* Hide table, show card view on mobile */
table { display: none; }
.issues-card-view { display: block; }
.issue-card {
background: #fff;
border: 1px solid #d1d1d1;
border-radius: 0.4rem;
padding: 1.5rem;
margin-bottom: 1rem;
cursor: pointer;
transition: box-shadow 0.2s;
}
.issue-card:hover {
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.issue-card-header {
display: flex;
justify-content: space-between;
align-items: start;
margin-bottom: 1rem;
}
.issue-card-id {
font-weight: bold;
color: #9b4dca;
}
.issue-card-title {
font-size: 1.6rem;
margin: 0.5rem 0;
}
.issue-card-meta {
display: flex;
flex-wrap: wrap;
gap: 1rem;
font-size: 1.2rem;
}
.modal-content {
width: 95%;
margin: 10% auto;
}
}
@media screen and (min-width: 769px) {
.issues-card-view { display: none; }
}

View File

@@ -0,0 +1,248 @@
let allIssues = [];
let ws = null;
let wsConnected = false;
// WebSocket connection
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = protocol + '//' + window.location.host + '/ws';
ws = new WebSocket(wsUrl);
ws.onopen = function() {
console.log('WebSocket connected');
wsConnected = true;
updateConnectionStatus(true);
};
ws.onmessage = function(event) {
console.log('WebSocket message:', event.data);
const mutation = JSON.parse(event.data);
handleMutation(mutation);
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
wsConnected = false;
updateConnectionStatus(false);
};
ws.onclose = function() {
console.log('WebSocket disconnected');
wsConnected = false;
updateConnectionStatus(false);
// Reconnect after 5 seconds
setTimeout(connectWebSocket, 5000);
};
}
// Update connection status indicator
function updateConnectionStatus(connected) {
const statusEl = document.getElementById('connection-status');
const dotEl = document.getElementById('connection-dot');
const textEl = document.getElementById('connection-text');
if (connected) {
statusEl.className = 'connection-status connected';
dotEl.className = 'connection-dot connected';
textEl.textContent = 'Connected';
} else {
statusEl.className = 'connection-status disconnected';
dotEl.className = 'connection-dot disconnected';
textEl.textContent = 'Disconnected';
}
}
// Show/hide loading overlay
function setLoading(isLoading) {
const overlay = document.getElementById('loading-overlay');
if (isLoading) {
overlay.classList.add('active');
} else {
overlay.classList.remove('active');
}
}
// Show error message
function showError(message) {
const errorEl = document.getElementById('error-message');
errorEl.textContent = message;
errorEl.classList.add('active');
setTimeout(() => {
errorEl.classList.remove('active');
}, 5000);
}
// Handle mutation event
function handleMutation(mutation) {
console.log('Mutation:', mutation.type, mutation.issue_id);
// Refresh data on mutation
loadStats();
loadIssues();
}
// Load statistics
async function loadStats() {
try {
const response = await fetch('/api/stats');
if (!response.ok) throw new Error('Failed to load statistics');
const stats = await response.json();
document.getElementById('stat-total').textContent = stats.total_issues || 0;
document.getElementById('stat-in-progress').textContent = stats.in_progress_issues || 0;
document.getElementById('stat-open').textContent = stats.open_issues || 0;
document.getElementById('stat-closed').textContent = stats.closed_issues || 0;
} catch (error) {
console.error('Error loading statistics:', error);
showError('Failed to load statistics: ' + error.message);
}
}
// Load all issues
async function loadIssues() {
try {
const response = await fetch('/api/issues');
if (!response.ok) throw new Error('Failed to load issues');
allIssues = await response.json();
renderIssues(allIssues);
} catch (error) {
console.error('Error loading issues:', error);
showError('Failed to load issues: ' + error.message);
document.getElementById('issues-tbody').innerHTML = '<tr><td colspan="6" style="text-align: center; color: #721c24;">Error loading issues</td></tr>';
document.getElementById('issues-card-view').innerHTML = '<div class="empty-state"><div class="empty-state-icon">⚠️</div><p>Error loading issues</p></div>';
}
}
// Render issues table
function renderIssues(issues) {
const tbody = document.getElementById('issues-tbody');
const cardView = document.getElementById('issues-card-view');
if (!issues || issues.length === 0) {
const emptyState = '<div class="empty-state"><div class="empty-state-icon">📋</div><h3>No issues found</h3><p>Create your first issue to get started!</p></div>';
tbody.innerHTML = '<tr><td colspan="6">' + emptyState + '</td></tr>';
cardView.innerHTML = emptyState;
return;
}
// Render table view
tbody.innerHTML = issues.map(issue => {
const statusClass = 'status-' + (issue.status || 'open').toLowerCase().replace('_', '-');
const priorityClass = 'priority-' + (issue.priority || 2);
return '<tr onclick="showIssueDetail(\'' + issue.id + '\')"><td>' + issue.id + '</td><td>' + issue.title + '</td><td class="' + statusClass + '">' + (issue.status || 'open') + '</td><td class="' + priorityClass + '">P' + (issue.priority || 2) + '</td><td>' + (issue.issue_type || 'task') + '</td><td>' + (issue.assignee || '-') + '</td></tr>';
}).join('');
// Render card view for mobile
cardView.innerHTML = issues.map(issue => {
const statusClass = 'status-' + (issue.status || 'open').toLowerCase().replace('_', '-');
const priorityClass = 'priority-' + (issue.priority || 2);
let html = '<div class="issue-card" onclick="showIssueDetail(\'' + issue.id + '\')">';
html += '<div class="issue-card-header">';
html += '<span class="issue-card-id">' + issue.id + '</span>';
html += '<span class="' + priorityClass + '">P' + (issue.priority || 2) + '</span>';
html += '</div>';
html += '<h3 class="issue-card-title">' + issue.title + '</h3>';
html += '<div class="issue-card-meta">';
html += '<span class="' + statusClass + '">● ' + (issue.status || 'open') + '</span>';
html += '<span>Type: ' + (issue.issue_type || 'task') + '</span>';
if (issue.assignee) html += '<span>👤 ' + issue.assignee + '</span>';
html += '</div>';
html += '</div>';
return html;
}).join('');
}
// Filter issues
function filterIssues() {
const statusSelect = document.getElementById('filter-status');
const selectedStatuses = Array.from(statusSelect.selectedOptions).map(opt => opt.value);
const priorityFilter = document.getElementById('filter-priority').value;
const filtered = allIssues.filter(issue => {
// If statuses are selected, check if issue status is in the selected list
if (selectedStatuses.length > 0 && !selectedStatuses.includes(issue.status)) return false;
if (priorityFilter && issue.priority !== parseInt(priorityFilter)) return false;
return true;
});
renderIssues(filtered);
}
// Reload all data
function reloadData() {
setLoading(true);
Promise.all([loadStats(), loadIssues()])
.then(() => {
setLoading(false);
})
.catch(error => {
console.error('Error reloading data:', error);
setLoading(false);
showError('Failed to reload data: ' + error.message);
});
}
// Show issue detail modal
async function showIssueDetail(issueId) {
const modal = document.getElementById('issue-modal');
const modalTitle = document.getElementById('modal-title');
const modalBody = document.getElementById('modal-body');
modal.style.display = 'block';
modalTitle.textContent = 'Loading...';
modalBody.innerHTML = '<div class="spinner"></div>';
try {
const response = await fetch('/api/issues/' + issueId);
if (!response.ok) throw new Error('Issue not found');
const issue = await response.json();
modalTitle.textContent = issue.id + ': ' + issue.title;
let html = '<p><strong>Status:</strong> ' + issue.status + '</p>';
html += '<p><strong>Priority:</strong> P' + issue.priority + '</p>';
html += '<p><strong>Type:</strong> ' + issue.issue_type + '</p>';
html += '<p><strong>Assignee:</strong> ' + (issue.assignee || 'Unassigned') + '</p>';
html += '<p><strong>Created:</strong> ' + new Date(issue.created_at).toLocaleString() + '</p>';
html += '<p><strong>Updated:</strong> ' + new Date(issue.updated_at).toLocaleString() + '</p>';
if (issue.description) html += '<h3>Description</h3><pre>' + issue.description + '</pre>';
if (issue.design) html += '<h3>Design</h3><pre>' + issue.design + '</pre>';
if (issue.notes) html += '<h3>Notes</h3><pre>' + issue.notes + '</pre>';
if (issue.labels && issue.labels.length > 0) html += '<p><strong>Labels:</strong> ' + issue.labels.join(', ') + '</p>';
modalBody.innerHTML = html;
} catch (error) {
console.error('Error loading issue details:', error);
showError('Failed to load issue details: ' + error.message);
modalBody.innerHTML = '<div class="empty-state"><div class="empty-state-icon">⚠️</div><p>Error loading issue details</p></div>';
}
}
// Close modal
document.querySelector('.close').onclick = function() {
document.getElementById('issue-modal').style.display = 'none';
};
window.onclick = function(event) {
const modal = document.getElementById('issue-modal');
if (event.target == modal) {
modal.style.display = 'none';
}
};
// Filter event listeners
document.getElementById('filter-status').addEventListener('change', filterIssues);
document.getElementById('filter-priority').addEventListener('change', filterIssues);
// Reload button listener
document.getElementById('reload-button').addEventListener('click', reloadData);
// Initial load
connectWebSocket();
loadStats();
loadIssues();
// Fallback: Refresh every 30 seconds (WebSocket should handle real-time updates)
setInterval(() => {
if (!wsConnected) {
loadStats();
loadIssues();
}
}, 30000);