Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(scheduler): Phase 2 & 3 — observability, batch submission, config hot-reload

Yash Jadhav203197fe55d9
diff --git a/docs/architecture/scheduler.md b/docs/architecture/scheduler.md
index b647caf6..c64454a0 100644
--- a/docs/architecture/scheduler.md
+++ b/docs/architecture/scheduler.md
@@ -22,6 +22,8 @@ In dashboard mode, the scheduler is created only when `scheduler.enabled` is tru
- `GET /tasks`
- `GET /tasks/{id}`
- `POST /tasks/{id}/cancel`
+- `GET /scheduler/stats`
+- `POST /tasks/batch`
## High-Level Flow
@@ -182,3 +184,77 @@ That means it does not currently provide:
- persistent queue storage
- durable recovery after process restart
- a separate task execution DSL
+
+---
+
+## Phase 2 -- Observability Layer
+
+### Metrics
+
+The scheduler maintains global and per-agent counters via the `Metrics` struct. Global counters use `atomic.Uint64` for lock-free increments. Per-agent counters use a sharded mutex pattern (`agentMetricEntry`) to avoid global lock contention.
+
+Tracked counters:
+
+- `TasksSubmitted`, `TasksCompleted`, `TasksFailed`
+- `TasksCancelled`, `TasksRejected`, `TasksExpired`
+- `DispatchTotal` and cumulative `DispatchLatency` (for average dispatch latency calculation)
+
+`Metrics.Snapshot()` returns a `MetricsSnapshot` -- a point-in-time serializable copy that includes per-agent breakdowns.
+
+### Stats Endpoint
+
+`GET /scheduler/stats` exposes three sections:
+
+- **queue** -- current queued/inflight counts from `QueueStats()`
+- **metrics** -- snapshot from `Metrics.Snapshot()`
+- **config** -- current scheduler configuration values
+
+### Lifecycle Logging
+
+Key scheduler events are logged via `slog`:
+
+- task submission, dispatch, completion, failure, cancellation
+- queue admission rejections
+- config reload events
+- webhook delivery outcomes
+
+### Webhook Delivery
+
+When a task has a `callbackUrl` and reaches a terminal state, the scheduler sends a POST with the task snapshot as JSON. This runs asynchronously in a goroutine from `finishTask()`.
+
+Security constraints:
+
+- only `http` and `https` schemes are accepted (SSRF mitigation)
+- a dedicated `http.Client` with a 10-second timeout prevents hanging connections
+- delivery failures are logged but do not affect task state
+
+Custom headers are sent: `X-PinchTab-Event: task.completed` and `X-PinchTab-Task-ID`.
+
+---
+
+## Phase 3 -- Hardening Layer
+
+### Batch Submission
+
+`POST /tasks/batch` accepts an array of task definitions (up to 50) sharing a single `agentId` and optional `callbackUrl`. Each task is submitted individually through `Submit()`, so queue admission limits apply per-task.
+
+The batch endpoint supports partial failure: if some tasks are rejected (queue full), the accepted tasks are still submitted and the response includes per-task status.
+
+### Config Hot-Reload
+
+`ReloadConfig(cfg Config)` updates tuning knobs at runtime:
+
+- queue limits via `queue.SetLimits(maxQueue, maxPerAgent)`
+- inflight limits via `cfgMu`-protected config fields
+- result TTL via `results.SetTTL(ttl)`
+
+Zero values in the reload config are ignored, preserving the existing setting.
+
+`ConfigWatcher` is a background goroutine that periodically calls a user-supplied `loadFn() (Config, error)` and applies changes via `ReloadConfig`. It can be started and stopped cleanly.
+
+### SetLimits and SetTTL
+
+The queue and result store expose safe runtime mutators:
+
+- `TaskQueue.SetLimits(maxQueue, maxPerAgent)` -- atomically updates admission thresholds
+- `ResultStore.SetTTL(ttl)` -- updates the eviction window for terminal task snapshots
diff --git a/docs/reference/scheduler.md b/docs/reference/scheduler.md
index 490abff2..3a151d12 100644
--- a/docs/reference/scheduler.md
+++ b/docs/reference/scheduler.md
@@ -68,6 +68,7 @@ Tasks are scheduler-owned records with these main fields:
| `result` | executor response payload |
| `error` | terminal error message |
| `position` | queue position at submission time |
+| `callbackUrl` | optional webhook URL for terminal state notification |
Task IDs are currently generated as `tsk_XXXXXXXX`, but callers should still treat them as opaque IDs.
@@ -106,6 +107,7 @@ Request fields:
| `params` | no | action-specific fields merged into the executor request body |
| `priority` | no | lower number means higher priority |
| `deadline` | no | RFC3339 timestamp; defaults to `now + 60s` |
+| `callbackUrl` | no | webhook URL; receives POST with task snapshot on terminal state |
Important:
@@ -283,4 +285,171 @@ In practice, task payloads should use the same action fields that the immediate
- equal-priority tasks for the same agent fall back to FIFO order
- across agents, the scheduler prefers the agent with the fewest in-flight tasks
- if a queued task passes its deadline before execution starts, it is marked failed with `deadline exceeded while queued`
-- terminal task snapshots are retained in memory for `resultTTLSec`
\ No newline at end of file
+- terminal task snapshots are retained in memory for `resultTTLSec`
+
+---
+
+## Phase 2 -- Observability
+
+### Scheduler Stats
+
+`GET /scheduler/stats` returns a snapshot of queue state, runtime metrics, and configuration.
+
+```bash
+curl http://localhost:9867/scheduler/stats
+# Response
+{
+ "queue": {
+ "totalQueued": 5,
+ "totalInflight": 2,
+ "agentCounts": {
+ "agent-crawl-01": 3,
+ "agent-scrape-02": 2
+ }
+ },
+ "metrics": {
+ "tasksSubmitted": 42,
+ "tasksCompleted": 35,
+ "tasksFailed": 3,
+ "tasksCancelled": 2,
+ "tasksRejected": 1,
+ "tasksExpired": 1,
+ "dispatchCount": 38,
+ "avgDispatchLatencyMs": 12.5,
+ "agents": {
+ "agent-crawl-01": {
+ "submitted": 25,
+ "completed": 22,
+ "failed": 2,
+ "cancelled": 1,
+ "rejected": 0
+ }
+ }
+ },
+ "config": {
+ "strategy": "fair-fifo",
+ "maxQueueSize": 1000,
+ "maxPerAgent": 100,
+ "maxInflight": 20,
+ "maxPerAgentFlight": 10,
+ "workerCount": 4,
+ "resultTTL": "5m0s"
+ }
+}
+```
+
+#### Metrics Fields
+
+| Field | Type | Meaning |
+| --- | --- | --- |
+| `tasksSubmitted` | uint64 | total tasks accepted since startup |
+| `tasksCompleted` | uint64 | tasks that finished successfully |
+| `tasksFailed` | uint64 | tasks that finished with an error |
+| `tasksCancelled` | uint64 | tasks cancelled via `POST /tasks/{id}/cancel` |
+| `tasksRejected` | uint64 | tasks rejected at admission (queue full) |
+| `tasksExpired` | uint64 | queued tasks that exceeded their deadline |
+| `dispatchCount` | uint64 | number of tasks dispatched to workers |
+| `avgDispatchLatencyMs` | float64 | average time from queue entry to dispatch start |
+| `agents` | object | per-agent breakdown (submitted, completed, failed, cancelled, rejected) |
+
+### Webhook Callbacks
+
+Tasks can include a `callbackUrl` field. When the task reaches a terminal state (`done`, `failed`, or `cancelled`), the scheduler delivers a POST with the task snapshot to that URL.
+
+```bash
+curl -X POST http://localhost:9867/tasks \
+ -H "Content-Type: application/json" \
+ -d '{
+ "agentId": "my-agent",
+ "action": "click",
+ "tabId": "8f9c7d4e1234567890abcdef12345678",
+ "callbackUrl": "https://example.com/hooks/task-done"
+ }'
+```
+
+Webhook behavior:
+
+- delivery is best-effort: failures are logged but do not affect task state
+- only `http` and `https` schemes are allowed (SSRF protection)
+- a dedicated HTTP client with a 10-second timeout is used
+- custom headers are sent: `X-PinchTab-Event: task.completed` and `X-PinchTab-Task-ID: <taskId>`
+
+The `callbackUrl` field is stored on the task and returned in `GET /tasks/{id}`.
+
+---
+
+## Phase 3 -- Hardening
+
+### Batch Task Submission
+
+`POST /tasks/batch` submits multiple tasks in a single request. All tasks in the batch share the same `agentId` and optional `callbackUrl`.
+
+```bash
+curl -X POST http://localhost:9867/tasks/batch \
+ -H "Content-Type: application/json" \
+ -d '{
+ "agentId": "agent-crawl-01",
+ "callbackUrl": "https://example.com/hooks/batch",
+ "tasks": [
+ { "action": "click", "tabId": "TAB_ID", "params": { "selector": "#btn" } },
+ { "action": "scroll", "tabId": "TAB_ID", "params": { "scrollY": 400 } },
+ { "action": "hover", "tabId": "TAB_ID", "params": { "selector": "h1" }, "priority": 1 }
+ ]
+ }'
+# Response (202 Accepted)
+{
+ "tasks": [
+ { "taskId": "tsk_aaaa1111", "state": "queued", "position": 1 },
+ { "taskId": "tsk_bbbb2222", "state": "queued", "position": 2 },
+ { "taskId": "tsk_cccc3333", "state": "queued", "position": 3 }
+ ],
+ "submitted": 3
+}
+```
+
+#### Batch Request Fields
+
+| Field | Required | Notes |
+| --- | --- | --- |
+| `agentId` | yes | shared across all tasks in the batch |
+| `callbackUrl` | no | webhook URL applied to every task |
+| `tasks` | yes | array of task definitions (1–50) |
+
+Each task definition supports the same fields as a single task submit (`action`, `tabId`, `ref`, `params`, `priority`, `deadline`) except `agentId` and `callbackUrl` which are inherited from the batch.
+
+#### Batch Validation
+
+| Condition | Response |
+| --- | --- |
+| missing `agentId` | `400 Bad Request` |
+| empty `tasks` array | `400 Bad Request` |
+| more than 50 tasks | `400 Bad Request` with `batch_too_large` code |
+| invalid JSON body | `400 Bad Request` |
+
+Partial failure: if some tasks are rejected by admission (queue full), the accepted tasks are still submitted. The response includes each task's status individually.
+
+### Config Hot-Reload
+
+`ReloadConfig(cfg)` updates queue limits, inflight limits, and result TTL at runtime without restarting the scheduler.
+
+Reloadable fields:
+
+| Field | What Changes |
+| --- | --- |
+| `maxQueueSize`, `maxPerAgent` | queue admission limits via `SetLimits()` |
+| `maxInflight`, `maxPerAgentFlight` | concurrency limits (protected by `cfgMu`) |
+| `resultTTL` | result store eviction window via `SetTTL()` |
+
+Zero values are ignored (the existing setting is preserved).
+
+#### ConfigWatcher
+
+`ConfigWatcher` runs a background goroutine that periodically re-reads the config and calls `ReloadConfig`. Create with:
+
+```go
+cw := scheduler.NewConfigWatcher(30*time.Second, loadFn, sched)
+cw.Start()
+defer cw.Stop()
+```
+
+`loadFn` is a `func() (Config, error)` that reads the current config from disk or environment.
\ No newline at end of file
diff --git a/internal/scheduler/batch.go b/internal/scheduler/batch.go
new file mode 100644
index 00000000..1fbdbd3e
--- /dev/null
+++ b/internal/scheduler/batch.go
@@ -0,0 +1,102 @@
+package scheduler
+
+import (
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+const maxBatchSize = 50
+
+var (
+ errMissingAgentID = errors.New("missing required field 'agentId'")
+ errEmptyBatch = errors.New("batch must contain at least one task")
+)
+
+// BatchRequest is the JSON body for POST /tasks/batch.
+type BatchRequest struct {
+ AgentID string `json:"agentId"`
+ CallbackURL string `json:"callbackUrl,omitempty"`
+ Tasks []BatchTaskDef `json:"tasks"`
+}
+
+// BatchTaskDef defines a single task inside a batch.
+type BatchTaskDef struct {
+ Action string `json:"action"`
+ TabID string `json:"tabId,omitempty"`
+ Ref string `json:"ref,omitempty"`
+ Params map[string]any `json:"params,omitempty"`
+ Priority int `json:"priority,omitempty"`
+ Deadline string `json:"deadline,omitempty"`
+}
+
+// BatchResponseItem is the result for each submitted task in the batch.
+type BatchResponseItem struct {
+ TaskID string `json:"taskId"`
+ State TaskState `json:"state"`
+ Position int `json:"position,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func (s *Scheduler) handleBatch(w http.ResponseWriter, r *http.Request) {
+ var req BatchRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, err)
+ return
+ }
+
+ if req.AgentID == "" {
+ web.Error(w, 400, errMissingAgentID)
+ return
+ }
+ if len(req.Tasks) == 0 {
+ web.Error(w, 400, errEmptyBatch)
+ return
+ }
+ if len(req.Tasks) > maxBatchSize {
+ web.ErrorCode(w, 400, "batch_too_large", "batch exceeds maximum size", false, map[string]any{
+ "submitted": len(req.Tasks),
+ "max": maxBatchSize,
+ })
+ return
+ }
+
+ results := make([]BatchResponseItem, 0, len(req.Tasks))
+ for _, td := range req.Tasks {
+ sr := SubmitRequest{
+ AgentID: req.AgentID,
+ Action: td.Action,
+ TabID: td.TabID,
+ Ref: td.Ref,
+ Params: td.Params,
+ Priority: td.Priority,
+ Deadline: td.Deadline,
+ CallbackURL: req.CallbackURL,
+ }
+
+ task, err := s.Submit(sr)
+ if err != nil {
+ item := BatchResponseItem{State: StateRejected, Error: err.Error()}
+ if task != nil {
+ item.TaskID = task.ID
+ }
+ results = append(results, item)
+ slog.Warn("batch: task rejected", "agent", req.AgentID, "action", td.Action, "err", err)
+ continue
+ }
+
+ results = append(results, BatchResponseItem{
+ TaskID: task.ID,
+ State: task.GetState(),
+ Position: task.Position,
+ })
+ }
+
+ web.JSON(w, 202, map[string]any{
+ "tasks": results,
+ "submitted": len(results),
+ })
+}
diff --git a/internal/scheduler/batch_test.go b/internal/scheduler/batch_test.go
new file mode 100644
index 00000000..8cbe7346
--- /dev/null
+++ b/internal/scheduler/batch_test.go
@@ -0,0 +1,232 @@
+package scheduler
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestHandleBatchSuccess(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ body := `{
+ "agentId": "a1",
+ "tasks": [
+ {"action":"click","tabId":"tab-1","ref":"e1"},
+ {"action":"navigate","tabId":"tab-1","ref":"e2","priority":5}
+ ]
+ }`
+
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 202 {
+ t.Fatalf("expected 202, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ submitted, ok := resp["submitted"].(float64)
+ if !ok || submitted != 2 {
+ t.Errorf("expected 2 submitted, got %v", resp["submitted"])
+ }
+
+ tasks, ok := resp["tasks"].([]any)
+ if !ok || len(tasks) != 2 {
+ t.Fatalf("expected 2 task results, got %v", resp["tasks"])
+ }
+
+ for i, item := range tasks {
+ m := item.(map[string]any)
+ if m["taskId"] == nil || m["taskId"] == "" {
+ t.Errorf("task[%d] missing taskId", i)
+ }
+ if m["state"] != "queued" {
+ t.Errorf("task[%d] expected queued, got %v", i, m["state"])
+ }
+ }
+}
+
+func TestHandleBatchMissingAgentID(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ body := `{"tasks":[{"action":"click","tabId":"t1"}]}`
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleBatchEmptyTasks(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ body := `{"agentId":"a1","tasks":[]}`
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleBatchTooLarge(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ // Build batch with maxBatchSize+1 tasks.
+ tasks := make([]map[string]string, maxBatchSize+1)
+ for i := range tasks {
+ tasks[i] = map[string]string{"action": "click", "tabId": "t1"}
+ }
+ reqBody := map[string]any{
+ "agentId": "a1",
+ "tasks": tasks,
+ }
+ bodyBytes, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(string(bodyBytes)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 for oversized batch, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleBatchBadJSON(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader("not json"))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleBatchWithCallbackURL(t *testing.T) {
+ _, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ body := `{
+ "agentId": "a1",
+ "callbackUrl": "http://example.com/hook",
+ "tasks": [
+ {"action":"click","tabId":"tab-1","ref":"e1"}
+ ]
+ }`
+
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 202 {
+ t.Fatalf("expected 202, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleBatchPartialFailure(t *testing.T) {
+ s, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ // Reduce per-agent limit to force rejection on second task.
+ s.queue.SetLimits(s.cfg.MaxQueueSize, 1)
+
+ body := `{
+ "agentId": "a1",
+ "tasks": [
+ {"action":"click","tabId":"tab-1","ref":"e1"},
+ {"action":"navigate","tabId":"tab-1","ref":"e2"}
+ ]
+ }`
+
+ req := httptest.NewRequest("POST", "/tasks/batch", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ // Should still return 202 since at least one task was accepted.
+ if w.Code != 202 {
+ t.Fatalf("expected 202, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ tasks := resp["tasks"].([]any)
+ if len(tasks) != 2 {
+ t.Fatalf("expected 2 results, got %d", len(tasks))
+ }
+
+ first := tasks[0].(map[string]any)
+ if first["state"] != "queued" {
+ t.Errorf("first task should be queued, got %v", first["state"])
+ }
+
+ second := tasks[1].(map[string]any)
+ if second["error"] == nil || second["error"] == "" {
+ t.Error("second task should have an error due to per-agent limit")
+ }
+}
+
+func TestHandleStats(t *testing.T) {
+ s, mux, executor := setupHandlerTest(t)
+ defer executor.Close()
+
+ // Submit a task so there's data.
+ _, _ = s.Submit(SubmitRequest{
+ AgentID: "a1",
+ Action: "click",
+ TabID: "tab-1",
+ })
+
+ req := httptest.NewRequest("GET", "/scheduler/stats", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ if resp["queue"] == nil {
+ t.Error("response should contain queue stats")
+ }
+ if resp["metrics"] == nil {
+ t.Error("response should contain metrics")
+ }
+ if resp["config"] == nil {
+ t.Error("response should contain config")
+ }
+
+ metrics := resp["metrics"].(map[string]any)
+ if metrics["tasksSubmitted"].(float64) != 1 {
+ t.Errorf("expected 1 submitted, got %v", metrics["tasksSubmitted"])
+ }
+}
diff --git a/internal/scheduler/handlers.go b/internal/scheduler/handlers.go
index 6da6232e..23dd8a6f 100644
--- a/internal/scheduler/handlers.go
+++ b/internal/scheduler/handlers.go
@@ -14,6 +14,8 @@ func (s *Scheduler) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /tasks", s.handleList)
mux.HandleFunc("GET /tasks/{id}", s.handleGet)
mux.HandleFunc("POST /tasks/{id}/cancel", s.handleCancel)
+ mux.HandleFunc("GET /scheduler/stats", s.handleStats)
+ mux.HandleFunc("POST /tasks/batch", s.handleBatch)
}
func (s *Scheduler) handleSubmit(w http.ResponseWriter, r *http.Request) {
@@ -107,3 +109,21 @@ func (s *Scheduler) handleList(w http.ResponseWriter, r *http.Request) {
}
web.JSON(w, 200, map[string]any{"tasks": tasks, "count": len(tasks)})
}
+
+func (s *Scheduler) handleStats(w http.ResponseWriter, _ *http.Request) {
+ queue := s.QueueStats()
+ metrics := s.GetMetrics()
+ web.JSON(w, 200, map[string]any{
+ "queue": queue,
+ "metrics": metrics,
+ "config": map[string]any{
+ "strategy": s.cfg.Strategy,
+ "maxQueueSize": s.cfg.MaxQueueSize,
+ "maxPerAgent": s.cfg.MaxPerAgent,
+ "maxInflight": s.cfg.MaxInflight,
+ "maxPerAgentFlight": s.cfg.MaxPerAgentFlight,
+ "workerCount": s.cfg.WorkerCount,
+ "resultTTL": s.cfg.ResultTTL.String(),
+ },
+ })
+}
diff --git a/internal/scheduler/metrics.go b/internal/scheduler/metrics.go
new file mode 100644
index 00000000..02d8c943
--- /dev/null
+++ b/internal/scheduler/metrics.go
@@ -0,0 +1,153 @@
+package scheduler
+
+import (
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// Metrics tracks scheduler-level counters and latency for observability.
+type Metrics struct {
+ TasksSubmitted atomic.Uint64
+ TasksCompleted atomic.Uint64
+ TasksFailed atomic.Uint64
+ TasksCancelled atomic.Uint64
+ TasksRejected atomic.Uint64
+ TasksExpired atomic.Uint64
+ DispatchTotal atomic.Uint64
+ DispatchLatency atomic.Uint64 // cumulative milliseconds
+
+ // Per-agent counters protected by mutex.
+ mu sync.RWMutex
+ agentStats map[string]*agentMetricEntry
+}
+
+// AgentMetrics holds per-agent observability counters.
+type AgentMetrics struct {
+ Submitted uint64 `json:"submitted"`
+ Completed uint64 `json:"completed"`
+ Failed uint64 `json:"failed"`
+ Cancelled uint64 `json:"cancelled"`
+ Rejected uint64 `json:"rejected"`
+}
+
+func newMetrics() *Metrics {
+ return &Metrics{
+ agentStats: make(map[string]*agentMetricEntry),
+ }
+}
+
+func (m *Metrics) recordSubmit(agentID string) {
+ m.TasksSubmitted.Add(1)
+ m.agentMetric(agentID).add(func(a *AgentMetrics) { a.Submitted++ })
+}
+
+func (m *Metrics) recordReject(agentID string) {
+ m.TasksRejected.Add(1)
+ m.agentMetric(agentID).add(func(a *AgentMetrics) { a.Rejected++ })
+}
+
+func (m *Metrics) recordComplete(agentID string) {
+ m.TasksCompleted.Add(1)
+ m.agentMetric(agentID).add(func(a *AgentMetrics) { a.Completed++ })
+}
+
+func (m *Metrics) recordFail(agentID string) {
+ m.TasksFailed.Add(1)
+ m.agentMetric(agentID).add(func(a *AgentMetrics) { a.Failed++ })
+}
+
+func (m *Metrics) recordCancel(agentID string) {
+ m.TasksCancelled.Add(1)
+ m.agentMetric(agentID).add(func(a *AgentMetrics) { a.Cancelled++ })
+}
+
+func (m *Metrics) recordExpire() {
+ m.TasksExpired.Add(1)
+}
+
+func (m *Metrics) recordDispatchLatency(d time.Duration) {
+ m.DispatchTotal.Add(1)
+ m.DispatchLatency.Add(uint64(d.Milliseconds()))
+}
+
+// Snapshot returns a point-in-time copy of all metrics.
+func (m *Metrics) Snapshot() MetricsSnapshot {
+ dispatched := m.DispatchTotal.Load()
+ latencySum := m.DispatchLatency.Load()
+ avgMs := 0.0
+ if dispatched > 0 {
+ avgMs = float64(latencySum) / float64(dispatched)
+ }
+
+ m.mu.RLock()
+ agents := make(map[string]AgentMetrics, len(m.agentStats))
+ for id, a := range m.agentStats {
+ a.mu.RLock()
+ agents[id] = AgentMetrics{
+ Submitted: a.Submitted,
+ Completed: a.Completed,
+ Failed: a.Failed,
+ Cancelled: a.Cancelled,
+ Rejected: a.Rejected,
+ }
+ a.mu.RUnlock()
+ }
+ m.mu.RUnlock()
+
+ return MetricsSnapshot{
+ TasksSubmitted: m.TasksSubmitted.Load(),
+ TasksCompleted: m.TasksCompleted.Load(),
+ TasksFailed: m.TasksFailed.Load(),
+ TasksCancelled: m.TasksCancelled.Load(),
+ TasksRejected: m.TasksRejected.Load(),
+ TasksExpired: m.TasksExpired.Load(),
+ DispatchCount: dispatched,
+ AvgDispatchLatency: avgMs,
+ Agents: agents,
+ }
+}
+
+// MetricsSnapshot is a serializable point-in-time view of scheduler metrics.
+type MetricsSnapshot struct {
+ TasksSubmitted uint64 `json:"tasksSubmitted"`
+ TasksCompleted uint64 `json:"tasksCompleted"`
+ TasksFailed uint64 `json:"tasksFailed"`
+ TasksCancelled uint64 `json:"tasksCancelled"`
+ TasksRejected uint64 `json:"tasksRejected"`
+ TasksExpired uint64 `json:"tasksExpired"`
+ DispatchCount uint64 `json:"dispatchCount"`
+ AvgDispatchLatency float64 `json:"avgDispatchLatencyMs"`
+ Agents map[string]AgentMetrics `json:"agents"`
+}
+
+// agentMetricEntry wraps AgentMetrics with its own lock for concurrent updates.
+type agentMetricEntry struct {
+ mu sync.RWMutex
+ AgentMetrics
+}
+
+func (e *agentMetricEntry) add(fn func(*AgentMetrics)) {
+ e.mu.Lock()
+ fn(&e.AgentMetrics)
+ e.mu.Unlock()
+}
+
+func (m *Metrics) agentMetric(agentID string) *agentMetricEntry {
+ m.mu.RLock()
+ if e, ok := m.agentStats[agentID]; ok {
+ m.mu.RUnlock()
+ return e
+ }
+ m.mu.RUnlock()
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ // Double-check after upgrading lock.
+ if e, ok := m.agentStats[agentID]; ok {
+ return e
+ }
+ e := &agentMetricEntry{}
+ m.agentStats[agentID] = e
+ return e
+}
diff --git a/internal/scheduler/metrics_test.go b/internal/scheduler/metrics_test.go
new file mode 100644
index 00000000..96ee3564
--- /dev/null
+++ b/internal/scheduler/metrics_test.go
@@ -0,0 +1,152 @@
+package scheduler
+
+import (
+ "testing"
+ "time"
+)
+
+func TestMetricsRecordSubmit(t *testing.T) {
+ m := newMetrics()
+ m.recordSubmit("a1")
+ m.recordSubmit("a1")
+ m.recordSubmit("a2")
+
+ snap := m.Snapshot()
+ if snap.TasksSubmitted != 3 {
+ t.Errorf("expected 3 submitted, got %d", snap.TasksSubmitted)
+ }
+ if snap.Agents["a1"].Submitted != 2 {
+ t.Errorf("expected a1 submitted=2, got %d", snap.Agents["a1"].Submitted)
+ }
+ if snap.Agents["a2"].Submitted != 1 {
+ t.Errorf("expected a2 submitted=1, got %d", snap.Agents["a2"].Submitted)
+ }
+}
+
+func TestMetricsRecordReject(t *testing.T) {
+ m := newMetrics()
+ m.recordReject("a1")
+
+ snap := m.Snapshot()
+ if snap.TasksRejected != 1 {
+ t.Errorf("expected 1 rejected, got %d", snap.TasksRejected)
+ }
+ if snap.Agents["a1"].Rejected != 1 {
+ t.Errorf("expected a1 rejected=1, got %d", snap.Agents["a1"].Rejected)
+ }
+}
+
+func TestMetricsRecordComplete(t *testing.T) {
+ m := newMetrics()
+ m.recordComplete("a1")
+ m.recordComplete("a1")
+
+ snap := m.Snapshot()
+ if snap.TasksCompleted != 2 {
+ t.Errorf("expected 2 completed, got %d", snap.TasksCompleted)
+ }
+ if snap.Agents["a1"].Completed != 2 {
+ t.Errorf("expected a1 completed=2, got %d", snap.Agents["a1"].Completed)
+ }
+}
+
+func TestMetricsRecordFail(t *testing.T) {
+ m := newMetrics()
+ m.recordFail("a1")
+
+ snap := m.Snapshot()
+ if snap.TasksFailed != 1 {
+ t.Errorf("expected 1 failed, got %d", snap.TasksFailed)
+ }
+ if snap.Agents["a1"].Failed != 1 {
+ t.Errorf("expected a1 failed=1, got %d", snap.Agents["a1"].Failed)
+ }
+}
+
+func TestMetricsRecordCancel(t *testing.T) {
+ m := newMetrics()
+ m.recordCancel("a1")
+
+ snap := m.Snapshot()
+ if snap.TasksCancelled != 1 {
+ t.Errorf("expected 1 cancelled, got %d", snap.TasksCancelled)
+ }
+ if snap.Agents["a1"].Cancelled != 1 {
+ t.Errorf("expected a1 cancelled=1, got %d", snap.Agents["a1"].Cancelled)
+ }
+}
+
+func TestMetricsRecordExpire(t *testing.T) {
+ m := newMetrics()
+ m.recordExpire()
+ m.recordExpire()
+
+ snap := m.Snapshot()
+ if snap.TasksExpired != 2 {
+ t.Errorf("expected 2 expired, got %d", snap.TasksExpired)
+ }
+}
+
+func TestMetricsDispatchLatency(t *testing.T) {
+ m := newMetrics()
+ m.recordDispatchLatency(100 * time.Millisecond)
+ m.recordDispatchLatency(200 * time.Millisecond)
+
+ snap := m.Snapshot()
+ if snap.DispatchCount != 2 {
+ t.Errorf("expected 2 dispatches, got %d", snap.DispatchCount)
+ }
+ // Average of 100ms and 200ms = 150ms.
+ if snap.AvgDispatchLatency < 140 || snap.AvgDispatchLatency > 160 {
+ t.Errorf("expected avg ~150ms, got %.1f", snap.AvgDispatchLatency)
+ }
+}
+
+func TestMetricsSnapshotIsolation(t *testing.T) {
+ m := newMetrics()
+ m.recordSubmit("a1")
+ snap1 := m.Snapshot()
+
+ m.recordSubmit("a1")
+ snap2 := m.Snapshot()
+
+ if snap1.TasksSubmitted != 1 {
+ t.Error("snapshot1 should not be affected by later records")
+ }
+ if snap2.TasksSubmitted != 2 {
+ t.Error("snapshot2 should reflect both records")
+ }
+}
+
+func TestMetricsConcurrentAgentCreation(t *testing.T) {
+ m := newMetrics()
+ done := make(chan struct{})
+
+ for i := range 10 {
+ go func(id int) {
+ defer func() { done <- struct{}{} }()
+ agent := "agent"
+ if id%2 == 0 {
+ agent = "agent-even"
+ }
+ m.recordSubmit(agent)
+ }(i)
+ }
+
+ for range 10 {
+ <-done
+ }
+
+ snap := m.Snapshot()
+ if snap.TasksSubmitted != 10 {
+ t.Errorf("expected 10 submitted, got %d", snap.TasksSubmitted)
+ }
+}
+
+func TestMetricsAvgLatencyZeroDispatches(t *testing.T) {
+ m := newMetrics()
+ snap := m.Snapshot()
+ if snap.AvgDispatchLatency != 0 {
+ t.Errorf("expected 0 avg latency with no dispatches, got %.1f", snap.AvgDispatchLatency)
+ }
+}
diff --git a/internal/scheduler/queue.go b/internal/scheduler/queue.go
index fe2a3232..e006600b 100644
--- a/internal/scheduler/queue.go
+++ b/internal/scheduler/queue.go
@@ -29,6 +29,18 @@ func NewTaskQueue(maxTotal, maxPerAgent int) *TaskQueue {
}
}
+// SetLimits updates queue capacity at runtime.
+func (q *TaskQueue) SetLimits(maxTotal, maxPerAgent int) {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ if maxTotal > 0 {
+ q.maxTotal = maxTotal
+ }
+ if maxPerAgent > 0 {
+ q.maxPerAgent = maxPerAgent
+ }
+}
+
// Enqueue adds a task. Returns the queue position or an error if limits are hit.
func (q *TaskQueue) Enqueue(t *Task) (int, error) {
q.mu.Lock()
diff --git a/internal/scheduler/reload.go b/internal/scheduler/reload.go
new file mode 100644
index 00000000..f87114a7
--- /dev/null
+++ b/internal/scheduler/reload.go
@@ -0,0 +1,85 @@
+package scheduler
+
+import (
+ "log/slog"
+ "sync"
+ "time"
+)
+
+// ReloadConfig applies new queue limits without restarting the scheduler.
+// Only tuning knobs that are safe to change at runtime are updated.
+func (s *Scheduler) ReloadConfig(cfg Config) {
+ if cfg.MaxQueueSize > 0 {
+ s.queue.SetLimits(cfg.MaxQueueSize, cfg.MaxPerAgent)
+ slog.Info("scheduler: queue limits reloaded",
+ "maxQueueSize", cfg.MaxQueueSize,
+ "maxPerAgent", cfg.MaxPerAgent,
+ )
+ }
+ if cfg.MaxInflight > 0 {
+ s.cfgMu.Lock()
+ s.cfg.MaxInflight = cfg.MaxInflight
+ s.cfg.MaxPerAgentFlight = cfg.MaxPerAgentFlight
+ s.cfgMu.Unlock()
+ slog.Info("scheduler: inflight limits reloaded",
+ "maxInflight", cfg.MaxInflight,
+ "maxPerAgentFlight", cfg.MaxPerAgentFlight,
+ )
+ }
+ if cfg.ResultTTL > 0 {
+ s.results.SetTTL(cfg.ResultTTL)
+ slog.Info("scheduler: result TTL reloaded", "ttl", cfg.ResultTTL)
+ }
+}
+
+// ConfigWatcher periodically re-reads the scheduler config and applies changes.
+type ConfigWatcher struct {
+ interval time.Duration
+ loadFn func() (Config, error)
+ sched *Scheduler
+ stopCh chan struct{}
+ wg sync.WaitGroup
+}
+
+// NewConfigWatcher creates a watcher that calls loadFn at the given interval
+// and applies any changed values to the scheduler.
+func NewConfigWatcher(interval time.Duration, loadFn func() (Config, error), sched *Scheduler) *ConfigWatcher {
+ return &ConfigWatcher{
+ interval: interval,
+ loadFn: loadFn,
+ sched: sched,
+ stopCh: make(chan struct{}),
+ }
+}
+
+// Start begins the config watch loop.
+func (cw *ConfigWatcher) Start() {
+ cw.wg.Add(1)
+ go cw.run()
+}
+
+// Stop terminates the config watcher.
+func (cw *ConfigWatcher) Stop() {
+ close(cw.stopCh)
+ cw.wg.Wait()
+}
+
+func (cw *ConfigWatcher) run() {
+ defer cw.wg.Done()
+ ticker := time.NewTicker(cw.interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-cw.stopCh:
+ return
+ case <-ticker.C:
+ cfg, err := cw.loadFn()
+ if err != nil {
+ slog.Warn("config watcher: failed to load config", "err", err)
+ continue
+ }
+ cw.sched.ReloadConfig(cfg)
+ }
+ }
+}
diff --git a/internal/scheduler/reload_test.go b/internal/scheduler/reload_test.go
new file mode 100644
index 00000000..4dbd34cb
--- /dev/null
+++ b/internal/scheduler/reload_test.go
@@ -0,0 +1,267 @@
+package scheduler
+
+import (
+ "errors"
+ "testing"
+ "time"
+)
+
+func TestReloadConfigQueueLimits(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ original := s.cfg
+ s.ReloadConfig(Config{
+ MaxQueueSize: 500,
+ MaxPerAgent: 50,
+ })
+
+ // Queue limits should be updated.
+ stats := s.QueueStats()
+ _ = stats // Stats reflect current queue state, not limits directly.
+
+ // Inflight limits should be unchanged.
+ perAgent, global := s.inflightLimits()
+ if perAgent != original.MaxPerAgentFlight {
+ t.Errorf("perAgent should be unchanged, got %d", perAgent)
+ }
+ if global != original.MaxInflight {
+ t.Errorf("global should be unchanged, got %d", global)
+ }
+}
+
+func TestReloadConfigInflightLimits(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ s.ReloadConfig(Config{
+ MaxInflight: 30,
+ MaxPerAgentFlight: 15,
+ })
+
+ perAgent, global := s.inflightLimits()
+ if perAgent != 15 {
+ t.Errorf("expected perAgent=15, got %d", perAgent)
+ }
+ if global != 30 {
+ t.Errorf("expected global=30, got %d", global)
+ }
+}
+
+func TestReloadConfigResultTTL(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ s.ReloadConfig(Config{
+ ResultTTL: 10 * time.Minute,
+ })
+
+ // Just verify no panic — TTL is internal to ResultStore.
+}
+
+func TestReloadConfigZeroValuesIgnored(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ original := s.cfg
+
+ // Zero values should not change anything.
+ s.ReloadConfig(Config{})
+
+ perAgent, global := s.inflightLimits()
+ if perAgent != original.MaxPerAgentFlight {
+ t.Errorf("perAgent should be unchanged, got %d", perAgent)
+ }
+ if global != original.MaxInflight {
+ t.Errorf("global should be unchanged, got %d", global)
+ }
+}
+
+func TestConfigWatcherStartStop(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ callCount := 0
+ loadFn := func() (Config, error) {
+ callCount++
+ return Config{MaxInflight: 99, MaxPerAgentFlight: 49}, nil
+ }
+
+ cw := NewConfigWatcher(50*time.Millisecond, loadFn, s)
+ cw.Start()
+
+ time.Sleep(200 * time.Millisecond)
+ cw.Stop()
+
+ if callCount == 0 {
+ t.Error("config watcher should have called loadFn at least once")
+ }
+
+ perAgent, global := s.inflightLimits()
+ if perAgent != 49 {
+ t.Errorf("expected perAgent=49 after reload, got %d", perAgent)
+ }
+ if global != 99 {
+ t.Errorf("expected global=99 after reload, got %d", global)
+ }
+}
+
+func TestConfigWatcherLoadError(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ original := s.cfg
+
+ loadFn := func() (Config, error) {
+ return Config{}, errors.New("config unavailable")
+ }
+
+ cw := NewConfigWatcher(50*time.Millisecond, loadFn, s)
+ cw.Start()
+ time.Sleep(200 * time.Millisecond)
+ cw.Stop()
+
+ // Limits should be unchanged since load always fails.
+ perAgent, global := s.inflightLimits()
+ if perAgent != original.MaxPerAgentFlight {
+ t.Errorf("perAgent should be unchanged after error, got %d", perAgent)
+ }
+ if global != original.MaxInflight {
+ t.Errorf("global should be unchanged after error, got %d", global)
+ }
+}
+
+func TestQueueSetLimits(t *testing.T) {
+ q := NewTaskQueue(10, 5)
+
+ q.SetLimits(20, 10)
+
+ // Should accept more tasks now.
+ for i := range 10 {
+ task := &Task{
+ ID: generateTaskID(),
+ AgentID: "a1",
+ Action: "click",
+ State: StateQueued,
+ Deadline: time.Now().Add(time.Minute),
+ }
+ _, err := q.Enqueue(task)
+ if err != nil {
+ t.Fatalf("Enqueue task[%d] failed unexpectedly: %v", i, err)
+ }
+ }
+
+ // 11th task from same agent should fail (per-agent limit is 10).
+ task := &Task{
+ ID: generateTaskID(),
+ AgentID: "a1",
+ Action: "click",
+ State: StateQueued,
+ Deadline: time.Now().Add(time.Minute),
+ }
+ _, err := q.Enqueue(task)
+ if err == nil {
+ t.Error("should reject task exceeding new per-agent limit")
+ }
+}
+
+func TestResultStoreSetTTL(t *testing.T) {
+ rs := NewResultStore(5 * time.Minute)
+
+ rs.SetTTL(1 * time.Minute)
+
+ // Just verify no panic.
+ task := &Task{
+ ID: "tsk_ttl_1",
+ AgentID: "a1",
+ State: StateDone,
+ }
+ rs.Store(task)
+
+ got := rs.Get("tsk_ttl_1")
+ if got == nil {
+ t.Error("should find stored task")
+ }
+}
+
+func TestMetricsWiredInSubmit(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ _, _ = s.Submit(SubmitRequest{
+ AgentID: "a1",
+ Action: "click",
+ TabID: "tab-1",
+ })
+
+ snap := s.GetMetrics()
+ if snap.TasksSubmitted != 1 {
+ t.Errorf("expected 1 submitted, got %d", snap.TasksSubmitted)
+ }
+ if snap.Agents["a1"].Submitted != 1 {
+ t.Errorf("expected a1 submitted=1, got %d", snap.Agents["a1"].Submitted)
+ }
+}
+
+func TestMetricsWiredInCancel(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ task, err := s.Submit(SubmitRequest{
+ AgentID: "a1",
+ Action: "click",
+ TabID: "tab-1",
+ })
+ if err != nil {
+ t.Fatalf("submit: %v", err)
+ }
+
+ if err := s.Cancel(task.ID); err != nil {
+ t.Fatalf("cancel: %v", err)
+ }
+
+ snap := s.GetMetrics()
+ if snap.TasksCancelled != 1 {
+ t.Errorf("expected 1 cancelled, got %d", snap.TasksCancelled)
+ }
+}
+
+func TestMetricsWiredInDispatch(t *testing.T) {
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ s.Start()
+ defer s.Stop()
+
+ _, err := s.Submit(SubmitRequest{
+ AgentID: "a1",
+ Action: "click",
+ TabID: "tab-1",
+ Ref: "e1",
+ })
+ if err != nil {
+ t.Fatalf("submit: %v", err)
+ }
+
+ // Wait for dispatch to complete.
+ deadline := time.After(5 * time.Second)
+ for {
+ snap := s.GetMetrics()
+ if snap.TasksCompleted >= 1 || snap.TasksFailed >= 1 {
+ break
+ }
+ select {
+ case <-deadline:
+ t.Fatal("timed out waiting for task dispatch")
+ case <-time.After(50 * time.Millisecond):
+ }
+ }
+
+ snap := s.GetMetrics()
+ if snap.DispatchCount == 0 {
+ t.Error("dispatch count should be > 0 after task execution")
+ }
+ if snap.AvgDispatchLatency <= 0 {
+ t.Error("avg dispatch latency should be > 0")
+ }
+}
diff --git a/internal/scheduler/results.go b/internal/scheduler/results.go
index d0309d24..acdb505c 100644
--- a/internal/scheduler/results.go
+++ b/internal/scheduler/results.go
@@ -48,6 +48,13 @@ func (rs *ResultStore) Stop() {
}
}
+// SetTTL updates the eviction TTL at runtime.
+func (rs *ResultStore) SetTTL(ttl time.Duration) {
+ rs.mu.Lock()
+ rs.ttl = ttl
+ rs.mu.Unlock()
+}
+
// Store saves a task snapshot into the result store.
func (rs *ResultStore) Store(t *Task) {
snap := t.Snapshot()
diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.go
index 13785e99..af2de3c7 100644
--- a/internal/scheduler/scheduler.go
+++ b/internal/scheduler/scheduler.go
@@ -47,10 +47,12 @@ func DefaultConfig() Config {
// Scheduler is the core dispatch engine.
type Scheduler struct {
cfg Config
+ cfgMu sync.RWMutex
queue *TaskQueue
results *ResultStore
resolver InstanceResolver
client *http.Client
+ metrics *Metrics
// tracks all live tasks (queued + in-flight) for lookup by ID.
live map[string]*Task
@@ -92,6 +94,7 @@ func New(cfg Config, resolver InstanceResolver) *Scheduler {
results: NewResultStore(cfg.ResultTTL),
resolver: resolver,
client: &http.Client{Timeout: 60 * time.Second},
+ metrics: newMetrics(),
live: make(map[string]*Task),
cancels: make(map[string]context.CancelFunc),
stopCh: make(chan struct{}),
@@ -156,16 +159,17 @@ func (s *Scheduler) Submit(req SubmitRequest) (*Task, error) {
}
t := &Task{
- ID: generateTaskID(),
- AgentID: req.AgentID,
- Action: req.Action,
- TabID: req.TabID,
- Ref: req.Ref,
- Params: req.Params,
- Priority: req.Priority,
- State: StateQueued,
- Deadline: deadline,
- CreatedAt: now,
+ ID: generateTaskID(),
+ AgentID: req.AgentID,
+ Action: req.Action,
+ TabID: req.TabID,
+ Ref: req.Ref,
+ Params: req.Params,
+ Priority: req.Priority,
+ State: StateQueued,
+ Deadline: deadline,
+ CreatedAt: now,
+ CallbackURL: req.CallbackURL,
}
pos, err := s.queue.Enqueue(t)
@@ -173,6 +177,8 @@ func (s *Scheduler) Submit(req SubmitRequest) (*Task, error) {
t.State = StateRejected
t.Error = err.Error()
s.results.Store(t)
+ s.metrics.recordReject(req.AgentID)
+ slog.Warn("task rejected", "task", t.ID, "agent", req.AgentID, "err", err)
return t, fmt.Errorf("rejected: %w", err)
}
@@ -183,6 +189,8 @@ func (s *Scheduler) Submit(req SubmitRequest) (*Task, error) {
s.liveMu.Unlock()
s.results.Store(t)
+ s.metrics.recordSubmit(req.AgentID)
+ slog.Info("task submitted", "task", t.ID, "agent", req.AgentID, "action", t.Action, "priority", t.Priority, "position", pos)
return t, nil
}
@@ -233,6 +241,9 @@ func (s *Scheduler) Cancel(taskID string) error {
return fmt.Errorf("cancel failed: %w", err)
}
+ s.metrics.recordCancel(t.AgentID)
+ slog.Info("task cancelled", "task", t.ID, "agent", t.AgentID, "previousState", state)
+
s.finishTask(t)
return nil
}
@@ -247,6 +258,19 @@ func (s *Scheduler) QueueStats() QueueStats {
return s.queue.Stats()
}
+// GetMetrics returns a snapshot of all scheduler metrics.
+func (s *Scheduler) GetMetrics() MetricsSnapshot {
+ return s.metrics.Snapshot()
+}
+
+func (s *Scheduler) inflightLimits() (perAgent, global int) {
+ s.cfgMu.RLock()
+ perAgent = s.cfg.MaxPerAgentFlight
+ global = s.cfg.MaxInflight
+ s.cfgMu.RUnlock()
+ return
+}
+
func (s *Scheduler) worker(id int) {
defer s.wg.Done()
for {
@@ -256,7 +280,7 @@ func (s *Scheduler) worker(id int) {
default:
}
- task := s.queue.Dequeue(s.cfg.MaxPerAgentFlight, s.cfg.MaxInflight)
+ task := s.queue.Dequeue(s.inflightLimits())
if task == nil {
select {
case <-s.stopCh:
@@ -271,11 +295,14 @@ func (s *Scheduler) worker(id int) {
}
func (s *Scheduler) dispatch(t *Task) {
+ dispatchStart := timeNow()
+
if err := t.SetState(StateAssigned); err != nil {
slog.Warn("task state transition failed", "task", t.ID, "err", err)
s.finishTask(t)
return
}
+ slog.Info("task assigned", "task", t.ID, "agent", t.AgentID, "action", t.Action)
s.results.Store(t)
ctx, cancel := context.WithDeadline(context.Background(), t.Deadline)
@@ -296,20 +323,28 @@ func (s *Scheduler) dispatch(t *Task) {
s.finishTask(t)
return
}
+ slog.Info("task running", "task", t.ID, "agent", t.AgentID)
s.results.Store(t)
result, execErr := s.executeTask(ctx, t)
+ latency := timeNow().Sub(dispatchStart)
+ s.metrics.recordDispatchLatency(latency)
+
if execErr != nil {
t.Error = execErr.Error()
if stateErr := t.SetState(StateFailed); stateErr != nil {
slog.Warn("failed to mark task as failed", "task", t.ID, "err", stateErr)
}
+ s.metrics.recordFail(t.AgentID)
+ slog.Info("task failed", "task", t.ID, "agent", t.AgentID, "err", execErr, "latencyMs", latency.Milliseconds())
} else {
t.Result = result
if stateErr := t.SetState(StateDone); stateErr != nil {
slog.Warn("failed to mark task as done", "task", t.ID, "err", stateErr)
}
+ s.metrics.recordComplete(t.AgentID)
+ slog.Info("task completed", "task", t.ID, "agent", t.AgentID, "action", t.Action, "latencyMs", latency.Milliseconds())
}
s.finishTask(t)
@@ -382,6 +417,11 @@ func (s *Scheduler) finishTask(t *Task) {
s.liveMu.Lock()
delete(s.live, t.ID)
s.liveMu.Unlock()
+
+ // Fire webhook asynchronously if configured.
+ if t.CallbackURL != "" && t.GetState().IsTerminal() {
+ go sendWebhook(t.CallbackURL, t)
+ }
}
func (s *Scheduler) deadlineReaper() {
@@ -400,6 +440,9 @@ func (s *Scheduler) deadlineReaper() {
if err := t.SetState(StateFailed); err != nil {
slog.Warn("deadline reaper state transition failed", "task", t.ID, "err", err)
}
+ s.metrics.recordExpire()
+ s.metrics.recordFail(t.AgentID)
+ slog.Info("task expired", "task", t.ID, "agent", t.AgentID)
s.finishTask(t)
}
}
diff --git a/internal/scheduler/task.go b/internal/scheduler/task.go
index a35a6a94..579f2086 100644
--- a/internal/scheduler/task.go
+++ b/internal/scheduler/task.go
@@ -52,6 +52,9 @@ type Task struct {
Result any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
+ // CallbackURL receives a POST with the task snapshot on completion.
+ CallbackURL string `json:"callbackUrl,omitempty"`
+
// position is the queue position at submission time.
Position int `json:"position,omitempty"`
}
@@ -120,19 +123,21 @@ func (t *Task) Snapshot() *Task {
LatencyMs: t.LatencyMs,
Result: t.Result,
Error: t.Error,
+ CallbackURL: t.CallbackURL,
Position: t.Position,
}
}
// SubmitRequest is the JSON body for POST /tasks.
type SubmitRequest struct {
- AgentID string `json:"agentId"`
- Action string `json:"action"`
- TabID string `json:"tabId,omitempty"`
- Ref string `json:"ref,omitempty"`
- Params map[string]any `json:"params,omitempty"`
- Priority int `json:"priority,omitempty"`
- Deadline string `json:"deadline,omitempty"`
+ AgentID string `json:"agentId"`
+ Action string `json:"action"`
+ TabID string `json:"tabId,omitempty"`
+ Ref string `json:"ref,omitempty"`
+ Params map[string]any `json:"params,omitempty"`
+ Priority int `json:"priority,omitempty"`
+ Deadline string `json:"deadline,omitempty"`
+ CallbackURL string `json:"callbackUrl,omitempty"`
}
// Validate checks that the request has the minimum required fields.
diff --git a/internal/scheduler/webhook.go b/internal/scheduler/webhook.go
new file mode 100644
index 00000000..aa2b2fab
--- /dev/null
+++ b/internal/scheduler/webhook.go
@@ -0,0 +1,64 @@
+package scheduler
+
+import (
+ "bytes"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// webhookClient is a dedicated HTTP client for webhook delivery with short timeouts.
+var webhookClient = &http.Client{
+ Timeout: 10 * time.Second,
+}
+
+// sendWebhook delivers a task snapshot to the configured callbackUrl.
+// Delivery is best-effort: failures are logged but do not affect task state.
+func sendWebhook(callbackURL string, t *Task) {
+ if callbackURL == "" {
+ return
+ }
+
+ // Only allow http/https schemes to prevent SSRF.
+ parsed, err := url.Parse(callbackURL)
+ if err != nil {
+ slog.Warn("webhook: invalid callback URL", "task", t.ID, "url", callbackURL, "err", err)
+ return
+ }
+ if parsed.Scheme != "http" && parsed.Scheme != "https" {
+ slog.Warn("webhook: unsupported scheme", "task", t.ID, "scheme", parsed.Scheme)
+ return
+ }
+
+ snap := t.Snapshot()
+ payload, err := json.Marshal(snap)
+ if err != nil {
+ slog.Warn("webhook: failed to marshal task", "task", t.ID, "err", err)
+ return
+ }
+
+ req, err := http.NewRequest(http.MethodPost, callbackURL, bytes.NewReader(payload))
+ if err != nil {
+ slog.Warn("webhook: failed to create request", "task", t.ID, "err", err)
+ return
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-PinchTab-Event", "task.completed")
+ req.Header.Set("X-PinchTab-Task-ID", snap.ID)
+
+ resp, err := webhookClient.Do(req)
+ if err != nil {
+ slog.Warn("webhook: delivery failed", "task", t.ID, "url", callbackURL, "err", err)
+ return
+ }
+ _ = resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ slog.Warn("webhook: non-success response", "task", t.ID, "url", callbackURL, "status", resp.StatusCode)
+ return
+ }
+
+ slog.Info("webhook: delivered", "task", t.ID, "url", callbackURL, "status", resp.StatusCode)
+}
diff --git a/internal/scheduler/webhook_test.go b/internal/scheduler/webhook_test.go
new file mode 100644
index 00000000..21653faa
--- /dev/null
+++ b/internal/scheduler/webhook_test.go
@@ -0,0 +1,160 @@
+package scheduler
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestSendWebhookSuccess(t *testing.T) {
+ var received atomic.Bool
+ var gotBody []byte
+ var gotHeaders http.Header
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ received.Store(true)
+ gotHeaders = r.Header.Clone()
+ var err error
+ gotBody, err = io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("read body: %v", err)
+ }
+ w.WriteHeader(200)
+ }))
+ defer srv.Close()
+
+ task := &Task{
+ ID: "tsk_webhook_1",
+ AgentID: "a1",
+ Action: "click",
+ State: StateDone,
+ }
+
+ sendWebhook(srv.URL, task)
+
+ if !received.Load() {
+ t.Fatal("webhook was never received")
+ }
+
+ // Verify headers.
+ if ct := gotHeaders.Get("Content-Type"); ct != "application/json" {
+ t.Errorf("expected application/json, got %s", ct)
+ }
+ if ev := gotHeaders.Get("X-PinchTab-Event"); ev != "task.completed" {
+ t.Errorf("expected task.completed event, got %s", ev)
+ }
+ if tid := gotHeaders.Get("X-PinchTab-Task-ID"); tid != "tsk_webhook_1" {
+ t.Errorf("expected task ID header, got %s", tid)
+ }
+
+ // Verify body is a valid task snapshot.
+ var snap Task
+ if err := json.Unmarshal(gotBody, &snap); err != nil {
+ t.Fatalf("unmarshal body: %v", err)
+ }
+ if snap.ID != "tsk_webhook_1" {
+ t.Errorf("expected task ID in body, got %s", snap.ID)
+ }
+}
+
+func TestSendWebhookEmptyURL(t *testing.T) {
+ // Should be a no-op, no panic.
+ sendWebhook("", &Task{ID: "tsk_empty"})
+}
+
+func TestSendWebhookUnsupportedScheme(t *testing.T) {
+ // file:// scheme should be rejected for SSRF protection.
+ sendWebhook("file:///etc/passwd", &Task{ID: "tsk_ssrf"})
+ // ftp:// should also be rejected.
+ sendWebhook("ftp://malicious.host/data", &Task{ID: "tsk_ssrf2"})
+}
+
+func TestSendWebhookInvalidURL(t *testing.T) {
+ sendWebhook("://bad-url", &Task{ID: "tsk_bad_url"})
+}
+
+func TestSendWebhookServerError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(500)
+ }))
+ defer srv.Close()
+
+ // Should not panic — just logs warning.
+ sendWebhook(srv.URL, &Task{ID: "tsk_500", State: StateFailed})
+}
+
+func TestSendWebhookTimeout(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(100 * time.Millisecond)
+ w.WriteHeader(200)
+ }))
+ defer srv.Close()
+
+ // Use a short-timeout client for testing.
+ origClient := webhookClient
+ webhookClient = &http.Client{Timeout: 10 * time.Millisecond}
+ defer func() { webhookClient = origClient }()
+
+ // Should not panic — timeout is logged.
+ sendWebhook(srv.URL, &Task{ID: "tsk_timeout"})
+}
+
+func TestWebhookFiredOnFinishTask(t *testing.T) {
+ var received atomic.Bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ received.Store(true)
+ w.WriteHeader(200)
+ }))
+ defer srv.Close()
+
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ task := &Task{
+ ID: "tsk_cb_1",
+ AgentID: "a1",
+ Action: "click",
+ State: StateDone,
+ CallbackURL: srv.URL,
+ }
+ s.live["tsk_cb_1"] = task
+
+ s.finishTask(task)
+
+ // Give goroutine time to fire.
+ time.Sleep(200 * time.Millisecond)
+
+ if !received.Load() {
+ t.Error("webhook should have been fired from finishTask")
+ }
+}
+
+func TestWebhookNotFiredWithoutCallback(t *testing.T) {
+ var received atomic.Bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ received.Store(true)
+ w.WriteHeader(200)
+ }))
+ defer srv.Close()
+
+ s, executor := newTestScheduler(t)
+ defer executor.Close()
+
+ task := &Task{
+ ID: "tsk_no_cb",
+ AgentID: "a1",
+ State: StateDone,
+ }
+ s.live["tsk_no_cb"] = task
+
+ s.finishTask(task)
+ time.Sleep(100 * time.Millisecond)
+
+ if received.Load() {
+ t.Error("webhook should not fire when no callbackUrl")
+ }
+}
diff --git a/tests/scheduler_phase2_3_test.ps1 b/tests/scheduler_phase2_3_test.ps1
new file mode 100644
index 00000000..d73500ec
--- /dev/null
+++ b/tests/scheduler_phase2_3_test.ps1
@@ -0,0 +1,747 @@
+# ============================================================
+# PinchTab Scheduler - Phase 2 & 3 Manual Integration Tests
+# ============================================================
+# Real-world browser automation tests against live websites.
+# Tests Phase 2 (Observability) and Phase 3 (Hardening) features:
+# - GET /scheduler/stats endpoint & metrics counters
+# - Per-agent metrics and dispatch latency tracking
+# - POST /tasks/batch endpoint (batch submission)
+# - Webhook callbacks (callbackUrl field)
+# - Metrics accuracy across real browser tasks
+#
+# Prerequisites:
+# 1. Server running: go run ./cmd/pinchtab dashboard
+# with scheduler enabled in config (scheduler.enabled = true)
+# 2. At least one browser instance running with a tab.
+#
+# Usage:
+# .\tests\scheduler_phase2_3_test.ps1 [-Port 9867] [-Token ""]
+#
+# After running, results are appended to SCHEDULER_CHANGES.md
+# ============================================================
+
+param(
+ [string]$Port = "9867",
+ [string]$Token = ""
+)
+
+$ErrorActionPreference = "Stop"
+$Base = "http://localhost:$Port"
+$Headers = @{ "Content-Type" = "application/json" }
+if ($Token -ne "") {
+ $Headers["Authorization"] = "Bearer $Token"
+}
+
+$Pass = 0
+$Fail = 0
+$Results = @()
+
+function Write-Test {
+ param([string]$Name, [bool]$Ok, [string]$Detail = "")
+ $icon = if ($Ok) { "[PASS]" } else { "[FAIL]" }
+ $color = if ($Ok) { "Green" } else { "Red" }
+ Write-Host "$icon $Name" -ForegroundColor $color
+ if ($Detail) { Write-Host " $Detail" -ForegroundColor DarkGray }
+ if ($Ok) { $script:Pass++ } else { $script:Fail++ }
+ $script:Results += [PSCustomObject]@{ Test = $Name; Status = $icon; Detail = $Detail }
+}
+
+function Invoke-Api {
+ param([string]$Method, [string]$Path, [object]$Body = $null)
+ $uri = "$Base$Path"
+ $params = @{
+ Uri = $uri
+ Method = $Method
+ Headers = $Headers
+ UseBasicParsing = $true
+ }
+ if ($Body) {
+ $params["Body"] = ($Body | ConvertTo-Json -Depth 10)
+ }
+ try {
+ $resp = Invoke-WebRequest @params
+ return @{
+ StatusCode = $resp.StatusCode
+ Body = ($resp.Content | ConvertFrom-Json)
+ Raw = $resp.Content
+ }
+ }
+ catch {
+ $ex = $_.Exception
+ $code = 0
+ $content = ""
+ if ($ex.Response) {
+ $code = [int]$ex.Response.StatusCode
+ $sr = [System.IO.StreamReader]::new($ex.Response.GetResponseStream())
+ $content = $sr.ReadToEnd()
+ $sr.Close()
+ }
+ return @{
+ StatusCode = $code
+ Body = $null
+ Raw = $content
+ Error = $ex.Message
+ }
+ }
+}
+
+function Wait-TaskDone {
+ param([string]$TaskId, [int]$TimeoutSec = 30)
+ $deadline = (Get-Date).AddSeconds($TimeoutSec)
+ while ((Get-Date) -lt $deadline) {
+ $r = Invoke-Api -Method GET -Path "/tasks/$TaskId"
+ if ($r.StatusCode -eq 200 -and $r.Body.state -in @("done","failed","cancelled")) {
+ return $r.Body
+ }
+ Start-Sleep -Milliseconds 500
+ }
+ return $null
+}
+
+function Submit-Task {
+ param(
+ [string]$AgentId,
+ [string]$Action,
+ [string]$Tab,
+ [hashtable]$Params = @{},
+ [int]$Priority = 5,
+ [string]$CallbackUrl = ""
+ )
+ $body = @{ agentId = $AgentId; action = $Action; tabId = $Tab; priority = $Priority }
+ if ($Params.Count -gt 0) { $body["params"] = $Params }
+ if ($CallbackUrl -ne "") { $body["callbackUrl"] = $CallbackUrl }
+ return Invoke-Api -Method POST -Path "/tasks" -Body $body
+}
+
+function Navigate-Tab {
+ param([string]$Tab, [string]$Url)
+ $r = Invoke-Api -Method POST -Path "/tabs/$Tab/navigate" -Body @{ url = $Url }
+ Start-Sleep -Seconds 3
+ return $r
+}
+
+# ============================================================
+Write-Host ""
+Write-Host "============================================" -ForegroundColor Cyan
+Write-Host " PinchTab Scheduler - Phase 2 & 3 Tests" -ForegroundColor Cyan
+Write-Host " Server: $Base" -ForegroundColor Cyan
+Write-Host "============================================" -ForegroundColor Cyan
+Write-Host ""
+
+# --------------------------------------------------
+# PREFLIGHT: Server & scheduler health
+# --------------------------------------------------
+Write-Host "--- Preflight: Server & Scheduler ---" -ForegroundColor Yellow
+$health = Invoke-Api -Method GET -Path "/health"
+Write-Test "Server is alive" ($health.StatusCode -eq 200) $health.Raw
+if ($health.StatusCode -ne 200) {
+ Write-Host "Server not reachable at $Base - aborting." -ForegroundColor Red
+ exit 1
+}
+
+$schedCheck = Invoke-Api -Method GET -Path "/tasks"
+if ($schedCheck.StatusCode -eq 404 -or $schedCheck.StatusCode -eq 0) {
+ Write-Host "Scheduler not enabled! Add '" -NoNewline -ForegroundColor Red
+ Write-Host '{"scheduler":{"enabled":true}}' -NoNewline -ForegroundColor Yellow
+ Write-Host "' to your config.json and restart the server." -ForegroundColor Red
+ exit 1
+}
+Write-Test "Scheduler is enabled" ($schedCheck.StatusCode -eq 200)
+
+# --------------------------------------------------
+# PREFLIGHT: Discover instance & tab
+# --------------------------------------------------
+Write-Host ""
+Write-Host "--- Discovering instance & tab ---" -ForegroundColor Yellow
+$instances = Invoke-Api -Method GET -Path "/instances"
+$running = ($instances.Body | Where-Object { $_.status -eq "running" })
+if (-not $running -or $running.Count -eq 0) {
+ Write-Host "No running instances found. Start one first." -ForegroundColor Red
+ exit 1
+}
+$inst = if ($running -is [array]) { $running[0] } else { $running }
+Write-Host " Instance: $($inst.id) Port: $($inst.port)" -ForegroundColor DarkGray
+
+$tabsResp = Invoke-Api -Method GET -Path "/instances/tabs"
+$tabs = $tabsResp.Body
+if (-not $tabs -or ($tabs.Count -eq 0)) {
+ Write-Host " No tabs found - creating one ..." -ForegroundColor DarkGray
+ $newTab = Invoke-Api -Method POST -Path "/tab" -Body @{ action = "new"; url = "about:blank" }
+ $TabId = $newTab.Body.tabId
+ Start-Sleep -Seconds 2
+} else {
+ $tab = if ($tabs -is [array]) { $tabs[0] } else { $tabs }
+ $TabId = $tab.id
+}
+Write-Host " Tab: $TabId" -ForegroundColor DarkGray
+Write-Test "Tab discovered" ($TabId -ne $null -and $TabId -ne "") "tabId=$TabId"
+
+# ============================================================
+# PHASE 2: OBSERVABILITY
+# ============================================================
+Write-Host ""
+Write-Host "########################################" -ForegroundColor Cyan
+Write-Host " PHASE 2: OBSERVABILITY TESTS" -ForegroundColor Cyan
+Write-Host "########################################" -ForegroundColor Cyan
+
+# --------------------------------------------------
+# SCENARIO 1: Stats endpoint structure
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 1: GET /scheduler/stats" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+Write-Host ""
+Write-Host "--- 1a: Stats endpoint returns valid structure ---" -ForegroundColor Yellow
+$stats = Invoke-Api -Method GET -Path "/scheduler/stats"
+Write-Test "GET /scheduler/stats returns 200" ($stats.StatusCode -eq 200)
+Write-Test "Response has queue section" ($null -ne $stats.Body.queue)
+Write-Test "Response has metrics section" ($null -ne $stats.Body.metrics)
+Write-Test "Response has config section" ($null -ne $stats.Body.config)
+
+Write-Host ""
+Write-Host "--- 1b: Metrics fields present ---" -ForegroundColor Yellow
+$m = $stats.Body.metrics
+Write-Test "Has tasksSubmitted" ($null -ne $m.tasksSubmitted)
+Write-Test "Has tasksCompleted" ($null -ne $m.tasksCompleted)
+Write-Test "Has tasksFailed" ($null -ne $m.tasksFailed)
+Write-Test "Has tasksCancelled" ($null -ne $m.tasksCancelled)
+Write-Test "Has tasksRejected" ($null -ne $m.tasksRejected)
+Write-Test "Has tasksExpired" ($null -ne $m.tasksExpired)
+Write-Test "Has dispatchCount" ($null -ne $m.dispatchCount)
+Write-Test "Has avgDispatchLatencyMs" ($null -ne $m.avgDispatchLatencyMs)
+Write-Test "Has agents map" ($null -ne $m.agents)
+
+Write-Host ""
+Write-Host "--- 1c: Config section fields ---" -ForegroundColor Yellow
+$cfg = $stats.Body.config
+Write-Test "Config has strategy" ($null -ne $cfg.strategy)
+Write-Test "Config has maxQueueSize" ($null -ne $cfg.maxQueueSize)
+Write-Test "Config has maxPerAgent" ($null -ne $cfg.maxPerAgent)
+Write-Test "Config has workerCount" ($null -ne $cfg.workerCount)
+Write-Test "Config has maxInflight" ($null -ne $cfg.maxInflight)
+Write-Test "Config has resultTTL" ($null -ne $cfg.resultTTL)
+
+Write-Host ""
+Write-Host "--- 1d: Queue stats fields ---" -ForegroundColor Yellow
+$qs = $stats.Body.queue
+Write-Test "Queue has totalQueued" ($null -ne $qs.totalQueued)
+Write-Test "Queue has totalInflight" ($null -ne $qs.totalInflight)
+Write-Test "Queue has agents" ($null -ne $qs.agents)
+
+# --------------------------------------------------
+# SCENARIO 2: Metrics increment after real browser tasks on Wikipedia
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 2: Metrics on Wikipedia" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav1 = Navigate-Tab -Tab $TabId -Url "https://en.wikipedia.org/wiki/Main_Page"
+Write-Test "Navigate to Wikipedia Main Page" ($nav1.StatusCode -eq 200)
+
+# Capture baseline metrics
+$baselineStats = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+$baseSubmitted = $baselineStats.tasksSubmitted
+$baseCompleted = $baselineStats.tasksCompleted
+
+Write-Host ""
+Write-Host "--- 2a: Scroll Wikipedia and track metrics ---" -ForegroundColor Yellow
+$s2a = Submit-Task -AgentId "wiki-metrics" -Action "scroll" -Tab $TabId -Params @{ scrollY = 400 }
+Write-Test "Submit: scroll Wikipedia 400px" ($s2a.StatusCode -eq 202)
+$r2a = Wait-TaskDone -TaskId $s2a.Body.taskId
+Write-Test "Scroll completed" ($r2a -ne $null -and $r2a.state -eq "done") "state=$($r2a.state)"
+
+Write-Host ""
+Write-Host "--- 2b: Click a heading link on Wikipedia ---" -ForegroundColor Yellow
+$s2b = Submit-Task -AgentId "wiki-metrics" -Action "click" -Tab $TabId -Params @{ selector = "#bodyContent a" }
+Write-Test "Submit: click a content link" ($s2b.StatusCode -eq 202)
+$r2b = Wait-TaskDone -TaskId $s2b.Body.taskId
+Write-Test "Click completed" ($r2b -ne $null -and $r2b.state -in @("done","failed")) "state=$($r2b.state)"
+
+Write-Host ""
+Write-Host "--- 2c: Hover over first paragraph ---" -ForegroundColor Yellow
+$s2c = Submit-Task -AgentId "wiki-metrics" -Action "hover" -Tab $TabId -Params @{ selector = "#mp-upper p" }
+Write-Test "Submit: hover first paragraph" ($s2c.StatusCode -eq 202)
+$r2c = Wait-TaskDone -TaskId $s2c.Body.taskId
+Write-Test "Hover completed" ($r2c -ne $null -and $r2c.state -in @("done","failed")) "state=$($r2c.state)"
+
+# Verify metrics incremented
+Write-Host ""
+Write-Host "--- 2d: Verify metrics incremented ---" -ForegroundColor Yellow
+$afterStats = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+Write-Test "tasksSubmitted increased by >= 3" ($afterStats.tasksSubmitted -ge ($baseSubmitted + 3))
+Write-Test "dispatchCount > 0" ($afterStats.dispatchCount -gt 0)
+Write-Test "avgDispatchLatencyMs >= 0" ($afterStats.avgDispatchLatencyMs -ge 0)
+
+# Per-agent metrics
+Write-Host ""
+Write-Host "--- 2e: Per-agent metrics for wiki-metrics ---" -ForegroundColor Yellow
+if ($afterStats.agents -and $afterStats.agents."wiki-metrics") {
+ $agentM = $afterStats.agents."wiki-metrics"
+ Write-Test "Agent wiki-metrics submitted >= 3" ($agentM.submitted -ge 3)
+ Write-Test "Agent wiki-metrics has completed field" ($null -ne $agentM.completed)
+ Write-Test "Agent wiki-metrics has failed field" ($null -ne $agentM.failed)
+} else {
+ Write-Test "Agent wiki-metrics present in agents map" $false "not found"
+}
+
+# --------------------------------------------------
+# SCENARIO 3: Metrics on cancel of real-world task
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 3: Cancel Metrics Tracking" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$cancelBefore = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics.tasksCancelled
+
+Write-Host ""
+Write-Host "--- 3a: Submit and immediately cancel ---" -ForegroundColor Yellow
+# Submit several low-priority tasks to increase chance one is still queued when we cancel.
+for ($ci = 0; $ci -lt 5; $ci++) {
+ Submit-Task -AgentId "cancel-metrics" -Action "scroll" -Tab $TabId -Priority 99 | Out-Null
+}
+$cancelTask = Submit-Task -AgentId "cancel-metrics" -Action "scroll" -Tab $TabId -Priority 99
+Write-Test "Task submitted for cancel" ($cancelTask.StatusCode -eq 202) "taskId=$($cancelTask.Body.taskId)"
+$cancelId = $cancelTask.Body.taskId
+
+$cancelResp = Invoke-Api -Method POST -Path "/tasks/$cancelId/cancel"
+$cancelOk = ($cancelResp.StatusCode -eq 200 -or $cancelResp.StatusCode -eq 409)
+Write-Test "Cancel returns 200 or 409 (already done)" $cancelOk "status=$($cancelResp.StatusCode)"
+
+$cancelCheck = Invoke-Api -Method GET -Path "/tasks/$cancelId"
+$cancelState = $cancelCheck.Body.state
+Write-Test "Task state is terminal" ($cancelState -in @("cancelled","done","failed")) "state=$cancelState"
+
+Write-Host ""
+Write-Host "--- 3b: Verify cancel metrics tracked ---" -ForegroundColor Yellow
+# Wait for all cancel-metrics tasks to finish
+Start-Sleep -Seconds 3
+$cancelAfter = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+Write-Test "cancel-metrics agent tracked" ($null -ne $cancelAfter.agents."cancel-metrics")
+if ($cancelAfter.agents."cancel-metrics") {
+ $cm = $cancelAfter.agents."cancel-metrics"
+ Write-Test "cancel-metrics submitted >= 6" ($cm.submitted -ge 6)
+}
+
+# --------------------------------------------------
+# SCENARIO 4: Dispatch latency tracking with Hacker News tasks
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 4: Dispatch Latency (HN)" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav4 = Navigate-Tab -Tab $TabId -Url "https://news.ycombinator.com"
+Write-Test "Navigate to Hacker News" ($nav4.StatusCode -eq 200)
+
+$latencyBefore = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics.dispatchCount
+
+Write-Host ""
+Write-Host "--- 4a: Click first story on HN ---" -ForegroundColor Yellow
+$s4a = Submit-Task -AgentId "hn-latency" -Action "click" -Tab $TabId -Params @{
+ selector = ".titleline > a"
+ waitNav = "true"
+}
+Write-Test "Submit: click first HN story" ($s4a.StatusCode -eq 202)
+$r4a = Wait-TaskDone -TaskId $s4a.Body.taskId
+Write-Test "Click story completed" ($r4a -ne $null -and $r4a.state -in @("done","failed")) "state=$($r4a.state)"
+Start-Sleep -Seconds 2
+
+Write-Host ""
+Write-Host "--- 4b: Scroll the story page ---" -ForegroundColor Yellow
+$s4b = Submit-Task -AgentId "hn-latency" -Action "scroll" -Tab $TabId -Params @{ scrollY = 600 }
+Write-Test "Submit: scroll story 600px" ($s4b.StatusCode -eq 202)
+$r4b = Wait-TaskDone -TaskId $s4b.Body.taskId
+Write-Test "Story scroll completed" ($r4b -ne $null -and $r4b.state -in @("done","failed")) "state=$($r4b.state)"
+
+Write-Host ""
+Write-Host "--- 4c: Verify dispatch latency tracking ---" -ForegroundColor Yellow
+$latencyAfter = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+Write-Test "dispatchCount increased" ($latencyAfter.dispatchCount -gt $latencyBefore)
+Write-Test "avgDispatchLatencyMs > 0 after dispatches" ($latencyAfter.avgDispatchLatencyMs -gt 0) "avg=$($latencyAfter.avgDispatchLatencyMs)ms"
+
+# ============================================================
+# PHASE 3: HARDENING
+# ============================================================
+Write-Host ""
+Write-Host "########################################" -ForegroundColor Cyan
+Write-Host " PHASE 3: HARDENING TESTS" -ForegroundColor Cyan
+Write-Host "########################################" -ForegroundColor Cyan
+
+# --------------------------------------------------
+# SCENARIO 5: Batch submission - Wikipedia multi-action
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 5: Batch Submit (Wikipedia)" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav5 = Navigate-Tab -Tab $TabId -Url "https://en.wikipedia.org/wiki/Alan_Turing"
+Write-Test "Navigate to Alan Turing article" ($nav5.StatusCode -eq 200)
+
+Write-Host ""
+Write-Host "--- 5a: Batch submit 3 real browser tasks ---" -ForegroundColor Yellow
+$batchBody = @{
+ agentId = "batch-wiki"
+ tasks = @(
+ @{ action = "scroll"; tabId = $TabId; params = @{ scrollY = 300 } },
+ @{ action = "hover"; tabId = $TabId; params = @{ selector = "h1" } },
+ @{ action = "scroll"; tabId = $TabId; params = @{ scrollY = 200 }; priority = 1 }
+ )
+}
+$br = Invoke-Api -Method POST -Path "/tasks/batch" -Body $batchBody
+Write-Test "Batch returns 202" ($br.StatusCode -eq 202)
+Write-Test "Batch has tasks array" ($null -ne $br.Body.tasks)
+Write-Test "Batch submitted count = 3" ($br.Body.submitted -eq 3)
+
+# Verify each task was assigned an ID
+if ($br.Body.tasks) {
+ foreach ($i in 0..($br.Body.tasks.Count - 1)) {
+ $item = $br.Body.tasks[$i]
+ Write-Test "Batch task[$i] has taskId" ($null -ne $item.taskId -and $item.taskId -ne "")
+ }
+}
+
+Write-Host ""
+Write-Host "--- 5b: Wait for all batch tasks to complete ---" -ForegroundColor Yellow
+$batchAllDone = $true
+if ($br.Body.tasks) {
+ foreach ($bt in $br.Body.tasks) {
+ if ($bt.taskId) {
+ $bResult = Wait-TaskDone -TaskId $bt.taskId
+ if ($bResult -eq $null) { $batchAllDone = $false }
+ }
+ }
+}
+Write-Test "All batch tasks reached terminal state" $batchAllDone
+
+Write-Host ""
+Write-Host "--- 5c: Batch agent appears in per-agent metrics ---" -ForegroundColor Yellow
+$batchMetrics = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+if ($batchMetrics.agents -and $batchMetrics.agents."batch-wiki") {
+ $bm = $batchMetrics.agents."batch-wiki"
+ Write-Test "batch-wiki submitted >= 3" ($bm.submitted -ge 3)
+} else {
+ Write-Test "batch-wiki agent in metrics" $false "not found"
+}
+
+# --------------------------------------------------
+# SCENARIO 6: Batch validation errors
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 6: Batch Validation" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+Write-Host ""
+Write-Host "--- 6a: Missing agentId ---" -ForegroundColor Yellow
+$br6a = Invoke-Api -Method POST -Path "/tasks/batch" -Body @{
+ tasks = @(@{ action = "click"; tabId = $TabId })
+}
+Write-Test "Missing agentId returns 400" ($br6a.StatusCode -eq 400)
+
+Write-Host ""
+Write-Host "--- 6b: Empty tasks array ---" -ForegroundColor Yellow
+$br6b = Invoke-Api -Method POST -Path "/tasks/batch" -Body @{
+ agentId = "batch-empty"
+ tasks = @()
+}
+Write-Test "Empty tasks returns 400" ($br6b.StatusCode -eq 400)
+
+Write-Host ""
+Write-Host "--- 6c: Oversized batch (>50) ---" -ForegroundColor Yellow
+$bigTasks = @()
+for ($i = 0; $i -lt 51; $i++) {
+ $bigTasks += @{ action = "scroll"; tabId = $TabId }
+}
+$br6c = Invoke-Api -Method POST -Path "/tasks/batch" -Body @{
+ agentId = "batch-big"
+ tasks = $bigTasks
+}
+Write-Test "Oversized batch returns 400" ($br6c.StatusCode -eq 400)
+
+Write-Host ""
+Write-Host "--- 6d: Bad JSON body ---" -ForegroundColor Yellow
+$br6d = Invoke-Api -Method POST -Path "/tasks/batch" -Body "not json"
+Write-Test "Invalid JSON returns 400" ($br6d.StatusCode -eq 400)
+
+# --------------------------------------------------
+# SCENARIO 7: Batch with callbackUrl on httpbin form
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 7: Batch + Callback (httpbin)" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav7 = Navigate-Tab -Tab $TabId -Url "https://httpbin.org/forms/post"
+Write-Test "Navigate to httpbin.org forms" ($nav7.StatusCode -eq 200)
+
+Write-Host ""
+Write-Host "--- 7a: Batch form fill with callbackUrl ---" -ForegroundColor Yellow
+$br7 = Invoke-Api -Method POST -Path "/tasks/batch" -Body @{
+ agentId = "batch-form"
+ callbackUrl = "http://localhost:19876/hook"
+ tasks = @(
+ @{ action = "fill"; tabId = $TabId; params = @{ selector = "input[name='custname']"; text = "Jane Doe" } },
+ @{ action = "fill"; tabId = $TabId; params = @{ selector = "input[name='custtel']"; text = "555-9999" } },
+ @{ action = "click"; tabId = $TabId; params = @{ selector = "input[value='medium']" } }
+ )
+}
+Write-Test "Batch with callback returns 202" ($br7.StatusCode -eq 202)
+Write-Test "3 tasks in response" ($br7.Body.submitted -eq 3)
+
+# Verify the callback URL is stored on each task
+if ($br7.Body.tasks -and $br7.Body.tasks.Count -gt 0) {
+ $firstTaskId = $br7.Body.tasks[0].taskId
+ if ($firstTaskId) {
+ $taskDetail = Invoke-Api -Method GET -Path "/tasks/$firstTaskId"
+ Write-Test "Task has callbackUrl field" ($taskDetail.Body.callbackUrl -eq "http://localhost:19876/hook")
+ }
+}
+
+# Wait for completion
+if ($br7.Body.tasks) {
+ foreach ($bt in $br7.Body.tasks) {
+ if ($bt.taskId) { $null = Wait-TaskDone -TaskId $bt.taskId }
+ }
+}
+
+# --------------------------------------------------
+# SCENARIO 8: Single task with callbackUrl (webhook field test)
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 8: Task with callbackUrl" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav8 = Navigate-Tab -Tab $TabId -Url "https://en.wikipedia.org/wiki/Computer_science"
+Write-Test "Navigate to CS Wikipedia article" ($nav8.StatusCode -eq 200)
+
+Write-Host ""
+Write-Host "--- 8a: Submit task with callbackUrl and verify stored ---" -ForegroundColor Yellow
+$s8a = Submit-Task -AgentId "cb-agent" -Action "scroll" -Tab $TabId -Params @{ scrollY = 300 } -CallbackUrl "http://localhost:19876/webhook"
+Write-Test "Submit with callback returns 202" ($s8a.StatusCode -eq 202)
+
+$taskGet = Invoke-Api -Method GET -Path "/tasks/$($s8a.Body.taskId)"
+Write-Test "Task GET returns callbackUrl" ($taskGet.Body.callbackUrl -eq "http://localhost:19876/webhook") "callbackUrl=$($taskGet.Body.callbackUrl)"
+
+$r8a = Wait-TaskDone -TaskId $s8a.Body.taskId
+Write-Test "Callback task completed" ($r8a -ne $null -and $r8a.state -in @("done","failed")) "state=$($r8a.state)"
+
+Write-Host ""
+Write-Host "--- 8b: Task without callbackUrl has no field ---" -ForegroundColor Yellow
+$s8b = Submit-Task -AgentId "no-cb-agent" -Action "scroll" -Tab $TabId -Params @{ scrollY = 100 }
+Write-Test "Submit without callback returns 202" ($s8b.StatusCode -eq 202)
+
+$taskGet2 = Invoke-Api -Method GET -Path "/tasks/$($s8b.Body.taskId)"
+$hasCb = ($null -ne $taskGet2.Body.callbackUrl -and $taskGet2.Body.callbackUrl -ne "")
+Write-Test "Task without callback has empty/no callbackUrl" (-not $hasCb) "callbackUrl=$($taskGet2.Body.callbackUrl)"
+
+# --------------------------------------------------
+# SCENARIO 9: Multi-agent batch + metrics accuracy on GitHub Explore
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 9: Multi-Agent Batch (GitHub)" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav9 = Navigate-Tab -Tab $TabId -Url "https://github.com/explore"
+Write-Test "Navigate to GitHub Explore" ($nav9.StatusCode -eq 200)
+
+Write-Host ""
+Write-Host "--- 9a: Two agents submit batches concurrently ---" -ForegroundColor Yellow
+$metricsBefore = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics.tasksSubmitted
+
+# Agent 1 batch
+$br9a = Invoke-Api -Method POST -Path "/tasks/batch" -Body @{
+ agentId = "gh-agent-1"
+ tasks = @(
+ @{ action = "scroll"; tabId = $TabId; params = @{ scrollY = 300 } },
+ @{ action = "scroll"; tabId = $TabId; params = @{ scrollY = 200 }; priority = 1 }
+ )
+}
+Write-Test "Agent-1 batch returns 202" ($br9a.StatusCode -eq 202) "submitted=$($br9a.Body.submitted)"
+
+# Agent 2 batch
+$br9b = Invoke-Api -Method POST -Path "/tasks/batch" -Body @{
+ agentId = "gh-agent-2"
+ tasks = @(
+ @{ action = "scroll"; tabId = $TabId; params = @{ scrollY = 100 } },
+ @{ action = "hover"; tabId = $TabId; params = @{ selector = "h2" } }
+ )
+}
+Write-Test "Agent-2 batch returns 202" ($br9b.StatusCode -eq 202) "submitted=$($br9b.Body.submitted)"
+
+# Wait for all tasks
+$allIds = @()
+if ($br9a.Body.tasks) { $allIds += ($br9a.Body.tasks | ForEach-Object { $_.taskId }) }
+if ($br9b.Body.tasks) { $allIds += ($br9b.Body.tasks | ForEach-Object { $_.taskId }) }
+$allCompleted = $true
+foreach ($tid in $allIds) {
+ if ($tid) {
+ $rr = Wait-TaskDone -TaskId $tid
+ if ($rr -eq $null) { $allCompleted = $false }
+ }
+}
+Write-Test "All 4 multi-agent batch tasks completed" $allCompleted
+
+Write-Host ""
+Write-Host "--- 9b: Verify per-agent metrics isolation ---" -ForegroundColor Yellow
+$metricsAfter = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+Write-Test "Total submitted increased by >= 4" ($metricsAfter.tasksSubmitted -ge ($metricsBefore + 4))
+
+if ($metricsAfter.agents."gh-agent-1") {
+ Write-Test "gh-agent-1 submitted >= 2" ($metricsAfter.agents."gh-agent-1".submitted -ge 2)
+} else {
+ Write-Test "gh-agent-1 in agents map" $false "not found"
+}
+if ($metricsAfter.agents."gh-agent-2") {
+ Write-Test "gh-agent-2 submitted >= 2" ($metricsAfter.agents."gh-agent-2".submitted -ge 2)
+} else {
+ Write-Test "gh-agent-2 in agents map" $false "not found"
+}
+
+# --------------------------------------------------
+# SCENARIO 10: Full metrics accuracy test on DuckDuckGo
+# --------------------------------------------------
+Write-Host ""
+Write-Host "========================================" -ForegroundColor Magenta
+Write-Host " SCENARIO 10: Full Metrics (DuckDuckGo)" -ForegroundColor Magenta
+Write-Host "========================================" -ForegroundColor Magenta
+
+$nav10 = Navigate-Tab -Tab $TabId -Url "https://duckduckgo.com"
+Write-Test "Navigate to DuckDuckGo" ($nav10.StatusCode -eq 200)
+
+# Snapshot before
+$snap10before = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+
+Write-Host ""
+Write-Host "--- 10a: humanClick on search input ---" -ForegroundColor Yellow
+$s10a = Submit-Task -AgentId "ddg-agent" -Action "humanClick" -Tab $TabId -Params @{
+ selector = "input[name='q']"
+}
+Write-Test "Submit: humanClick search input" ($s10a.StatusCode -eq 202)
+$r10a = Wait-TaskDone -TaskId $s10a.Body.taskId
+Write-Test "humanClick completed" ($r10a -ne $null -and $r10a.state -in @("done","failed")) "state=$($r10a.state)"
+
+Write-Host ""
+Write-Host "--- 10b: humanType search query ---" -ForegroundColor Yellow
+$s10b = Submit-Task -AgentId "ddg-agent" -Action "humanType" -Tab $TabId -Params @{
+ selector = "input[name='q']"
+ text = "PinchTab scheduler"
+}
+Write-Test "Submit: humanType search query" ($s10b.StatusCode -eq 202)
+$r10b = Wait-TaskDone -TaskId $s10b.Body.taskId
+Write-Test "humanType completed" ($r10b -ne $null -and $r10b.state -in @("done","failed")) "state=$($r10b.state)"
+
+Write-Host ""
+Write-Host "--- 10c: Press Enter to search ---" -ForegroundColor Yellow
+$s10c = Submit-Task -AgentId "ddg-agent" -Action "press" -Tab $TabId -Params @{ key = "Enter" }
+Write-Test "Submit: press Enter" ($s10c.StatusCode -eq 202)
+$r10c = Wait-TaskDone -TaskId $s10c.Body.taskId
+Write-Test "Search submitted" ($r10c -ne $null -and $r10c.state -in @("done","failed")) "state=$($r10c.state)"
+Start-Sleep -Seconds 2
+
+Write-Host ""
+Write-Host "--- 10d: Scroll search results ---" -ForegroundColor Yellow
+$s10d = Submit-Task -AgentId "ddg-agent" -Action "scroll" -Tab $TabId -Params @{ scrollY = 500 }
+Write-Test "Submit: scroll results" ($s10d.StatusCode -eq 202)
+$r10d = Wait-TaskDone -TaskId $s10d.Body.taskId
+Write-Test "Results scroll completed" ($r10d -ne $null -and $r10d.state -in @("done","failed")) "state=$($r10d.state)"
+
+Write-Host ""
+Write-Host "--- 10e: Verify final metrics snapshot ---" -ForegroundColor Yellow
+$snap10after = (Invoke-Api -Method GET -Path "/scheduler/stats").Body.metrics
+Write-Test "tasksSubmitted increased by >= 4" ($snap10after.tasksSubmitted -ge ($snap10before.tasksSubmitted + 4))
+
+if ($snap10after.agents."ddg-agent") {
+ $ddg = $snap10after.agents."ddg-agent"
+ Write-Test "ddg-agent submitted >= 4" ($ddg.submitted -ge 4)
+ Write-Test "ddg-agent completed >= 0" ($ddg.completed -ge 0)
+} else {
+ Write-Test "ddg-agent in agents map" $false "not found"
+}
+
+# ============================================================
+# SUMMARY
+# ============================================================
+Write-Host ""
+Write-Host "============================================" -ForegroundColor Cyan
+Write-Host " RESULTS: $Pass passed, $Fail failed / $($Pass + $Fail) total" -ForegroundColor $(if ($Fail -eq 0) { "Green" } else { "Red" })
+Write-Host "============================================" -ForegroundColor Cyan
+Write-Host ""
+
+# ============================================================
+# Append results to SCHEDULER_CHANGES.md
+# ============================================================
+$mdPath = Join-Path $PSScriptRoot "..\SCHEDULER_CHANGES.md"
+if (-not (Test-Path $mdPath)) {
+ $mdPath = Join-Path (Get-Location) "SCHEDULER_CHANGES.md"
+}
+
+if (Test-Path $mdPath) {
+ $timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
+ $sep = "---"
+ $h2 = "## Phase 2 & 3 Manual Integration Test Results (Real-World)"
+ $tblHeader = "| # | Test | Status | Detail |"
+ $tblSep = "|---|------|--------|--------|"
+
+ $lines = [System.Collections.Generic.List[string]]::new()
+ $lines.Add("")
+ $lines.Add($sep)
+ $lines.Add("")
+ $lines.Add($h2)
+ $lines.Add("")
+ $lines.Add("**Run at:** $timestamp")
+ $lines.Add("**Server:** $Base")
+ $lines.Add("**Instance:** $($inst.id) (port $($inst.port))")
+ $lines.Add("**Tab:** $TabId")
+ $lines.Add("")
+ $lines.Add("### Phase 2 features tested")
+ $lines.Add("- GET /scheduler/stats endpoint structure")
+ $lines.Add("- Metrics counters (tasksSubmitted, tasksCompleted, tasksFailed, tasksCancelled, tasksExpired)")
+ $lines.Add("- Per-agent metrics isolation")
+ $lines.Add("- Dispatch latency tracking (dispatchCount, avgDispatchLatencyMs)")
+ $lines.Add("")
+ $lines.Add("### Phase 3 features tested")
+ $lines.Add("- POST /tasks/batch endpoint (real browser tasks)")
+ $lines.Add("- Batch validation (missing agentId, empty tasks, oversized batch)")
+ $lines.Add("- callbackUrl field on single tasks and batch tasks")
+ $lines.Add("- Multi-agent batch submission with metrics accuracy")
+ $lines.Add("")
+ $lines.Add("### Websites tested")
+ $lines.Add("- Wikipedia (en.wikipedia.org) -- scroll, click, hover, metrics tracking")
+ $lines.Add("- Hacker News (news.ycombinator.com) -- click story, scroll, dispatch latency")
+ $lines.Add("- GitHub (github.com/explore) -- multi-agent batch, per-agent metrics")
+ $lines.Add("- httpbin.org (forms) -- batch form fill with callbackUrl")
+ $lines.Add("- DuckDuckGo (duckduckgo.com) -- humanClick, humanType, full metrics snapshot")
+ $lines.Add("")
+ $lines.Add("### Action kinds exercised")
+ $lines.Add("scroll, click, hover, fill, press, humanClick, humanType")
+ $lines.Add("")
+ $lines.Add($tblHeader)
+ $lines.Add($tblSep)
+
+ $i = 1
+ foreach ($r in $Results) {
+ $detail = if ($r.Detail) { ($r.Detail -replace '\|', '/') } else { "" }
+ if ($detail.Length -gt 80) { $detail = $detail.Substring(0, 80) + "..." }
+ $lines.Add("| $i | $($r.Test) | $($r.Status) | $detail |")
+ $i++
+ }
+
+ $lines.Add("")
+ $lines.Add("**Total: $Pass passed, $Fail failed / $($Pass + $Fail) tests**")
+ $lines.Add("")
+
+ Add-Content -Path $mdPath -Value ($lines -join "`n") -Encoding UTF8
+ Write-Host "Results appended to $mdPath" -ForegroundColor Green
+} else {
+ Write-Host "SCHEDULER_CHANGES.md not found - skipping MD update." -ForegroundColor Yellow
+}
+
+# Exit code
+if ($Fail -gt 0) { exit 1 } else { exit 0 }