Skip to content

Fix agent command connection handling - #81

Merged
cvsloane merged 5 commits into
mainfrom
codex/connection-hardening
May 19, 2026
Merged

cvsloane merged 5 commits into
mainfrom
codex/connection-hardening

Conversation

@cvsloane

@cvsloane cvsloane commented May 8, 2026 •

Copy link
Copy Markdown
Owner

Summary\n- add websocket ping/pong deadlines for agentd\n- report idle Postgres pool errors through the control-plane logger\n- include project status update already present locally\n\n## Verification\n- go test ./... (agents/agentd)\n- pnpm --filter @agent-command/control-plane typecheck\n- pnpm --filter @agent-command/control-plane build

Summary by CodeRabbit

  • New Features

    • WebSocket connections gain keepalive (periodic pings and pong handling) for more reliable live connections.
    • Database pool errors can be reported via a configurable handler for better observability.
    • Playwright dashboard test configuration and test scripts added for UI smoke testing.
  • Bug Fixes

    • Outgoing message sends now respect write timeouts to avoid indefinite blocking.
  • Tests & CI

    • Added unit and Playwright smoke tests; CI runs tests and installs browser dependencies.
  • Documentation

    • Project status metadata and activity snapshot refreshed.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 73024487-5352-4e23-b713-d29c1993e8c7

📥 Commits

Reviewing files that changed from the base of the PR and between fb0ddab and 3045ebf.

📒 Files selected for processing (1)
  • project_status.md

📝 Walkthrough

Walkthrough

Adds WebSocket keepalive (ping/pong) with deadlines and separate reader/pinger goroutines, applies write deadlines to outbound sends, exposes a Postgres pool error reporter wired to the control-plane logger, adds CI/test scripts and Playwright smoke tests, includes schema and auth unit tests, and refreshes project status metadata.

Changes

WebSocket Keepalive Enhancement

Layer / File(s) Summary
Timing Constants
agents/agentd/internal/ws/client.go
Adds writeWait, pongWait, and pingPeriod constants for WebSocket deadlines and keepalive intervals.
Connection Setup with Goroutines
agents/agentd/internal/ws/client.go
Connect() sets read deadline and pong handler on the dialed connection, stores it, and launches reader(conn) and pinger(conn) goroutines.
Reader Refactoring with Stable Cleanup
agents/agentd/internal/ws/client.go
Reader accepts a concrete *websocket.Conn; deferred cleanup closes and clears c.conn only if it still matches, then triggers reconnection.
Periodic Pinger with Deadlines
agents/agentd/internal/ws/client.go
pinger(conn) ticks at pingPeriod, verifies connection identity, sets a write deadline, sends ping frames, and closes the connection on ping write failure.
Write Deadlines on Outbound Messages
agents/agentd/internal/ws/client.go
Send() and ResendQueued() set writeWait before WebSocket writes to avoid indefinite blocking.

Postgres Pool Error Reporting

Layer / File(s) Summary
Pool Error Handler and Reporter State
services/control-plane/src/db/index.ts
Adds pool.on('error') listener and poolErrorReporter state to route idle-client errors to a configured reporter or console.error.
Error Reporter Configuration Export
services/control-plane/src/db/index.ts
Exports setPoolErrorReporter() to register an external error-reporting callback.
Control-Plane Server Wiring
services/control-plane/src/index.ts
start() calls db.setPoolErrorReporter() with a callback that logs unexpected idle client errors via app.log.error.

Project Status Metadata Refresh

Layer / File(s) Summary
Status Document Metadata and Activity
project_status.md
Updates "Last updated" timestamp, removes active tmux session details, refreshes recent commits, "Files Changed Recently", and branch info.

CI and Package Scripts

Layer / File(s) Summary
CI workflow changes
.github/workflows/ci.yml
Adds CI steps to run tests, install Playwright Chromium, and execute dashboard smoke tests.
Top-level and service package scripts
package.json, packages/ac-schema/package.json, services/control-plane/package.json
Adds test:ci, test:smoke:dashboard, test scripts and adds vitest devDependency where applicable.

Playwright and Smoke Tests

Layer / File(s) Summary
Playwright dashboard config
playwright.dashboard.config.ts
Adds Playwright config exporting default defineConfig for dashboard smoke tests with conditional webServer and environment wiring.
Dashboard smoke tests
tests/smoke/dashboard.spec.ts
Playwright smoke suite that mocks control-plane APIs, automates sign-in via access code, and verifies key pages render after sign-in.

Schema and Control-Plane Unit Tests

Layer / File(s) Summary
ac-schema tests
packages/ac-schema/tests/core-workflows.test.ts
Adds Vitest tests for approval, memory, automation, and work-item schema validations and defaults.
control-plane auth tests
services/control-plane/tests/auth.test.ts
Adds auth tests covering RBAC, JWT verification, request-token precedence, and service-token length-mismatch handling.
sequenceDiagram
  participant Client
  participant Dialer
  participant Conn
  participant Reader
  participant Pinger
  Client->>Dialer: dial connection
  Dialer-->>Conn: connection established
  Client->>Conn: set read deadline and pong handler
  Client->>Reader: start reader(conn)
  Client->>Pinger: start pinger(conn)
  loop every pingPeriod
    Pinger->>Conn: set write deadline and send ping
    Conn-->>Pinger: pong or error
  end
  Reader->>Conn: read messages and reset read deadline
  alt read error or ping/write fail
    Reader->>Client: trigger reconnect
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰
I ping the net to keep hearts near,
Deadlines hush the stalled-connection fear,
Loggers stand ready, listening clear,
Tests awake the dashboard cheer,
A hopping rabbit keeps the lines sincere.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix agent command connection handling' directly and clearly summarizes the main change: WebSocket keepalive improvements and connection liveness handling in the agentd client, which is the primary technical change in the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/connection-hardening

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
services/control-plane/src/db/index.ts (1)

33-47: 💤 Low value

Pool error wiring looks correct; consider isolating reporter throws.

The registration order (listener at module load, setter to swap implementation later) is sound, and the fallback to console.error covers the startup window before setPoolErrorReporter is invoked.

One small hardening: if a future reporter throws synchronously, the throw escapes the pool.on('error') listener as an uncaught exception. Wrapping the call defends against that without changing current behavior.

♻️ Optional defensive wrap
 pool.on('error', (error) => {
   if (poolErrorReporter) {
-    poolErrorReporter(error);
-    return;
+    try {
+      poolErrorReporter(error);
+    } catch (reporterError) {
+      console.error('[db] Pool error reporter threw:', reporterError, 'original:', error);
+    }
+    return;
   }
   console.error('[db] Unexpected idle Postgres client error:', error);
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/control-plane/src/db/index.ts` around lines 33 - 47, The pool
'error' handler currently calls poolErrorReporter(error) directly which can let
exceptions thrown by the reporter escape; wrap the reporter invocation inside a
try/catch in the pool.on('error') callback (still call console.error fallback on
errors) so any synchronous throw from poolErrorReporter is caught and logged
instead of crashing the process; update the handler around the pool.on('error')
listener and keep setPoolErrorReporter and poolErrorReporter semantics
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@services/control-plane/src/db/index.ts`:
- Around line 33-47: The pool 'error' handler currently calls
poolErrorReporter(error) directly which can let exceptions thrown by the
reporter escape; wrap the reporter invocation inside a try/catch in the
pool.on('error') callback (still call console.error fallback on errors) so any
synchronous throw from poolErrorReporter is caught and logged instead of
crashing the process; update the handler around the pool.on('error') listener
and keep setPoolErrorReporter and poolErrorReporter semantics unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 77bb7012-de91-4705-bee0-167ea27a6544

📥 Commits

Reviewing files that changed from the base of the PR and between 5e948fc and 1179ad3.

📒 Files selected for processing (4)
  • agents/agentd/internal/ws/client.go
  • project_status.md
  • services/control-plane/src/db/index.ts
  • services/control-plane/src/index.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
services/control-plane/package.json (1)

13-13: ⚡ Quick win

Declare vitest in package devDependencies to avoid implicit workspace coupling.

"test": "vitest run" currently depends on root-level tooling resolution. Add vitest to @agent-command/control-plane devDependencies so the package remains self-contained and CI behavior is stable across pnpm/turbo modes.

Proposed diff
   "devDependencies": {
     "`@types/bcryptjs`": "^3.0.0",
     "`@types/node`": "^20.10.0",
     "`@types/pg`": "^8.11.0",
     "tsx": "^4.19.0",
-    "typescript": "^5.3.0"
+    "typescript": "^5.3.0",
+    "vitest": "^4.1.6"
   }

The same issue exists in packages/ac-schema/package.json—add "vitest": "^4.1.6" there as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/control-plane/package.json` at line 13, The package's test script
("test": "vitest run") relies on a workspace root tool; add vitest to the
package devDependencies so the package is self-contained: in
services/control-plane/package.json add a devDependency entry "vitest": "^4.1.6"
and do the same in packages/ac-schema/package.json (ensure version "^4.1.6"),
then run a local install/check to verify the test script resolves vitest from
the package's own devDependencies.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@services/control-plane/package.json`:
- Line 13: The package's test script ("test": "vitest run") relies on a
workspace root tool; add vitest to the package devDependencies so the package is
self-contained: in services/control-plane/package.json add a devDependency entry
"vitest": "^4.1.6" and do the same in packages/ac-schema/package.json (ensure
version "^4.1.6"), then run a local install/check to verify the test script
resolves vitest from the package's own devDependencies.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 23fc6da8-975f-4df8-85bf-dae844171d1e

📥 Commits

Reviewing files that changed from the base of the PR and between 3290d70 and fb0ddab.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • .github/workflows/ci.yml
  • package.json
  • packages/ac-schema/package.json
  • packages/ac-schema/tests/core-workflows.test.ts
  • playwright.dashboard.config.ts
  • services/control-plane/package.json
  • services/control-plane/tests/auth.test.ts
  • tests/smoke/dashboard.spec.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/ac-schema/package.json

@cvsloane
cvsloane merged commit 3045ebf into main May 19, 2026
5 checks passed
@cvsloane
cvsloane deleted the codex/connection-hardening branch September 27, 2026 03:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant