Skip to content

refactor(events): deslop listener and disposal plumbing - #164221

Merged
steipete merged 4 commits into
mainfrom
deslop/x11-listener-dispose-plumbing-20261003
Oct 3, 2026
Merged

steipete merged 4 commits into
mainfrom
deslop/x11-listener-dispose-plumbing-20261003

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Listener registration and teardown repeat small local registries and compatibility paths, and stale unsubscribe handles can silently remove replacement observers.

User Impact

Replacement subscriptions keep receiving updates after an old disposer runs again. A synchronous HTTP bind failure releases its temporary listeners. Callback ordering, error isolation, replay, cleanup ownership, config, protocol, and visible UI remain unchanged.

Why This Change Was Made

  • Reuse the canonical registration helper and matching error-isolated notification helper; retain live versus snapshot iteration, zero-argument calls, and intentional exception propagation.
  • Replace the sole embedded-attempt cleanup array with its concrete release callback, and remove duplicate per-signal cancellation bookkeeping from the reply queue.
  • Replace single-subscriber Matrix verification and Tlon settings registries with direct owner callbacks.
  • Remove unused Discord listener mutation methods and Copilot's obsolete void/off() subscription fallback; the pinned SDK returns an unsubscribe function.

Fixes found along the way

Guard retired keyed subscriptions in MCP context, session maintenance, tool activity, model-catalog updates, SDK reconnects, and LLM activity. Add regressions at each owner boundary. Release both temporary HTTP listeners when native listen() throws synchronously, with a real-server regression that never opens a port.

Evidence

  • Production: 195 added / 346 removed = 151 net lines removed across 61 files. Tests and support: 223 added / 52 removed.
  • BELOW-1000: the attached size-sorted coverage log records 178 fully read production pattern owners over 200 lines and three explicit regex false positives. Larger retained registries enforce distinct replay, subscription identity, error, or resource-custody contracts; replacing them would change behavior.
  • Independent Codex autoreview, including fresh review of the CI corrections: no actionable P0–P2 findings. Rebase conflicts were adjacent imports only; both imports were retained.
  • Eight regression cases failed against their original owners; all 64 tests in the seven repaired owner suites passed after the fixes.
  • Focused validation and plugin contracts: 2,770 tests across 122 files passed. The 66-file focused selection took 1,210.78 seconds on the loaded Mac; plugin contracts passed 1,132 tests across 48 files in 668.02 seconds (Vitest wall time).
  • CI corrections passed targeted lint and 65 lifecycle tests. Both required import analyzers again reported zero cycles. The final rebase preserved the reviewed patch; the overlapping CLI event owner passed its two focused tests again on the final head (101.74 seconds including cold worker preparation).
  • Linux Testbox reproduced the two original package defects. Its replacement stayed queued beyond ten minutes; sanitized AWS source sync also stalled beyond ten minutes. Remaining checks used the authorized serial nice -n 15 fallback. Owned leases were completed, stopped, or released. Final Linux repair proof used Blacksmith Testbox tbx_01m40q0381hefeh3w72hd5hb4v (lease workflow); command exit codes own the proof result because stopping the lease can cancel its hosting workflow.
  • Copilot SDK 1.0.14 installed JavaScript and declarations confirm that both on() forms return unsubscribe functions. No dependency or public SDK export was added.

CI corrections and inherited failure

The first hosted run caught two callback typing/lint issues, the required assertion-baseline shrink, and an audio ordering regression. Those are addressed: async finalizers retain their original typed registration, synchronous HTTP listen failures clean up and rethrow into the Promise executor, the Copilot assertion count shrinks from 2 to 1, and the original meeting waiter remains unchanged. Its Promise.race scheduling boundary is required for final audio to carry closed: true; the existing audio boundary test passes without altered assertions.

Four attempt-stream-prepare.test.ts cases fail with terminal.readSanitizedResult is not a function. The same failures appear on hourly main CI job 111175455568, main head f323437952ccee1fc7abc06bab6eb6f7a376c726, independently of this PR. The test, mock fixture, stream-preparation owner, and tool-search executor have identical blobs in that main run and this PR. The unchanged mock constructs a terminal object without the reader that main's executor now requires; the property access fails before activity creation or transcript writes. These cases use a plain fake session, not the changed session cleanup path, and activity notifications are mocked. No inherited main fixture repair is included. Main subsequently repaired that fixture in commit b1c49290c8d5335331c63fc176d75a80805fa953; the final PR merge validation includes that owner fix.

The second hosted CI run 37116543498 exposed a race in chat-subagent-waiting.e2e.test.ts: returning to the retained parent schedules child-roster hydration after 250 ms, but the test measured request counts before that hydration finished. The test now holds that exact request, releases a response with a distinct child label, and waits for the label to render before measuring event-only updates. Transcript assertions are scoped to the active pane so hidden retained panes cannot produce duplicate matches. The exact no-extra-request assertion remains unchanged.

The repair passed 20 Linux browser executions (--repeats 19), taking 123.29 seconds of test time and 138.02 seconds wall time. A temporary production mutation deliberately added a read on the settled-to-waiting transition: the unchanged assertion failed with expected 3, received 4. The production file was restored byte-for-byte. The 55 sibling tests and all 1,132 plugin-contract tests also passed on the same Blacksmith lease, and both cycle analyzers reported zero. Three consecutive runs of the original 82-file UI shard passed all 391 cases each. The shard replay initially exposed a missing Playwright FFmpeg asset on the disposable lease; installing that required asset resolved all eight setup failures without source changes. The negative control was not repeated after it had established the intended failure.

ClawSweeper completed the earlier review of 6449398ad1fd89a836d195c53a73612b09204a54 with no introduced defect. Its mechanical data-model compatibility checkbox is unsupported by the diff and contradicted by its technical review: device-scope-upgrade.ts only replaces equivalent Set registration with the canonical helper; no migration, storage shape, or upgrade contract changes.

Final hosted CI and inherited-only exception

Final-head CI 37121575413 at 32fb7b416af2f0b9c0d842acce1d5db34c8aa325 passed every selected job except checks-node-changed-compact-large-21-1 and its aggregate gate. The repaired UI shard passes.

The sole failed case is server-endpoint-compaction.test.ts → “leaves a missing canonical checkpoint window to client budget compaction”: Cannot add property providerReplay, object is not extensible at test line 255 / openai-responses-compaction-replay.ts:127. The same case fails on the current independent peer CI job 111201356130, peer head 3a118d68bc6e0989b657dbcd00b9882dda9a0ca0.

Main commit e40ed06f23cb8bd939c9a6ff537eba7136074686 made appended messages immutable. This unchanged fixture attempts to mutate a transcript-owned message before calling the compaction operation; production compaction already clones its owner message. The test, capture helper, append/persistence owners, and freeze helper are unchanged between our CI baseline and tested merge. Our listener changes do not execute on the failing setup path. The fixture repair is already owned by #163471; no duplicate repair is included. This qualifies for the explicitly authorized inherited-only CI exception; CI is retained as failed, and security/review gates remain enforced.

Regression test wall times

All commands used node scripts/run-vitest.mjs <file> --maxWorkers=1, at nice level 15. These are measured local wall times, including worker preparation; hosted CI timing is tracked separately.

Owner suite Wall time
src/config/sessions/session-accessor.sqlite-maintenance-age.test.ts 12.07 s
src/agents/mcp-app-model-context.test.ts 7.28 s
src/agents/embedded-agent-runner/run/tool-activity-heartbeat.test.ts 140.93 s
src/gateway/server/http-listen.test.ts 93.05 s
ui/src/lib/model-catalog-store.test.ts 12.89 s
packages/ai/src/utils/llm-request-activity.test.ts and packages/sdk/src/transport.test.ts (one invocation) 11.28 s

The HTTP regression compares the complete pre-call listener lists, preserving Node's own listener as well as the caller's.

Focused test selection
node scripts/run-vitest.mjs --maxWorkers=1 extensions/copilot/src/event-bridge.test.ts extensions/copilot/src/attempt.test.ts extensions/copilot/src/attempt-transcript-journal.test.ts extensions/discord/src/internal/client.test.ts extensions/discord/src/monitor/provider.startup.test.ts extensions/matrix/src/matrix/sdk/verification-manager.test.ts extensions/matrix/src/matrix/sdk/client-startup-recovery.test.ts extensions/matrix/src/matrix/sdk/joined-room-encryption.test.ts extensions/tlon/src/settings.test.ts extensions/tlon/src/monitor/index.test.ts extensions/tlon/src/monitor/index.history.test.ts extensions/tlon/src/monitor/index.thread-mentions.test.ts extensions/tlon/src/monitor/index.group-invites.test.ts extensions/tlon/src/monitor/index.citations.test.ts src/agents/embedded-agent-runner/run/attempt.abort-race.test.ts src/agents/sessions/agent-session-loop-next-turn.test.ts src/agents/auth-profiles/runtime-snapshots.test.ts src/agents/auth-profiles/shared-store-bootstrap.runtime.test.ts src/agents/sessions/extensions/runner.test.ts src/agents/cli-runner/execute-events.compaction-tracking.test.ts src/config/runtime-snapshot.test.ts src/config/runtime-snapshot.preparation.test.ts src/infra/diagnostic-events.test.ts src/infra/unhandled-rejections.test.ts src/infra/kysely-sync.test.ts src/infra/sqlite-wal-checkpoint.test.ts src/infra/sqlite-worker-broker.test.ts src/skills/runtime/refresh-state.test.ts src/process/gateway-work-admission.test.ts src/meeting-bot/node-host.test.ts src/proxy-capture/runtime.lifecycle.test.ts src/auto-reply/reply/queue.authority.test.ts src/auto-reply/reply/queue.collect.test.ts src/auto-reply/reply/queue.in-flight.test.ts src/gateway/worker-environments/placement-turn-authority.test.ts src/gateway/worker-environments/store-projection.test.ts src/plugins/http-registry.test.ts ui/src/lib/model-catalog-store.lifecycle.test.ts ui/src/lib/chat/chat-metadata-store.test.ts ui/src/app/boot-record.test.ts ui/src/app/gateway-store.observers.test.ts ui/src/app/agent-selection.test.ts ui/src/app/bootstrap-theme.palette.test.ts ui/src/app/chat-submissions.test.ts ui/src/app/config.test.ts ui/src/app/device-scope-upgrade-controller.runtime.test.ts ui/src/app/mentions.test.ts ui/src/app/native-conversation-bridge.test.ts ui/src/app/native-device-settings.test.ts ui/src/app/native-gateways.test.ts ui/src/app/native-notifications.test.ts ui/src/app/overlays.test.ts ui/src/app/session-placement-startup.test.ts ui/src/app/skill-workshop-revision-admissions.test.ts ui/src/app/web-push.test.ts ui/src/lib/agents/identity.test.ts ui/src/lib/board/provider.test.ts ui/src/lib/channels/index.test.ts ui/src/components/sidebar-attention-store.test.ts ui/src/components/assistant-panel.test.ts ui/src/plugins/control-ui-host.test.ts ui/src/pages/systems/systems-page.test.ts ui/src/pages/chat/chat-pane-session-controls.permissions.test.ts ui/src/pages/chat/chat-model-restriction-recovery.test.ts ui/src/pages/chat/chat-send-handoff.test.ts ui/src/pages/chat/chat-send.test.ts
node scripts/run-vitest.mjs src/plugins/contracts --maxWorkers=1
node --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.ts
node --import ./scripts/tsx.mjs scripts/check-import-cycles.ts
Size-sorted production coverage log

Listener and disposal coverage

This cross-cutting lane inventories concrete listener registries, subscription/disposal owners and teardown wrappers; unrelated modules are outside the pattern. Sizes use the starting main revision 54d008b6dae. Every actual candidate over 200 lines is marked READ with its simplification or retention reason. Regex false positives are explicit. Existing native-language and dependency-specific lifecycles remain with their owners.

Lines Production file Coverage and decision
1719 apps/macos/Sources/OpenClaw/GatewayConnection.swift READ — native actor owns AsyncStream continuations, snapshot replay, physical-socket generations, route-retirement receipts, and distinct bounded realtime stream handling; TypeScript listener helpers cannot replace these runtime/ownership contracts.
1644 src/infra/diagnostic-events.ts READ — Reused canonical registration for trusted tool execution; remaining keyed dispatch clones private data per listener and counts filter interest.
1436 src/gateway/node-registry.ts READ — ping listeners have one settlement owner, timeout cancellation, and connection-generation recheck; registry policy and invoke forwarding are outside x11.
1356 extensions/tlon/src/monitor/index.ts READ — Applied direct settings subscription callback at the existing late-registration boundary; no separate local listener registry.
1318 src/auto-reply/reply/queue/drain.ts READ — Replaced the redundant per-signal callback Map with one shared abort callback and the existing signal Set. Both aggregate call sites retain admission transition and finally cleanup.
1282 scripts/dev/realtime-talk-live-smoke.ts READ — the listener Set is embedded in a generated browser-fixture source string; snapshot iteration and fail-fast dispatch model the gateway client, while page/context/browser and media teardown belong to browser resources. A Node helper import is not a direct equivalent.
1210 src/gateway/watch-node-http.ts READ — HTTP finish/close receipt distinguishes successful bootstrap delivery from abort; transport polls and session cleanup retain exact owner.
1195 apps/macos/Sources/OpenClaw/GatewayEndpointStore.swift READ — actor-isolated endpoint publication uses AsyncStream initial-value replay and onTermination actor handoff; endpoint revision/tunnel authority must stay together. No matching cross-runtime canonical helper.
1168 scripts/lib/managed-child-process.mts READ — this is the canonical script process owner: signal registration tracks active children, async cleanup joins descendants and output closure, and failed closure retains ownership. Generic synchronous listener isolation would change fail-fast signal behavior and resource guarantees.
1055 src/commands/models/list.probe.ts READ — No sound x11 simplification remains: createAuthProbeWork already owns the run/drain barrier. Probe finalization closes run admission first, then after physical work drains attempts session removal, snapshot invalidation, exact-path agent-database disposal, and directory removal sequentially, continuing after every cleanup error. It preserves a single error's identity or throws an ordered AggregateError whose cause is the first failure. Best-effort cleanup would swallow the required failure; disposal stacks would change ordering/error shape. The outer state-owner release uses nested finally so signal listeners detach even if state-lock release fails, and is itself delayed through the same work barrier. The rest of the file is probe target/auth selection and result projection outside x11 scope.
874 src/agents/sessions/extensions/runner.ts READ — canonical registerListener now owns Set registration; retain fail-fast error-listener dispatch and ordered async transforming hook chains.
860 extensions/copilot/src/event-bridge.ts READ — Applied pinned SDK unsubscribe contract; removed obsolete optional off fallback and captured session/disposers once for 21 registrations. Reverse teardown and per-disposer exception isolation retained.
814 src/agents/sessions/agent-session-base.ts READ — canonical notifyListeners now owns isolated synchronous abort fanout; retain copy-on-write array subscriptions and awaited terminal barrier, whose duplicate-registration and error contracts differ from Set dispatch.
785 ui/src/components/session-data-controller.ts READ — Already uses SubscriptionsController; explicit ordering preserves catalog, filtered-query and mutation ownership.
782 src/state/openclaw-state-db-cache.ts READ — Retained native-handle replay on registration and synchronous fail-fast lifecycle callbacks; generic notification would swallow failures.
777 ui/src/pages/custodian/custodian-session-store.ts READ — Direct two-line registration and propagating zero-argument loop; context subscriptions have distinct lifetime and synchronization.
774 src/plugins/plugin-instance.ts READ — reverse plugin cleanup, module custody, awaited consumers, timeout reporting, and failure aggregation are intentional owner boundaries.
770 src/gateway/exec-approval-lifecycle.ts READ — observation closure intentionally differs from durable verdict and handoff custody; edits skipped for overlapping PR #164022, which merged during this audit.
767 src/gateway/server-chat-state.ts READ — provisional subscription rollback/commit and merged per-connection modes are required; listener callback is variadic and fail-fast.
763 src/agents/auth-profiles/runtime-snapshots.ts READ — canonical registerListener owns registration; fail-fast mutation publication remains unchanged.
760 extensions/matrix/src/matrix/sdk/client-base.ts READ — Applied constructor-owned summary callback; removed redundant listener-bound flag and post-construction registration. Bootstrap/facade constructors do not emit summaries.
754 src/infra/agent-run-registry.ts READ — Registration already canonical; delegated authority closure supplies two positional arguments and isolates failures, while exact claim-clear callbacks intentionally propagate errors. Unary notifyListeners is not equivalent.
749 packages/agent-core/src/agent.ts READ — Retained: queue notification is synchronous live iteration; agent events await each listener in order and carry active-run cancellation. Shared sync isolated notifier is not equivalent and package cannot import core internals.
748 src/config/sessions/session-transcript-reconcile.ts READ — No sound canonical-listener substitution: MessagePort message/error listeners remain installed through asynchronous handler settlement and native lease release, then the owned port is closed and listeners removed. The settled guard prevents further protocol work, while terminal receipt and release failures have distinct recovery paths; ordinary Set notification or cleanup-at-Promise-settlement would change custody or ordering.
748 src/gateway/session-row-projection-record.ts READ — notifier already canonical; selection subscriptions deliberately share the projection's whole lifetime; edits skipped for overlapping PR #164022, since merged.
746 src/gateway/control-ui-session-pr-subscriptions.ts READ — demand predicates preserve pending admission, shared refresh ownership, per-recipient receipts, and serialization; not interchangeable callbacks.
737 src/process/supervisor/adapters/child.ts READ — No sound x11 simplification remains: createProcessAdapterEvents already owns replayable exit/error observations; native child and pipe listeners implement separate close, drain, IPC, and tree-extinction barriers. The small FIFO outputUnsubscribers.splice(0) loop deliberately drains before stream destruction, keeps error/Node-close bookkeeping attached during destruction, and is fail-fast. A generic disposal stack would reverse ordering or alter error aggregation/continuation; isolating notification helpers would alter fail-fast semantics.
731 extensions/discord/src/voice/realtime-speaker-session.ts READ — Retained: multiple waitForInputIdle callers need separate abort/removal handles; recording input ownership and turn-close authority prevent direct callback replacement without changing lifecycle.
731 ui/src/app/gateway-store.ts READ: snapshot/event registration uses registerListener; event-log subscription retains final-listener retirement and guarded snapshot delivery.
728 src/infra/sqlite-worker-broker.ts READ — Replaced native-loss observer error-isolation loop with canonical notifyListeners; kept capacity FIFO and settled-input custody.
727 src/auto-reply/reply/reply-run-registry.state.ts READ — After-clear callbacks are fail-fast and barrier-aware; waiter sets carry completion ownership rather than subscriptions.
724 scripts/lib/cross-os-release-checks/process.ts READ — process shutdown delegates to canonical terminateManagedChild; local callback registry retains snapshot signal delivery, delayed force-kill, and forwarded-exit completion. The reversed async cleanup list preserves sequential LIFO best effort, unlike notifyListeners.
724 src/gateway/server-methods/sessions-patch-engine.ts NOT-PATTERN — grep hit is a commit-guard predicate Set, not a listener/disposal registry; no full-read claim.
724 ui/src/lib/sessions/index.ts READ: already uses registerListener; direct loops intentionally propagate errors and disposal retains ordered owners.
716 extensions/matrix/src/matrix/sdk/verification-manager.ts READ — Applied sole production summary subscriber as constructor callback; removed Set and unsubscribe API. Summary construction and synchronous exception propagation preserved.
715 src/config/sessions/session-accessor.sqlite-reclamation-worker-lifetime.ts READ — No sound cleanup-stack replacement: it already uses native addAbortListener and the canonical transport-end observer. Idle-drain disposal is tied to renewed use; process/pressure/owner registrations are deliberately retained after uncertain cleanup so explicit retirement can retry, and removed only after native exit or released task custody is proven.
712 ui/src/lib/sessions/session-roster-refresh.ts READ: managed entries retain per-window pacing and query ownership; actual registration delegated to primary-windows. DOM lifecycle ordering retained.
709 ui/src/lib/chat/outbox-store.ts READ: shared storage listener attaches on first subscription and detaches on last; zero-argument isolated callbacks cannot use event-argument notifyListeners unchanged.
707 src/config/runtime-snapshot.ts READ — Reused canonical write-listener registration; preparers carry generation and synchronous replay contracts.
705 src/gateway/github-personal-oauth.ts READ — cleanup Map already uses canonical getOrCreatePromise; stop joins remote credential rotation and retains failed persistence ownership.
704 ui/src/components/mcp-app-view.ts READ — Cleanup Set supports early individual release plus ordered asynchronous bridge/transport teardown; a stack would alter ordering and failure behavior.
701 ui/src/lib/session-progress-cards.ts READ: demand-driven attach/detach also depends on watch owners; callback zero-argument propagation and idle cache retirement retained.
699 scripts/run-oxlint.mts READ — output callback Set owns drain-listener removal while streams are paused for backpressure; callbacks delete themselves and resume one stream. Managed subprocess and transient artifact cleanup already use their canonical owners.
691 ui/src/lib/sessions/session-roster-observations.ts READ: row/list delivery revalidates connection, row incarnation, and snapshot between callbacks; not interchangeable with generic delivery.
690 src/process/gateway-work-admission.ts READ — Reused canonical suspension registration; retained snapshot notification and admission wake-before-transition ordering.
683 src/agents/code-mode-state.ts READ — continuation ownership, retries of failed physical disposal, parked calls, and cancellation fences require this lifecycle; direct catalog callback registration has exact owner-based removal.
680 packages/gateway-client/src/protocol-client.ts READ — Retained: snapshot membership plus per-subscription identity and socket-generation revalidation between callbacks are real stale-event fences.
675 src/agents/provider-local-service.ts READ — spawn listeners include already-spawned PID fallback and distinct abort-to-error mapping; generic once/disposer replacement would change that contract.
668 src/gateway/worker-environments/placement-turn-authority.ts READ — applied canonical registration; retained snapshot-before-clear zero-argument revocation notifications and all post-commit authority behavior.
668 src/infra/agent-events.ts READ — Already canonical for notification and audit registration; merged live global/run dispatch preserves registration IDs and mutation cursor.
639 src/gateway/worker-environments/session-attachment-service.ts READ — cleanups already use KeyedAsyncQueue; retry custody and abort-controller owner Sets have required settlement behavior and identity checks.
635 src/plugin-sdk/api-baseline-declaration-closure.ts NOT-PATTERN — grep hit is graph traversal's default visited Set; no listener/disposal implementation or full-read claim.
626 ui/src/pages/chat/chat-state-controller.ts READ — Render cancellation scopes and LIFO cleanup have distinct completion/cancellation ownership; no matching canonical replacement.
624 ui/src/lib/channels/index.ts READ: subscription uses registerListener; publication still propagates listener errors and channel lifecycle retains its own teardown.
617 apps/android/wear/src/main/java/ai/openclaw/wear/WearTalkAvatar.kt READ — Compose DisposableEffect owns subscription lifetime; Android API-level implementations select duration-scale listener versus BroadcastReceiver plus LifecycleObserver. Native platform adaptation is required, not duplicate TS event ownership.
617 ui/src/pages/systems/systems-controller.ts READ — Replaced hand-written registration with registerListener; retained presentation-owned requests and teardown ordering.
615 src/state/openclaw-state-db-async-lifecycle.ts READ — Cleanup phases retain failed resources and allow admitted cleanup work; this is native custody, not a replaceable event bus.
615 ui/src/lib/session-pull-requests.ts READ: snapshot-membership notifications, waiter ownership, and last-subscriber Gateway sync remain explicit.
610 ui/src/pages/config/talk-page.ts READ — Immediate subscribe synchronization and shared Gateway-lifetime voice drafts; canonical SubscriptionsController already owns page watches.
605 src/gateway/desktop/session-registry.ts READ — epoch-scoped observer records carry authority, reservations, control takeover, linger, and failed-stop retry custody; simple callback Set would lose state.
604 src/gateway/mcp-http.ts READ — SSE keepalive and response membership have separate teardown outcomes; server shutdown retains grant invalidation and accepted request draining.
604 ui/src/plugins/control-ui-runtime.ts READ — Activation-scoped disposers revoke live contribution authority in reverse order; generic disposal would lose identity/reentrancy contracts.
600 ui/src/lib/chat/chat-metadata-store.ts READ: isolated notification uses notifyListeners over the same snapshotted Map keys and exact error logger; active-demand Map lifecycle retained.
598 src/agents/embedded-agent-runner/run/attempt.ts READ — removed single-use runCleanups array in favor of the concrete releaseTools callback; preparation/session custody and cleanup deadlines remain.
590 src/agents/mcp-ui-resource.ts READ — view disposal already uses canonical notifyListeners with error reporting and exact-view identity fencing.
589 src/infra/sqlite-snapshot-single-flight.ts READ — Listeners are retained operation objects with synchronous servicing and orphan cleanup custody; no callback-helper replacement preserves that contract.
586 src/gateway/sessions-history-http.ts READ — finish releases stream resources but intentionally retains error handlers until close; subscriptions fence session identity and publication authority.
581 ui/src/app/native-conversation-bridge.ts READ: subscription uses registerListener; native command deadlines, outgoing FIFO, exact-document authority and pending expiration ordering retained.
579 src/gateway/mcp-grant-store.ts READ — notifications intentionally fail fast, registration is already two lines; unary isolated notifier would change failure propagation.
558 src/gateway/portals/portal-http-proxy.ts READ — one header parser listener transitions to pipe after bounded handshake; close/error callbacks belong to physical socket lifetime.
543 src/gateway/server/ws-connection/worker-connection.ts READ — one message listener is retired with connection tool abort, expiry, and FIFO received-work custody; no competing subscription owner.
540 src/gateway/server-methods/models-auth-status.ts NOT-PATTERN — grep hit is a set of health status values; no listener/disposal implementation or full-read claim.
533 src/agents/tool-search-catalog.ts READ — disposal list is fail-fast; direct disposeObserver and mutable catalog ownership cannot be replaced with error-isolating notifications.
526 src/agents/embedded-agent-subscribe.ts READ — teardown revokes admission before settling compaction waiters and unsubscribing; lifecycle ordering is intrinsic, not redundant subscription plumbing.
526 src/gateway/worker-environments/store-projection.ts READ — applied canonical registration, preserving a fresh wrapper per registration and fail-fast revocation delivery.
523 src/worker/worker-connection.ts READ — Already uses canonical registration and notification; readiness waiters retain resolve/reject and reconnect ownership.
516 src/gateway/worker-environments/store.ts READ — facade tracks its own projection unsubscribe handles and releases only after mutations settle; owner/refcount boundaries stay separate.
507 src/gateway/server/ws-connection/authenticated-request-dispatch.ts READ — source invalidation subscriptions and disconnect cancellation have distinct authorities; finally nesting preserves cleanup after failure.
486 extensions/whatsapp/src/session.ts READ — Retained: connection wait detaches its exact handler before settlement and owns timeout cleanup; socket-lifetime error handlers intentionally stay attached.
485 ui/src/app/session-placement-startup.runtime.ts READ: subscription uses registerListener; placement ownership, lifecycle cancellation and direct delivery retained.
476 src/agents/embedded-agent-runner/run/attempt-tool-prepare.ts READ — removed runCleanups registry that only pushed releaseTools once; real generationCleanups list remains because tools dynamically register many resources.
474 src/gateway/server/plugins-http.ts READ — HTTP profile updates are request-scoped, while upgraded sockets retain access-abort listeners; different lifetimes cannot share one disposal.
470 src/agents/cli-runner/execute-events.ts READ — canonical registerListener now owns compaction subscription; retain fail-fast ordered notifications and unchanged event projection.
470 src/agents/embedded-agent-runner/run/lane-controller.ts READ — deadline subscription synchronously publishes current state after registration; retain registration/publish order and fail-fast deadline propagation.
458 src/commands/doctor/shared/context-engine-host-compat.ts READ — No sound x11 simplification remains: one inspection path owns the acquired plugin-registry lease and resolved engine. Its two-item cleanup loop awaits engine disposal before inspection release, attempts release even when disposal fails, preserves the original resolution error if present, otherwise preserves the first cleanup error, and turns that retained error into the established Doctor warning. runBestEffortCleanup, a disposal stack, or an aggregate helper does not preserve this first-failure warning contract without restoring equivalent local policy. No listener registry, redundant subscription owner, or unused disposal layer is present elsewhere in the fully read file.
455 ui/src/lib/model-catalog-store.ts READ: fixed repeated old unsubscribe deleting a newer observer bucket; real publication regression added. Request settlement/lane ownership unchanged.
454 extensions/memory-core/src/memory/manager-search-knn-subprocess.ts READ — Retained: child error handlers live beyond per-request handlers, close owns process-slot release, and abort cannot release a still-running child. Generic listener helper cannot collapse these distinct lifetimes.
448 src/gateway/server-http-upgrades.ts READ — upgrade budget cleanup transfers only after connection owner claims it, with failure cleanup already present; edits skipped for overlapping PR #164022, since merged.
438 apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatSessionHoverCardFacts.swift READ — UUID watch owners drive a serialized remote subscription union; generation/lifetime fencing, task cancellation, and final empty-subscription acknowledgment are necessary custody semantics.
438 src/plugins/host-hook-cleanup.ts READ — session-before-runtime ordering, per-plugin ownership, timeout isolation, and persistent/scheduler cleanup are not generic listeners.
431 ui/src/pages/plugin/logbook-controller.ts READ — False positive: a single view invalidation callback, with polling/client generations rather than a listener registry.
426 ui/src/lib/agents/index.ts READ: already uses registerListener; callbacks propagate and mutable-state publication timing is intentional.
426 ui/src/pages/new-session/draft-preference-state.ts READ — Three-argument publication and write-receipt fencing; unary notification helper cannot preserve its contract.
420 ui/src/app/session-placement-startup.ts READ: subscription uses registerListener; lazy-runtime handoff and reload-guard lifecycle remain distinct ownership boundaries.
415 ui/src/app/native-device-settings.ts READ: subscription uses registerListener; exact-native-handler authority and host update event semantics retained.
414 src/agents/embedded-agent-runner/run/attempt-settle.ts READ — named ordered cleanup stages preserve first error while logging each failure; canonical notification helper lacks per-stage identity/error return contract.
414 src/gateway/desktop/rfb-preauth.ts READ — temporary stream adapter teardown owns fixed protocol negotiation listeners and leaves the authenticated stream alive for handoff.
411 scripts/e2e/lib/plugin-lifecycle-matrix/measure.mjs READ — process signal listeners forward/rethrow the original signal only after process-group drain or escalation, with metrics finalized once. Process-exit semantics cannot be replaced with generic listener/error-isolation helpers.
405 ui/src/app/overlays.ts READ: subscription uses registerListener; approval/device-pair/update cleanup order retained.
404 src/infra/oauth-loopback-callback.ts READ — No sound x11 simplification remains: this is the canonical shared OAuth callback-server owner. Its bind-error listener handoff, once-only finish/close settlement, pending-response custody, abort cleanup, and idempotent close promise distinguish admission from socket completion. racePromiseWithAbortSignal is not equivalent to its local DNS abort wait: it changes the exact OAuth callback cancelled error consumed by OAuth callers to an AbortError with different message/cause and settlement mechanics. Generalizing it solely for this caller would replace 13 direct lines with new policy.
399 src/infra/worker-native-handle.ts READ — EventEmitter implements Worker-compatible started/message/error/exit semantics and AsyncLocalStorage callback ownership.
396 src/gateway/server-methods/session-catalog-list-lifetime.ts READ — native completion custody outlives bounded delivery captures; subscriber preparation, abort handling, and publisher release have different lifetimes.
393 extensions/discord/src/voice/audio-transport.ts READ — Retained: readable EOF, physical subscription finalization, adapter destruction and worker exit are distinct completion boundaries; EventEmitter is the native stream/worker contract.
381 src/config/sessions/session-accessor.sqlite-archive.ts READ — No sound abort-helper substitution: the FIFO abort listener is removed at admission, preserving immediate queued cancellation and inert queue slots while admitted work must join physical settlement. racePromiseWithAbortSignal would reject after admission and change the error shape. Worker result/error listeners deliberately settle only on exit, when SQLite/file handles are closed.
381 src/state/user-profile-events.ts READ — Already canonical registration; email binding callbacks deliberately propagate synchronous writer errors, profile display notification already canonical.
376 src/gateway/desktop/observe-bridge.ts READ — temporary WebSocket preauth listeners transition into authorized stream forwarding; close owner also retires backpressure and audio.
373 src/infra/sqlite-readonly-native-resource.client.ts READ — No sound x11 simplification remains: the MessagePort framing/client is already the transport owner. Port-lifetime listeners are installed once, and the host connection removes its listeners before closing both ports. Per-copy abort registration has a matching finally removal and cannot be replaced by an abort race because cancellation must wait for a real RPC child-close acknowledgement. Session maps retain native custody after transport failure until a close reply or acknowledged closed state permits release.
367 ui/src/lib/model-catalog-cache.ts READ: direct notification deliberately snapshots membership and propagates errors; cache does not own observer registration deletion.
364 src/claws/provenance-runtime-read.ts READ — Snapshot listeners intentionally propagate authority/preparation failures; existing two-line registration is already minimal.
359 src/infra/unhandled-rejections.ts READ — Reused canonical handler registration; first handled result intentionally short-circuits dispatch, preserving per-handler diagnostics.
351 packages/ai/src/stream.ts READ — Retained: async-iterator waiters wake on buffer progress and retirement while result and buffer completion jointly retain the transport host; canonical sync notifier does not own that lifecycle.
351 src/gateway/desktop/node-stream-broker.ts READ — listener teardown changes at metadata/authorization handoff; error listener deliberately remains for the WebSocket lifetime.
349 src/process/spawn-broker/child.ts READ — EventEmitter implements ChildProcess contract including spawn/IPC/close ordering and async-resource context, not an unused wrapper.
348 ui/src/app/boot-record.ts READ: registration and isolated delivery use canonical helpers; live iteration, error logger, retirement generation and storage ownership retained.
345 ui/src/app/agent-selection.ts READ: subscription uses registerListener; ordering of preference, Gateway and roster owners preserved.
336 src/gateway/server-cron-lazy.ts READ — scheduling-resume Set contains promise resolvers, not external listeners; clear-before-resolve and lazy startup/drain ordering remain.
336 src/state/user-github-connections.ts READ — Canonical observer registration already present; retirement callbacks propagate committed owner cleanup failure.
333 src/node-host/plugin-node-host.ts READ — Watcher cleanup concurrently settles every callback, retains only rejected owners for retry, and preserves plugin registry context; AsyncDisposableStack is not equivalent.
333 src/secrets/private-plan-file.ts READ — No sound x11 simplification remains: the matched IDisposable is embedded C# implementing Win32 SafeFileHandle custody, not duplicated JavaScript disposal infrastructure. Its finally calls dispose after ACL verification/publication failure; disposal arms delete-on-close before handle release and attempts explicit deletion only when arming fails. Descriptor memory is separately freed in Open's finally. Replacing these native phases with the TypeScript helpers is not possible and collapsing them changes private-file failure semantics.
332 src/gateway/operator-role-policy.ts READ — registration/notification already canonical; snapshot iteration preserves listener mutation semantics.
328 src/gateway/desktop/managed-linux-audio.ts READ — capture cleanup Set retains per-process stop promises until supervisor cleanup settles; daemon and capture ownership differ.
327 src/infra/worker-task-pool-retirement.ts READ — No sound x11 simplification remains: retirement already uses createRetainedOperation and runBestEffortCleanup. Rotation snapshots tasks/slots, waits tasks before native retirement, joins artifact cleanup after native shutdown, and retains failed custody for retry. service() must advance synchronously without waiting for Promise reactions, so straight-line async teardown is not equivalent. Completion callbacks deliberately execute directly/fail-fast after native listener removal; notifyListeners would isolate failures and change dispatch/retry behavior.
326 src/config/sessions/session-accessor.sqlite-maintenance-age.ts READ — Fixed repeated old unsubscribe deleting a replacement identity bucket; regression exercises real publication.
326 src/skills/runtime/refresh-state.ts READ — Reused canonical subscription registration; source reconciliation and monotonic version notifications remain unchanged.
323 src/gateway/node-runner-inventory-runtime.ts READ — keyed listener removal supports availability waiters and notifications are intentionally fail-fast; generic isolated fanout would change behavior.
322 src/infra/sqlite-wal-checkpoint.ts READ — Reused canonical registration; retained per-listener health cloning and diagnostics error isolation.
321 src/plugins/install-runtime-batch.ts READ — source cleanups retain filesystem inode, committed index, and lease authority; no generic disposer can replace those assertions.
320 ui/src/lib/chat/outbox-store-projection.ts READ: tab/durable subscription lifetime and stale generations depend on active readers; zero-argument isolated delivery retained.
319 packages/sdk/src/transport.ts READ — Fixed stale disposer deleting a replacement reconnect bucket by deleting the WeakMap bucket only after its own listener was removed; regression at real transport reconnect boundary.
318 src/worker/worker-connection-frames.ts READ — All three worker event registries already use canonical registration and notification.
305 extensions/openai/realtime-quicksilver-socket.ts READ — Retained: EventEmitter is required by websocket-shaped adapter; queued-control credits, close event and worker exit remain separate ownership boundaries.
305 src/gateway/server-shared-auth-generation.ts READ — invalidation registration/notification already canonical and bound to auth-generation owner.
304 src/gateway/server-broadcast-narration.ts READ — connection close, subscription change, and run abort retire different pending data; pacing and authority semantics require those boundaries.
303 src/gateway/http-common.ts READ — response admission and client-disconnect observation intentionally differ; late response errors remain handled after finish.
302 ui/src/app/bootstrap-theme.ts READ: subscription uses registerListener; palette readiness and initial preference delivery order preserved; media-query platform adapter is not equivalent.
296 src/gateway/desktop/rfb-probe.ts READ — readable-mode listeners preserve socket buffering across protocol handoff; stream owns remaining data/error/close events.
292 src/media/store.read-scope.ts READ — Retained zero-argument exit callbacks, per-error redaction, filesystem identity guards and delegated cleanup custody.
291 src/config/sessions/session-transcript-reconcile-pool.ts READ — No redundant listener registry: the operations Set tracks asynchronous resource custody, not callbacks. MessagePort close and lease-released messages provide separate proofs; lease recovery may dispatch after new-work admission closes. Canonical WorkerTaskPool, deferred, singleton, and database-resource owners are already used.
287 src/config/sessions/session-accessor.sqlite-archive-session.ts READ — No sound general cleanup replacement: request-scoped message/exit listeners are removed on valid settlement, exit, or synchronous dispatch failure, whereas connection-level error/exit listeners survive until the reused worker exits. Constructor registration failure rolls back the first registration; successful close unregisters owners only after retirement, preserving failure retries.
286 ui/src/pages/chat/chat-pane-sidebar-layout.ts READ — Pending lazy import waiters clear after publication; direct loop deliberately propagates failures and needs no subscription API.
280 ui/src/app/config.ts READ: subscription uses registerListener; current-config publication, authority and throw propagation unchanged.
280 ui/src/app/mentions.ts READ: subscription uses registerListener; profile-owned request invalidation, listeners' zero-argument calls and teardown ordering retained.
277 src/hooks/internal-hooks.ts READ — Handler arrays preserve duplicate registration and remove one matching registration; dispatch snapshots family-before-exact handlers and awaits each sequentially with per-error logging. Set registration or synchronous notification would change behavior.
274 src/agents/mcp-app-model-context.ts READ — FIX: stale unsubscribe cannot remove a fresh WeakMap listener bucket; added boundary regression to existing test.
269 src/config/sessions/session-turn.ts READ — Fresh commit guards are synchronous authority checks that must throw; no listener notification simplification applies.
267 ui/src/lib/sessions/session-managed-list-refresh.ts READ: each listener requires current-connection/current-snapshot check; generic notification would alter propagation and invalidation.
264 src/skills/runtime/session-snapshot.ts READ — Waiters are per-caller authority assertions and remove rejected owners; dispatch failure must surface only after all callers retire.
263 src/gateway/chat-abort-lifecycle-internal.ts READ — per-entry removal waiters and terminal persistence cannot collapse into ordinary event fanout; exact execution custody retained.
262 src/gateway/worker-environments/project-setup-script.ts READ — remote standalone JS owns process signal teardown in finally; cannot import host helpers into generated standalone execution contract.
258 extensions/tlon/src/settings.ts READ — Applied direct startSubscription callback; removed private Set, fanout wrapper and unused unsubscribe API while preserving listener-error logging.
258 ui/src/lib/agents/roster-activity-store.ts READ: each registration owns a distinct wrapper, first/last subscription lifecycle and snapshot replacement checks; retained intentionally.
255 src/gateway/desktop/audio-bridge.ts READ — one stream settlement owner removes end/close/error/data/abort listeners; start/stop serialization owns real capture lifecycle.
254 extensions/discord/src/voice/realtime-recording.ts READ — Retained: recording owner retains exact input unsubscribe handles until eligibility completion; input can outlive its audio and batch halves. No shared plugin SDK helper with matching propagated exceptions.
249 src/agents/mcp-stdio-client.ts READ — SDK protocol owns subscriptions and transport shutdown, one stderr listener has matching disposal; abort listeners have protocol-specific failure mapping.
248 ui/src/components/session-data-controller-events.ts READ — Subscriptions attach canonical owners and preserve initial projection plus error-reset cleanup; no duplicate lifecycle owner.
247 ui/src/pages/model-setup/first-run-activation-receipt.ts READ — In-tab Set plus separate cross-tab storage listener and receipt authority; retained exact dispatch and removal.
245 src/agents/auth-profiles/shared-store-bootstrap.ts READ — canonical registerListener owns registration; fail-fast relocation publication remains unchanged.
244 extensions/workboard/browser/widgets/runtime.ts READ — Retained: shared per-host widgets have multiple listeners and reference-counted disposal with runtime identity checks; browser artifact cutover is unnecessary.
241 ui/src/lib/config/runtime-config-capability.ts READ: already canonical registration; publish/finally ordering protects writes and loading state.
240 src/agents/mcp-transport.ts READ — stderr finalizer jointly flushes UTF-8 state/timer and detaches data/end/close callbacks; no repeated generic owner to remove.
240 src/gateway/server-broadcast-live-text.ts READ — connection and run-owned queues/receipts have separate abort cleanup; send ordering and backpressure remain intact.
236 src/agents/prepared-model-runtime.resources.ts READ — construction resources already use AsyncDisposableStack; remaining release tracking retains physical claims and aggregates failed closure, unlike listener notification.
235 extensions/openai/realtime-quicksilver-sideband.ts READ — Retained: startup buffering deliberately retains close/error observation across open handoff and replaces discarded-socket error guards for process safety.
235 src/gateway/cli-session-history.claude-snapshot.ts READ — per-record worker reply/error/exit listeners share settlement while worker safety listener survives all records.
235 src/infra/embedded-question-broker.ts READ — Already canonical subscribe/notify; abort handlers track question manager resolution lifecycle.
233 src/infra/kysely-sync-cache-state.ts READ — Reused canonical dispose-callback registration; native disposal remains synchronous and fail-fast.
229 ui/src/lib/agents/identity.ts READ: subscription uses registerListener; application-lifetime Gateway bindings and identity request generation retained.
226 extensions/discord/src/monitor/gateway-supervisor.ts READ — Retained: buffering, active, teardown and disposed phases have distinct delivery/logging contracts; late error guard intentionally survives supervisor disposal.
224 src/agents/session-maintenance/coordinator.ts READ — wake Set is a waiter queue with foreground/write-settlement authority; registration/removal is already directly scoped in try/finally.
217 src/process/terminal-pty-node.ts READ — Retained late exit replay, native data backpressure and fail-fast listener semantics; helper conversion would not simplify.
216 src/gateway/talk/session-registry.ts READ — failed cleanup remains retryable under original owner before replacement cleanup; immediate/synchronous outcomes and async joins preserved.
215 extensions/codex/src/session-catalog-events.ts READ: Exact-bucket unsubscribe guard is already present; notifications carry multiple arguments and asynchronous resume outcomes.
214 extensions/codex/src/app-server/server-requests.ts READ: Ordered request handlers stop at the first defined result and retain refresh work until close.
213 src/process/terminal-pty-bun.ts READ — Retained reentrant output drain, pause semantics, late exit replay and fail-fast listener ordering.
212 extensions/whatsapp/src/inbound/message-debounce.ts READ — Retained: live work notification is a one-shot wake set whose snapshot is cleared before callbacks; handler settlement races queued flushability and is not normal pub/sub.
212 src/gateway/session-event-prepared-row.ts READ — FIFO per-turn wake Set is a fairness queue, not general listener delivery; one resume per turn prevents repeated preparation.
211 extensions/diagnostics-otel/src/service-exporter-health.ts READ — Retained: event emitter names denote route-failure coalescing functions, not listener registries; state prevents one exporter route recovering another.
210 ui/src/pages/chat/chat-settings-patches.ts READ — Replaced registration with registerListener; retained snapshot dispatch and receipt ownership.
206 extensions/workboard/src/store-runtime.ts READ — Retained: multiple persistence observers isolate errors after writes succeed; extension cannot import private core notifier and no public SDK helper is exposed.
205 src/infra/worker-task-pool-resources.ts READ — One shared native-exit listener owns concurrent cleanup receipts and reference counts; operation servicing/failure custody is required.
201 src/agents/prepared-model-runtime.publication-events.ts READ — notifications and registrations already use canonical helpers.

@clawsweeper

clawsweeper Bot commented Oct 3, 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.

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 32fb7b416af2f0b9c0d842acce1d5db34c8aa325
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/runtime-materializations.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/runtime-snapshots.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/shared-store-bootstrap.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/gateway/worker-environments/placement-turn-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord channel: matrix Channel integration: matrix channel: tlon Channel integration: tlon app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling extensions: copilot size: L labels Oct 3, 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 Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 3, 2026, 8:09 AM ET / 12:09 UTC (Revision 4).

ClawSweeper review

What this changes

The PR consolidates listener registration and cleanup across runtime owners and plugins, fixes stale unsubscribe handles, and stabilizes a browser regression test.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR remains useful against current main, and no blocking introduced defect was found. The earlier migration-proof blocker is unsupported by the inspected diff.

Priority: P2
Reviewed head: 32fb7b416af2f0b9c0d842acce1d5db34c8aa325

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A sound cleanup with focused lifecycle repairs and useful reported validation; no actionable introduced bug was found.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate, and the diff does not materially change authority. Inspected owner regressions and reported browser validation are supplemental; no stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate, and the diff does not materially change authority. Inspected owner regressions and reported browser validation are supplemental; no stored-data contract changes require migration proof.
Evidence reviewed 10 items Pinned introduction and merge ownership: Reviewed the merge-base-to-head introduced hunks. The raw test-merge record has the pinned base followed by the exact PR head; its comparison preserves the same listener changes rather than removing unrelated main work.
Existing helper preserves registration semantics: The canonical helper adds the supplied callback to its Set and returns deletion of that callback. Notification substitutions preserve live or snapshot iteration at their callers and existing error isolation.
Previous compatibility blocker does not apply: The complete scope-upgrade module and introduced hunk show only an import and equivalent Set registration replacement. No persisted representation, migration, permission decision, or upgrade contract changes; the previous migration-proof request should not remain a blocker.
Findings None None.
Security None None.

How this fits together

Listeners carry runtime, channel, and Gateway updates to subscribed consumers, including the Control UI. Their cleanup owners must remove retired subscriptions without interrupting replacements or leaking temporary handlers.

flowchart TD
  A[Runtime and channel updates] --> B[Existing listener owners]
  C[Consumer subscriptions] --> B
  B --> D[Notification callbacks]
  D --> E[Agents and Control UI]
  F[Unsubscribe or shutdown] --> G[Owner cleanup]
  G --> B
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source -151, Tests +171, Other 0. Total +20 across 80 files.

View PR surface stats
Area Files Added Removed Net
Source 61 195 346 -151
Tests 18 223 52 +171
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 80 419 399 +20

Review metrics

None.

Stored data model

Persistent data-model change detected: migration/backfill/repair: ui/src/app/device-scope-upgrade.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep cleanup with the existing owners, preserving replacement subscriptions and releasing only the handlers acquired by a failed bind attempt.

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

Yes, from source: dispose a subscription, register its replacement, then repeat the old disposer; current main deletes the replacement bucket. The HTTP regression exercises synchronous native bind rejection, but neither scenario was executed in this review.

Is this the best way to solve the issue?

Yes. Reusing equivalent helpers and repairing bucket retirement at each existing owner preserves the established contracts without adding another registry or public API.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 5f52ff0f863c.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR addresses bounded subscription-lifecycle defects and cleanup without evidence of an urgent user-facing outage.
  • 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 maintainer-authored PR is exempt from the external-contributor proof gate, and the diff does not materially change authority. Inspected owner regressions and reported browser validation are supplemental; no stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction and merge ownership: Reviewed the merge-base-to-head introduced hunks. The raw test-merge record has the pinned base followed by the exact PR head; its comparison preserves the same listener changes rather than removing unrelated main work. (ff42b2f05552)
  • Existing helper preserves registration semantics: The canonical helper adds the supplied callback to its Set and returns deletion of that callback. Notification substitutions preserve live or snapshot iteration at their callers and existing error isolation. (src/shared/listeners.ts:17, 32fb7b416af2)
  • Previous compatibility blocker does not apply: The complete scope-upgrade module and introduced hunk show only an import and equivalent Set registration replacement. No persisted representation, migration, permission decision, or upgrade contract changes; the previous migration-proof request should not remain a blocker. (ui/src/app/device-scope-upgrade.ts:64, 32fb7b416af2)
  • Current main and release still need the keyed-listener repair: Inspected current main and v2026.9.8 versions of the LLM activity owner: both unconditionally delete the WeakMap bucket when an old captured Set is empty. Repeating a retired disposer therefore removes a newly registered bucket. Current main's HTTP owner also lacks the introduced synchronous-listen cleanup. (packages/ai/src/utils/llm-request-activity.ts:18, 5f52ff0f863c)
  • Concrete HTTP boundary regression: The new test uses Node's real HTTP server with invalid port 65536 and compares complete listener lists before and after rejection. The production catch removes only its two temporary listeners and retains existing error wrapping and retry behavior. Tests were inspected, not executed during this read-only review. (src/gateway/server/http-listen.test.ts:51, 32fb7b416af2)
  • Copilot dependency signal and private cutover: The changed event bridge directly consumes Copilot SDK event subscriptions; its plugin package pins @github/copilot-sdk 1.0.14. Removed Discord, Matrix, and Tlon subscription methods are private implementation surfaces absent from the inspected public barrels, and their production callers were updated together. (extensions/copilot/package.json:11, 32fb7b416af2)

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 (3 earlier review cycles)
  • reviewed 2026-10-03T09:43:13.850Z sha fca19ab7ea6c2946c0207904a361b51a69889de1 :: blocked before merge. :: none
  • reviewed 2026-10-03T10:40:19.378Z sha 6449398ad1fd89a836d195c53a73612b09204a54 :: blocked before merge. :: none
  • reviewed 2026-10-03T11:04:28.915Z sha 6449398ad1fd89a836d195c53a73612b09204a54 :: blocked before merge. :: none

Reuse canonical listener registration and matching isolated notifications. Remove single-subscriber and single-cleanup registries plus unused listener compatibility paths. Preserve callback ordering and resource ownership.

Fix stale unsubscribe handles dropping replacement observers and synchronous HTTP listen failures leaking temporary handlers. Add owner-boundary regressions for both cases.
Keep async capture finalizers on their typed owner, preserve native HTTP error handling during synchronous bind cleanup, and retain the audio waiter scheduling boundary. Prune the assertion baseline for the removed Copilot compatibility cast.
@steipete
steipete force-pushed the deslop/x11-listener-dispose-plumbing-20261003 branch from 6449398 to 32fb7b4 Compare October 3, 2026 12:02
@steipete
steipete merged commit 4c0c0c0 into main Oct 3, 2026
201 of 205 checks passed
@steipete
steipete deleted the deslop/x11-listener-dispose-plumbing-20261003 branch October 3, 2026 12:37
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

vincentkoc added a commit that referenced this pull request Oct 3, 2026
* origin/main:
  fix(test): restore fixture state and await async completion (#164222)
  refactor(sessions): stage and settle pending inputs in workers (#164284)
  fix: speech-only replies fail when models include reasoning (#164285)
  fix(nextcloud-talk): avoid webhook migration for unconfigured channels
  fix: guide background skill reviews through Workshop proposals (#164292)
  test(build): reject AI dependencies in retained config repairs
  refactor(channels): require canonical private-network settings (#163535)
  fix(memory): migrate embedding cache in bounded batches and record oversized rows (#164303)
  feat(state): incognito actor memory and Codex history routing (P5c, inactive) (#164224)
  refactor(synology-chat): remove unused route account ID (#164280)
  test(ui): await web push preference publications (#164295)
  perf(scripts): avoid compiler projects for runtime import parsing (#164243)
  fix(worktrees): create workspaces from nested Windows repositories (#164249)
  test(agents,channels,cli): remove low-value tests (batch d173) (#164302)
  perf(workboard): serve cards per board revision and push changes instead of polling (#164301)
  refactor(sqlite): deslop sqlite stores (#164271)
  chore(ui): refresh control ui locales (#164299)
  refactor(events): deslop listener and disposal plumbing (#164221)
  fix: canonicalize fresh worker reasoning signatures (#164287)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
)

* refactor(events): deslop listener and disposal plumbing

Reuse canonical listener registration and matching isolated notifications. Remove single-subscriber and single-cleanup registries plus unused listener compatibility paths. Preserve callback ordering and resource ownership.

Fix stale unsubscribe handles dropping replacement observers and synchronous HTTP listen failures leaking temporary handlers. Add owner-boundary regressions for both cases.

* test(events): preserve native HTTP listeners in cleanup regression

* fix(events): preserve callback and terminal-close contracts

Keep async capture finalizers on their typed owner, preserve native HTTP error handling during synchronous bind cleanup, and retain the audio waiter scheduling boundary. Prune the assertion baseline for the removed Copilot compatibility cast.

* test(ui): await restored roster before asserting event reads
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui channel: discord Channel integration: discord channel: matrix Channel integration: matrix channel: tlon Channel integration: tlon extensions: copilot gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: L 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