Skip to content

refactor(browser): simplify relay lifecycle helpers - #133706

Merged
steipete merged 1 commit into
mainfrom
steipete/mystifying-swirles-5c98cd
Aug 31, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/mystifying-swirles-5c98cd

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Related: standalone browser relay and native-host wake-up.

Additional instructions

Maintainer-requested cleanup. This same-repository branch remains editable by maintainers.

What Problem This Solves

The landed standalone browser relay and adjacent action handling contain repeated lifecycle bookkeeping and action wrappers that make their ownership boundaries harder to maintain. This follows an explicit maintainer request to simplify that code and reduce production LOC.

The focused baseline also exposed a flaky Gateway ingress fixture: it assumed corked TCP writes would arrive entirely in Node's WebSocket upgrade head, but received zero head bytes instead of the expected 243.

Why This Change Was Made

Keep the existing owners and remove duplication: the owner client alone enforces its adopted profile admission; retirement and disconnection share terminal invalidation without conflating acknowledgement; immutable RPC result schemas are reused; unused retained owner metadata is removed; target announcements receive explicit recipient snapshots; daemon completion uses the existing deferred helper; existing-session actions bind their navigation guard once.

The ingress fixture supplies its encoded bytes at the existing production upgrade-head boundary, as the pre-auth boundary tests already do. It still exercises real HTTP/WebSocket authentication, buffered-frame consumption, hello promotion and inventory publication. Node's OutgoingMessage.end() fully uncorks the socket, and TCP writes cannot guarantee parser head boundaries. No retry, timeout increase or weakened assertion was added.

User Impact

No intended user-visible behavior change. Authentication, live-key checks, checks across asynchronous boundaries, reference and registration identity, cleanup acknowledgements, recipient ordering, action error precedence and cancellation remain unchanged. No new configuration, protocol, storage, dependency or public SDK surface.

Production: +161/-236, net -75 lines across six files. Tests/support: +34/-45, net -11 lines in one file. This does not claim to repair separately tracked correctness issues in unchanged relay code.

Evidence

  • Untouched baseline: 112 passed, 1 failed. The failure was the borrowed legacy upgrade-head fixture described above.
  • After cleanup and deterministic fixture repair: 203 passed, 0 failed, 0 pending across 19 focused files. Coverage includes owned/borrowed relay bootstrap, profile/key drift, retirement, reference fencing, Gateway ingress, announcement/creation, daemon shutdown and action/navigation guards.
  • Complete changed-scope checks passed: formatting, production/test types, lint, doctor contracts, dependency/export and ownership guards, and import cycles. No skip override.
  • Full build passed with unchanged source and no ineffective-dynamic-import diagnostic.
  • Four independent cleanup reviews and a final quality/equivalence review completed. Fresh managed Codex autoreview of the uncommitted diff at P0 is scoped-clean with no findings. Exact-head CI will be verified before native preparation and merge.

This is a bounded behavior-preserving refactor. No operator browser/Gateway was touched, no new installed/live-browser claim is made, and no visual behavior changed.

Exact local validation commands
OPENCLAW_VITEST_MAX_WORKERS=4 node scripts/run-vitest.mjs \
  extensions/browser/src/browser/extension-relay/owner-auth-client.test.ts \
  extensions/browser/src/browser/extension-relay/owner-server.test.ts \
  extensions/browser/src/browser/extension-relay/owner-connection.integration.test.ts \
  extensions/browser/src/browser/extension-relay/relay-coexistence.integration.test.ts \
  extensions/browser/src/browser/extension-relay/gateway-relay-route.integration.test.ts \
  extensions/browser/src/browser/extension-relay/gateway-relay-ingress.integration.test.ts \
  extensions/browser/src/browser/extension-relay/relay-server.auth-v2.test.ts \
  extensions/browser/src/browser/extension-relay/relay-lifecycle.test.ts \
  extensions/browser/src/browser/extension-relay/relay-bootstrap.integration.test.ts \
  extensions/browser/src/browser/pw-session.pinned-transport.test.ts \
  extensions/browser/src/browser/server-context.extension-readiness.test.ts \
  extensions/browser/src/browser/relay-daemon.test.ts \
  extensions/browser/src/browser/extension-relay-daemon-spawn.test.ts \
  extensions/browser/src/browser/extension-install-layout.test.ts \
  extensions/browser/src/browser/extension-relay/relay-bridge.test.ts \
  extensions/browser/src/browser/extension-relay/relay-targets.test.ts \
  extensions/browser/src/browser/extension-relay/relay-bridge.cleanup.test.ts \
  extensions/browser/src/browser/relay-daemon.shutdown.test.ts \
  extensions/browser/src/browser/routes/agent.act.existing-session-navigation-guard.test.ts \
  --reporter=default --reporter=json --outputFile=.artifacts/relay-simplify-20260831/after-vitest.json
node scripts/check-changed.mjs --timed -- \
  extensions/browser/src/browser/extension-relay/gateway-relay-route.integration.test.ts \
  extensions/browser/src/browser/extension-relay/owner-client.ts \
  extensions/browser/src/browser/extension-relay/relay-access.ts \
  extensions/browser/src/browser/extension-relay/relay-bridge.ts \
  extensions/browser/src/browser/extension-relay/relay-lifecycle.ts \
  extensions/browser/src/browser/relay-daemon.ts \
  extensions/browser/src/browser/routes/agent.act.ts
pnpm build
git diff --check

Remove duplicate profile admission and terminal handling, reuse RPC result
schemas and deferred completion, and make announcement recipients and
request-local action guards explicit. Preserve authentication, asynchronous
ownership checks, cleanup acknowledgements, and action error precedence.

Make the Gateway upgrade-head fixture deterministic at its existing input
boundary instead of depending on TCP coalescing. Keep its assertions.

Maintainer-requested follow-up to the standalone relay in #128379.
Production LOC -75; test LOC -11. Validated with 203 focused tests, changed
checks, full build, and fresh scoped-clean Codex autoreview at P0.
@steipete steipete self-assigned this Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 9:58 PM ET / August 31, 2026, 01:58 UTC.

ClawSweeper review

What this changes

Refactors browser relay lifecycle and existing-session action helpers while making the Gateway upgrade-head integration fixture deterministic.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open. Current main does not contain this maintainer-requested browser-relay cleanup, and the introduced changes preserve the existing lifecycle lease, CDP recipient, and navigation-guard boundaries; normal maintainer approval and exact-head CI completion remain required.

Priority: P3
Reviewed head: 626ca3dc158871e8007412a7a5a9feb5adcd9d3e
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a focused net-reducing refactor with no identified correctness or security finding.
Proof confidence 🌊 off-meta tidepool Not applicable: This same-repository MEMBER PR is a bounded internal refactor with no claimed user-visible behavior change; its body records focused validation, but no external-contributor proof gate applies.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This same-repository MEMBER PR is a bounded internal refactor with no claimed user-visible behavior change; its body records focused validation, but no external-contributor proof gate applies.
Evidence reviewed 6 items Single lifecycle authority remains intact: The lifecycle creates the profile-current closure, installs it on the owner client before registry registration, and the client invokes it first whenever borrowed access is read.
Borrowed access remains fenced across connection work: The consumer rechecks the registry identity after establishing borrowed CDP access and closes the connection if the relay changed.
Action error and navigation ordering is preserved: The request-local wrapper still executes the action, runs the post-interaction navigation check, and only then rethrows an action failure; route-boundary tests cover guarded actions and blocked newly opened tabs.
Findings None None.
Security None None.

How this fits together

The browser plugin accepts extension relay connections and exposes authenticated CDP access to Gateway browser actions. Relay lifecycle state controls whether Gateway owns or borrows that connection, while existing-session actions apply navigation policy after browser interaction.

flowchart LR
  Extension[Browser extension] --> Relay[Extension relay]
  Gateway[Gateway browser service] --> Lifecycle[Relay lifecycle]
  Lifecycle --> Relay
  Relay --> CDP[Authenticated CDP clients]
  Agent[Agent browser action] --> Guard[Navigation guard]
  Guard --> CDP
Loading

Decision needed

Question Recommendation
Should this maintainer-requested browser-relay refactor merge after the exact-head required checks complete? Merge after checks: Accept the behavior-preserving cleanup once the exact PR head has green required checks.

Why: The PR is maintainer-authored and carries the protected maintainer label, so repository policy requires explicit maintainer handling even though no source-level defect was found.

Before merge

  • Resolve merge risk (P1) - Exact-head CI was still in progress in the captured review state, so this review is not a merge-ready signal.
  • Complete next step (P2) - The protected maintainer label and in-progress exact-head checks require normal browser-owner merge handling rather than automated repair.
Agent review details

Security

None.

PR surface

Source -75, Tests -11. Total -86 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 6 161 236 -75
Tests 1 34 45 -11
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 195 281 -86

Review metrics

Metric Value Why it matters
Production versus test LOC production +161/-236 (net -75); tests +34/-45 (net -11) The branch reduces production helper surface while retaining a focused integration-fixture adjustment.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the owner client as the single profile-lease enforcement point and land the cleanup once the browser owner accepts it and exact-head checks are green.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Retain the owner client as the single profile-lease enforcement point and land the cleanup once the browser owner accepts it and exact-head checks are green.

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

Not applicable: this PR is a requested refactor, not a report of a current user-facing defect; the fixture change is source-scoped and its claimed test run was not independently executed in this read-only review.

Is this the best way to solve the issue?

Yes. Consolidating the duplicate registry check into the already-adopted owner-client lease keeps one canonical lifecycle authority without changing public configuration, protocol, or storage behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c29f34dc5312.

Labels

Label justifications:

  • P3: This is a behavior-preserving maintainability refactor with no intended user-visible 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: This same-repository MEMBER PR is a bounded internal refactor with no claimed user-visible behavior change; its body records focused validation, but no external-contributor proof gate applies.

Evidence

What I checked:

  • Single lifecycle authority remains intact: The lifecycle creates the profile-current closure, installs it on the owner client before registry registration, and the client invokes it first whenever borrowed access is read. (extensions/browser/src/browser/extension-relay/relay-lifecycle.ts:247, 626ca3dc1588)
  • Borrowed access remains fenced across connection work: The consumer rechecks the registry identity after establishing borrowed CDP access and closes the connection if the relay changed. (extensions/browser/src/browser/pw-session-connection.ts:486, 626ca3dc1588)
  • Action error and navigation ordering is preserved: The request-local wrapper still executes the action, runs the post-interaction navigation check, and only then rethrows an action failure; route-boundary tests cover guarded actions and blocked newly opened tabs. (extensions/browser/src/browser/routes/agent.act.ts:532, 626ca3dc1588)
  • CDP announcement recipients are unchanged in meaning: The bridge now receives explicit recipient snapshots, while the auto-attach and create-target callers construct the same initiating-client or auto-attach-client sets as before. (extensions/browser/src/browser/extension-relay/relay-bridge.ts:610, 626ca3dc1588)
  • Current main has not superseded this cleanup: There is no diff in the six production browser paths between the PR base and fetched current main, so main retains the pre-refactor implementation. (c29f34dc5312)
  • Related feature provenance: The surrounding standalone-relay feature was merged as the related PR, establishing this as a follow-up cleanup rather than a duplicate implementation. (ebca214d87b6)

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Wait for the exact-head required checks to complete successfully before merge.

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 (1 earlier review cycle)
  • reviewed 2026-08-31T01:47:33.970Z sha 626ca3d :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review August 31, 2026 01:52
@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready verification for 626ca3dc158871e8007412a7a5a9feb5adcd9d3e.

This is the explicitly requested maintainer cleanup: production +161/-236, net -75 lines; tests/support +34/-45, net -11. It retains the owner client as the single adopted profile-lease enforcement point, preserves asynchronous fencing and cleanup acknowledgement, and keeps CDP announcement order and post-action navigation-error precedence. The only fixture repair replaces an unreliable TCP-coalescing assumption with the existing Gateway upgrade-head boundary; authentication, hello, inventory and length assertions remain.

Proof: 203 focused tests passed, complete changed-scope checks passed, and pnpm build passed without ineffective-dynamic-import warnings. The exact local commands are recorded in this PR's Evidence section. The normal commit hook preserved the tested tree. Fresh managed Codex autoreview is scoped-clean at P0 with no findings, and native review artifacts are complete. The tested/reviewed patch is byte-identical to the native PR checkout.

Exact-head hosted proof completed successfully, both on attempt 1: CI run 33348914007 and OpenGrep run 33348914071. The native exact-head watcher returned GREEN.

The latest ClawSweeper review and rank-up move are addressed: the PR is ready, the explicit maintainer landing decision is to accept this cleanup, and the exact-head checks have passed. The maintainer label remains; this proceeds through ordinary native preparation and pinned-head merge gates.

No new installed/live-Chrome or Windows runtime acceptance is claimed for this bounded behavior-preserving refactor. No operator browser/Gateway was touched. Previously recorded cross-client cleanup isolation and Windows symlink-rejection follow-ups remain separate; this PR does not claim to repair them.

@steipete
steipete merged commit 220c68e into main Aug 31, 2026
173 checks passed
@steipete
steipete deleted the steipete/mystifying-swirles-5c98cd branch August 31, 2026 02:04
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
Remove duplicate profile admission and terminal handling, reuse RPC result
schemas and deferred completion, and make announcement recipients and
request-local action guards explicit. Preserve authentication, asynchronous
ownership checks, cleanup acknowledgements, and action error precedence.

Make the Gateway upgrade-head fixture deterministic at its existing input
boundary instead of depending on TCP coalescing. Keep its assertions.

Maintainer-requested follow-up to the standalone relay in openclaw#128379.
Production LOC -75; test LOC -11. Validated with 203 focused tests, changed
checks, full build, and fresh scoped-clean Codex autoreview at P0.
steipete added a commit that referenced this pull request Oct 13, 2026
Consolidate image traversal, request observation ownership, bus waiters,
Slack response classification, Node selection and WebSocket decoding.
Retire the generic Windows executable export after its Node caller moved;
keep trusted taskkill/PowerShell paths and all environment validation.
Remove duplicate planner validation and unsupported private lifecycle guards.
Keep external evidence validation, security authority, resource limits and
ordinary write-capable shutdown settlement.

Also preserve WhatsApp audio preflight when enabling message actions and
avoid recording a POSIX pipe-drain failure during the normal TERM grace.

Best-effort tradeoffs accepted:
- Bus cloning trusts its private typed event union. 0ebeee8 added the
  unsupported-kind throw only for lint; fabricated internal kinds now fail
  naturally, and a new typed variant must update this owner at compile time.
- Overlapping private QA driver transitions are unsupported; callers await
  them. #113855 introduced synthetic interleavings, not a human incident.
- Canonical smoke selection is trusted instead of revalidated; #114055 was
  an ownership cutover. A future selector defect belongs at that owner.
- Wire image inputs are parsed JSON trees. #71311 introduced no human
  cyclic-input incident; unsupported internal cyclic objects are best effort.
- Fabricated cyclic/BigInt tool outputs now fail clearly instead of becoming
  empty evidence. 195e721 added stabilization, not a human incident.
- Reinstalling the private AIMock mount is unsupported. bdc9c60 added
  speculative guards; the actual owner installs it once before start.
- Obsolete repeated observer disposal after port reuse can remove the newer
  QA lookup. 6386dc4 was an affinity repair, not a disposal incident;
  normal unique-port ownership and stop ordering prevent that lifecycle.
- Local non-federated Matrix joins fail immediately on setup errors; #64489
  added initial coverage, not a reported transient-join incident. Rerun the
  QA command after an unusual setup fault.
- Artifact publication is trusted after its awaited atomic writer. #92606
  added suite execution, not a missing-write incident; deletion afterward
  is reported by normal readers.
- Native browser JSON needs no branded rawJSON surrogate workaround.
  #140882 added that generality without a human incident; a future branded
  producer must own its serialization contract.
- Insertion-only pending caches clear directly on settlement. #113926 and
  #128379 supplied no human successor-eviction incident; no replacement can
  precede these finalizers. Real close-time successor checks stay.
- Re-registering the identical private borrowed-relay handle is unsupported.
  #128379/#133706 introduced no such incident; the owner creates fresh handles
  and current authority and distinct-successor comparisons remain.
- Inconclusive Linux process snapshots conservatively stay alive until the
  next check. #132230/#131643 used controlled fault injection, not a human
  actual-use incident. Final unconfirmed settlement retains state for retry.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…0889)

Consolidate image traversal, request observation ownership, bus waiters,
Slack response classification, Node selection and WebSocket decoding.
Retire the generic Windows executable export after its Node caller moved;
keep trusted taskkill/PowerShell paths and all environment validation.
Remove duplicate planner validation and unsupported private lifecycle guards.
Keep external evidence validation, security authority, resource limits and
ordinary write-capable shutdown settlement.

Also preserve WhatsApp audio preflight when enabling message actions and
avoid recording a POSIX pipe-drain failure during the normal TERM grace.

Best-effort tradeoffs accepted:
- Bus cloning trusts its private typed event union. f993a27 added the
  unsupported-kind throw only for lint; fabricated internal kinds now fail
  naturally, and a new typed variant must update this owner at compile time.
- Overlapping private QA driver transitions are unsupported; callers await
  them. openclaw#113855 introduced synthetic interleavings, not a human incident.
- Canonical smoke selection is trusted instead of revalidated; openclaw#114055 was
  an ownership cutover. A future selector defect belongs at that owner.
- Wire image inputs are parsed JSON trees. openclaw#71311 introduced no human
  cyclic-input incident; unsupported internal cyclic objects are best effort.
- Fabricated cyclic/BigInt tool outputs now fail clearly instead of becoming
  empty evidence. 5929e9a added stabilization, not a human incident.
- Reinstalling the private AIMock mount is unsupported. e98e098 added
  speculative guards; the actual owner installs it once before start.
- Obsolete repeated observer disposal after port reuse can remove the newer
  QA lookup. ace0e05 was an affinity repair, not a disposal incident;
  normal unique-port ownership and stop ordering prevent that lifecycle.
- Local non-federated Matrix joins fail immediately on setup errors; openclaw#64489
  added initial coverage, not a reported transient-join incident. Rerun the
  QA command after an unusual setup fault.
- Artifact publication is trusted after its awaited atomic writer. openclaw#92606
  added suite execution, not a missing-write incident; deletion afterward
  is reported by normal readers.
- Native browser JSON needs no branded rawJSON surrogate workaround.
  openclaw#140882 added that generality without a human incident; a future branded
  producer must own its serialization contract.
- Insertion-only pending caches clear directly on settlement. openclaw#113926 and
  openclaw#128379 supplied no human successor-eviction incident; no replacement can
  precede these finalizers. Real close-time successor checks stay.
- Re-registering the identical private borrowed-relay handle is unsupported.
  openclaw#128379/openclaw#133706 introduced no such incident; the owner creates fresh handles
  and current authority and distinct-successor comparisons remain.
- Inconclusive Linux process snapshots conservatively stay alive until the
  next check. openclaw#132230/openclaw#131643 used controlled fault injection, not a human
  actual-use incident. Final unconfirmed settlement retains state for retry.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: browser maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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