Skip to content

refactor(gateway): share connection lifecycle across transports - #145950

Merged
vincentkoc merged 3 commits into
mainfrom
repair/pr-142931-clean-replacement-20260912
Sep 13, 2026
Merged

vincentkoc merged 3 commits into
mainfrom
repair/pr-142931-clean-replacement-20260912

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

Related: #142916
Replaces: #142931

What Problem This Solves

Gateway connection admission, request dispatch, and cleanup were coupled to
WebSocket-specific I/O, preventing another transport from reusing the existing
authenticated lifecycle safely.

Why This Change Was Made

Extract the existing connection lifecycle into one transport-neutral owner while
keeping WebSocket receive, receiver limits, heartbeat, socket errors, and
physical liveness in the WebSocket adapter.

The repair preserves the keepalive behavior from
#145191, including passing the underlying
socket to startWebSocketKeepalive. It adds no endpoint, config, protocol, or
persistence surface.

The ancestry-preserving refresh includes
#146102 and
#147028.

User Impact

No intended user-visible behavior change. The Gateway gains one reusable
connection boundary without duplicating authentication, registration, request
dispatch, or disconnect cleanup.

Evidence

  • Refreshed head: ceda70dd6ce0e069ad1a6a9ab28ed4c77b008250
  • Exact reviewed merge base: 060e856e5f9df245d63c98990fcb47e18108c6b9
  • Refresh parents: 7b0a779bb1eb1cad1f6789688ecc367ed5fa814c and
    060e856e5f9df245d63c98990fcb47e18108c6b9
  • Refreshed scope: 25 files; stable aggregate patch ID
    aac1da4a5893b524768c29bca2d4111847297d95
  • All 16 production blobs are byte-identical to the reviewed source head. The
    patch ID changed from d620e013d1321e228ec7d747b10c9ed51cfb47cf
    only because four test/baseline files also moved on main; every per-file
    addition/deletion count is unchanged.
  • Production: +870/-776, net +94. The 657-line shared lifecycle owner replaces
    roughly 660 WebSocket-owned lines; the remaining growth is the transport
    contract, adapter wiring, and receiver extraction.
  • Tests: +231/-20, net +211.
  • Assertion baseline: +2/-2, retaining the reviewed
    node-registry.ts 5->4 and ws-connection.ts 3->1 reductions.
  • git diff --check passed on the refreshed head.

Focused proof command:

node scripts/run-vitest.mjs \
  src/gateway/server/connection.test.ts \
  src/gateway/server/ws-connection.test.ts \
  src/gateway/server/ws-connection/request-start.test.ts \
  src/gateway/server/ws-connection/request-start.server.test.ts \
  src/gateway/server/ws-connection/message-handler.control-ui-build-admission.test.ts \
  src/gateway/server/ws-connection/message-handler.post-connect-health.test.ts \
  src/gateway/server/ws-connection/message-handler.suspension-admission.test.ts \
  src/gateway/node-registry.test.ts \
  src/gateway/server.node-shutdown.test.ts \
  src/gateway/server-import-boundary.test.ts \
  src/gateway/server.public-worker-ingress.test.ts

Result on source head 7b0a779b: 11 test files passed, 291 tests passed. The
refreshed head preserves the production blobs and exact per-file delta; exact-head
hosted CI and ClawSweeper remain required before landing.

Scope Boundary

This PR adds no HTTPS/watch endpoint. It does not satisfy or close
#142916 and leaves that issue's later
security/native holds untouched.

@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Sep 12, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review September 12, 2026 12:10
@vincentkoc vincentkoc self-assigned this Sep 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 9:19 AM ET / 13:19 UTC (Revision 6).

ClawSweeper review

What this changes

Moves Gateway connection admission, request dispatch, and disconnect cleanup into a shared owner while retaining physical WebSocket handling in its adapter.

Merge readiness

✅ Ready for maintainer review

This remains a useful, distinct extraction that current main does not provide. No actionable introduced defect was found, and the refreshed production files match the previously reviewed head. The maintainer-authored PR should remain open for normal landing checks.

Priority: P2
Reviewed head: ceda70dd6ce0e069ad1a6a9ab28ed4c77b008250

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent extraction with focused lifecycle coverage and no actionable findings; production identity preserves the prior review's scope.
Proof confidence 🌊 off-meta tidepool Not applicable: The MEMBER-authored internal extraction is exempt from the external-contributor proof gate and does not materially change authority. Reported focused tests cover the shared owner and physical WebSocket path, but are not represented as a new live deployment run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The MEMBER-authored internal extraction is exempt from the external-contributor proof gate and does not materially change authority. Reported focused tests cover the shared owner and physical WebSocket path, but are not represented as a new live deployment run.
Evidence reviewed 9 items Applicable repository policy: Read the full root and Gateway AGENTS.md files and applied their single-owner, lifecycle, lazy-loading, and validation guidance. No applicable deeper AGENTS.md or maintainer-notes directory was found.
Current main still owns the lifecycle inside WebSocket ingress: Current main has no server/connection.ts and retains admission, registration, heartbeat hookup, dispatch attachment, and tracked cleanup in ws-connection.ts. The latest supplied release commit likewise has no shared connection module.
Shared owner preserves registration and retirement ordering: The extraction retains immediate connection-signal abortion, one-client registration, worker replacement invalidation, node lifecycle drainage, and tracked asynchronous disconnect cleanup. Comparing the extracted owner with the pinned base showed relocation and adapter injection rather than new authorization policy.
Findings None None.
Security None None.

How this fits together

Gateway connections carry requests from operator clients, nodes, and workers into OpenClaw. The connection lifecycle handles registration and cleanup, while the WebSocket adapter supplies receive limits, heartbeat monitoring, and transport events.

flowchart TD
  A[Operator and node clients] --> B[WebSocket adapter]
  B --> C[Shared connection lifecycle]
  C --> D[Authentication and registration]
  D --> E[Gateway request dispatch]
  B --> F[Worker admission and dispatch]
  C --> G[Disconnect and shutdown cleanup]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +94, Tests +211, Other 0. Total +305 across 25 files.

View PR surface stats
Area Files Added Removed Net
Source 16 870 776 +94
Tests 8 231 20 +211
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 25 1103 798 +305

Review metrics

Metric Value Why it matters
Production versus test growth Production net +94 lines; tests net +211 lines Production growth is explained by the transport contract and adapter wiring; the shared lifecycle replaces the existing WebSocket-owned implementation.

Root-cause cluster

Relationship: canonical
Canonical: #145950
Summary: This is the active connection-extraction replacement; the broader watch feature remains separate.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one shared connection lifecycle with transport-specific I/O adapters, leaving additional endpoints and watch capabilities to separately reviewed work.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this PR extracts an existing lifecycle rather than reporting a behavioral defect; runtime tests were not executed during this read-only review.

Is this the best way to solve the issue?

Yes. The diff moves the existing owner and injects transport operations without duplicating authentication, changing wire contracts, or adding a competing registration path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 0a7b7fecfd7f.

Labels

Label justifications:

  • P2: This is a bounded Gateway architecture improvement supporting planned transport work without an intended user-visible behavior change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The MEMBER-authored internal extraction is exempt from the external-contributor proof gate and does not materially change authority. Reported focused tests cover the shared owner and physical WebSocket path, but are not represented as a new live deployment run.

Evidence

What I checked:

  • Applicable repository policy: Read the full root and Gateway AGENTS.md files and applied their single-owner, lifecycle, lazy-loading, and validation guidance. No applicable deeper AGENTS.md or maintainer-notes directory was found. (src/gateway/AGENTS.md:1, ceda70dd6ce0)
  • Current main still owns the lifecycle inside WebSocket ingress: Current main has no server/connection.ts and retains admission, registration, heartbeat hookup, dispatch attachment, and tracked cleanup in ws-connection.ts. The latest supplied release commit likewise has no shared connection module. (src/gateway/server/ws-connection.ts:125, 0a7b7fecfd7f)
  • Shared owner preserves registration and retirement ordering: The extraction retains immediate connection-signal abortion, one-client registration, worker replacement invalidation, node lifecycle drainage, and tracked asynchronous disconnect cleanup. Comparing the extracted owner with the pinned base showed relocation and adapter injection rather than new authorization policy. (src/gateway/server/connection.ts:261, ceda70dd6ce0)
  • WebSocket receiver and liveness cutover: The adapter supplies the original socket to both receiver handoff and startWebSocketKeepalive, including the underlying upgrade socket. It installs the physical ping/pong capability before node registration; connect finalization still validates receive limits before registration and activates them afterward. (src/gateway/server/ws-connection.ts:77, ceda70dd6ce0)
  • Review continuity and validation scope: Compared Git blob identities for all 16 introduced production files between 7b0a779 and the reviewed head: all matched. The prior completed review contained no findings. The captured PR body reports 291 passing tests across 11 files on that earlier source head; this review inspected the relevant test changes but did not execute tests or builds. The pinned diff whitespace check passed. (src/gateway/server/connection.test.ts:18, ceda70dd6ce0)
  • Existing behavior contracts and focused coverage: Transport documentation defines preauth limits, authenticated scheduling, shutdown settlement, and queued-ping semantics. The new connection test covers competing connect frames, delayed or failed hello writes, and cleanup ordering; the real Gateway shutdown test additionally verifies that node connectivity performs a physical WebSocket ping. (src/gateway/server.node-shutdown.test.ts:167, ceda70dd6ce0)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-12T12:17:30.649Z sha d44f664 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T07:45:01.240Z sha d44f664 :: blocked before merge. :: none
  • reviewed 2026-09-13T09:13:27.575Z sha f7279d8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T11:14:51.780Z sha f7279d8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T12:53:07.719Z sha 7b0a779 :: needs maintainer review before merge. :: none

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc
vincentkoc force-pushed the repair/pr-142931-clean-replacement-20260912 branch from d44f664 to f7279d8 Compare September 13, 2026 08:45
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

The branch was reconstructed as one signed commit on current main without
changing the reviewed 25-file scope.

  • head: f7279d8efc901e9437e1ee7867f20c01e6aaf2ac
  • base: 912685f442286233fbbd40762482d98598299497
  • focused suites: 52/52 passed
  • assertion-safety ratchet and git diff --check: passed
  • production: +870/-776; tests: +231/-20; baseline: +2/-2

Please review the exact replacement head.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

* temp/pr-145950: (101 commits)
  refactor(memory-wiki): share freshness result construction (#146935)
  improve(gateway): use metadata projection for presence (#146817)
  test(agents): reuse complete Responses model fixtures (#147015)
  fix(sessions): align the reclamation-memory test with the archive session owner (#147028)
  refactor(terminal): simplify copy-sensitive token checks (#146934)
  refactor(media): remove duplicate spaced path fallback (#146933)
  refactor(cli): reuse command-group names (#146893)
  improve(plugins): reduce JavaScript generation capture work (#146993)
  test: align plugin fixtures with current runtime contracts (#147000)
  refactor(browser): separate session tab tracking from cleanup (#146973)
  fix(tests): make systemd clock fixtures private (#146990)
  fix(linux): retire sleep guards when logind disconnects (#146046)
  refactor(matrix): share draft fallback delivery (#144840)
  fix(sessions): preserve cross-agent replies after reload (#146799)
  test(models): cover quota recovery during catalog discovery (#146708)
  fix(macos): recover browser sign-in when no browser opens (#146787)
  fix(process): prevent one-shot agents exiting while polling (#144268)
  fix(status): label the session inventory as stored (#146979)
  fix: avoid repeated background reads while loading chat (#146953)
  refactor(ui): narrow Skill Workshop proposal context (#146977)
  ...
@vincentkoc
vincentkoc merged commit b652eeb into main Sep 13, 2026
187 checks passed
@vincentkoc
vincentkoc deleted the repair/pr-142931-clean-replacement-20260912 branch September 13, 2026 13:26
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 13, 2026
* temp/pr-137049: (110 commits)
  improve: reduce GitHub OAuth maintenance work for large agent rosters (#147021)
  fix(test): avoid settings lock writer startup timeouts (#147029)
  fix(update): correct backup guidance and cover incident regressions (#147023)
  refactor(gateway): share connection lifecycle across transports (#145950)
  refactor(telegram): share HTML text escaping (#146936)
  perf(build): reduce disk use in UI performance checks (#146687)
  refactor(memory-wiki): share freshness result construction (#146935)
  improve(gateway): use metadata projection for presence (#146817)
  test(agents): reuse complete Responses model fixtures (#147015)
  fix(sessions): align the reclamation-memory test with the archive session owner (#147028)
  refactor(terminal): simplify copy-sensitive token checks (#146934)
  refactor(media): remove duplicate spaced path fallback (#146933)
  refactor(cli): reuse command-group names (#146893)
  improve(plugins): reduce JavaScript generation capture work (#146993)
  test: align plugin fixtures with current runtime contracts (#147000)
  refactor(browser): separate session tab tracking from cleanup (#146973)
  fix(tests): make systemd clock fixtures private (#146990)
  fix(linux): retire sleep guards when logind disconnects (#146046)
  refactor(matrix): share draft fallback delivery (#144840)
  fix(sessions): preserve cross-agent replies after reload (#146799)
  ...
vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit '0ac8a700e43efceef73d92fe8e50b185819e38ad': (27 commits)
  test(acpx): prove targeted turn cancellation (#137049)
  fix(ci): honor realtime meeting live-test opt-in (#147044)
  improve: reduce heartbeat enrollment work for large fleets (#147055)
  fix(gateway): install despite stale Linux session bus addresses (#146569)
  chore(i18n): refresh native locales (#147025)
  fix: avoid Gateway reinstalls when macOS service inspection is inconclusive (#146880)
  fix(pairing): QR setup rejects trusted-proxy gateways without a shared secret (#147036)
  fix(update): bound activation and accept slow Windows identity reads (#147019)
  perf(accounts): avoid materializing avatars for owner checks (#147032)
  improve(status): report external and ArrayBuffer memory (#141902)
  fix(update): preserve linked plugins during post-core sync (#147009)
  fix(channels): keep replies working after hot config reloads (#147001)
  refactor(gateway): defer worker transcript runtime loading (#143495)
  improve: reduce GitHub OAuth maintenance work for large agent rosters (#147021)
  fix(test): avoid settings lock writer startup timeouts (#147029)
  fix(update): correct backup guidance and cover incident regressions (#147023)
  refactor(gateway): share connection lifecycle across transports (#145950)
  refactor(telegram): share HTML text escaping (#146936)
  perf(build): reduce disk use in UI performance checks (#146687)
  refactor(memory-wiki): share freshness result construction (#146935)
  ...

# Conflicts:
#	src/config/sessions/session-accessor.sqlite-reclamation-memory.test.ts
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…claw#145950)

* refactor(gateway): share connection lifecycle across transports

* chore: refresh pull request source ref
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant