Skip to content

feat(cloud-workers): replayable worker live-event streaming into the session fanout - #105275

Merged
steipete merged 10 commits into
mainfrom
claude/cloud-workers-live-events
Jul 12, 2026
Merged

steipete merged 10 commits into
mainfrom
claude/cloud-workers-live-events

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Part of #104294 (cloud workers, milestone 2, PR 7). Builds on #104688 (worker role) and #104809 (transcript commits). Design: docs/plan/cloud-workers.md ("Session backend RPCs" — replayable live events; and docs/concepts/streaming.md).

What Problem This Solves

Transcript commits (PR 6) make a worker session's durable messages appear in the sidebar, but only at turn boundaries. This PR adds the ephemeral, replayable live-event channel so a worker session streams in real time — token deltas, tool start/finish, approvals, run-status — by translating each worker event into the SAME internal agent event and pushing it through the EXISTING fanout, so chat view / tool rows / unread-status behave identically to a local session. No parallel streaming path, no token-delta channel message (per streaming.md). Durable content still arrives via the PR-6 commit path; the live channel never writes transcript entries.

Why This Change Was Made

  • Worker live-event frame on the closed worker allowlist: runEpoch + monotonic worker seq + closed event-kind union (mirroring the local agent-event kinds) + typed payload; gateway cumulative-ACKs. Additive schema, independent feature negotiation, no version bump.
  • Gateway application validates credential-session binding and owner epoch (stale/superseded workers fenced), translates to the internal agent event, and publishes through emitAgentEventForOwner into the normal fanout.
  • Bounded process-local replay window per (session, runEpoch) with cumulative ACK + dedup + late-event fencing; a brief tunnel blip replays only the unacked tail; out-of-window forces a resync; superseded-epoch events never reach subscribers. In-memory only (transient), lifecycle-bounded.

Deep-review findings fixed pre-merge

A dedicated deep code review (verified independently) found and fixed:

  • Event-loss race (root cause): the gateway projection is deferred through a Promise while claim release was synchronous. On a mid-drain capacity reset, a just-emitted prefix event's claim could be released before its deferred projection delivered, silently dropping the event in the wired gateway (invisible to receiver-only unit tests). Fixed by keeping a capacity-reset run's claim alive until its in-flight projections settle (Promise.allSettled), while detach/supersession teardown stays immediate. Proven by a new gateway+WebSocket integration test asserting exactly-once delivery of a published prefix across a subsequent buffered-capacity event.
  • Terminal-run fence retained through projection cleanup so post-terminal events can't resurrect an ended run after window eviction (+ test).
  • Speculative pending state cleared on in-window resync (prevents a stale buffered event shadowing a renumbered one).
  • Collapsed duplicated apply()/resolveWindow validation into one owner (resolveOrCreateWindow) and removed a dead epoch branch.
  • Bounded fenced-environment LRU refreshes recency on re-fence.
  • Added the AGENTS.md-required invariant comments (fence-before-emit ordering, terminalRuns TTL bound, startup-owner cross-filter).

User Impact

Opt-in only; the worker loop that drives these events lands in PR 9. This is the real-time streaming mechanism for worker sessions. No config/changelog/version-bump changes.

Evidence

  • Blacksmith Testbox: 4 Vitest shards green (live-events receiver incl. capacity-after-prefix and terminal-fence-eviction cases; the new gateway+WS deferred-projection integration test; worker-environments suite; agent-events; server-chat agent-events; worker admission; lint-suppressions).
  • Codex fresh autoreview after the fixes: clean, no actionable findings. Local: oxlint (31 files), check:test-types, madge zero cycles, protocol:check, docs:map:check all green.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Jul 12, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 968e6afead

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +115 to +118
const hasProjectedRun = hasProjectedAgentRunForSession({
sessionKeys: [params.requestedKey, params.canonicalKey],
...(sessionId ? { sessionId } : {}),
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Keep projected active runs scoped to the requested agent

When the selected session is global, callers pass agentId/defaultAgentId so active-run checks don't leak across agents, but this new projected-run path only checks sessionKeys/sessionId. A hidden worker run registered for another agent's global session can therefore make sessions.list or chat.info for the requested agent report hasActiveRun: true with no abortable runIds; pass the agent scope through and compare it like isTrackedActiveSessionRunForKey does.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 12, 2026
@clawsweeper

clawsweeper Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 12, 2026, 8:44 AM ET / 12:44 UTC.

Summary
Adds a feature-negotiated worker live-event RPC with bounded replay and ACK handling, exclusive run ownership, session identity rebinding, and projection through the existing gateway session fanout.

PR surface: Source +1890, Tests +1030, Docs 0. Total +2920 across 33 files.

Reproducibility: yes. at source level. The deterministic paths are a cross-agent global session query and a separate subsequent expected frame that hits capacity before the prior ACKed event's deferred gateway handler runs; no real-runtime reproduction artifact is attached.

Review metrics: 2 noteworthy metrics.

  • Worker protocol surface: 1 RPC and 1 negotiated feature added. The authenticated closed worker ingress expands with authorization-, schema-, and replay-sensitive behavior.
  • Session identity surface: 5 mutation kinds added. Create, move, replace, reset, and delete notifications now drive live-worker target rebinding and fencing.

Stored data model
Persistent data-model change detected: durable storage schema: packages/gateway-protocol/src/schema/worker-admission.test.ts, durable storage schema: packages/gateway-protocol/src/schema/worker-admission.ts, durable storage schema: src/gateway/server/ws-connection/worker-connection.ts, durable storage schema: src/gateway/worker-environments/live-events.test.ts, durable storage schema: src/gateway/worker-environments/live-events.ts, durable storage schema: src/gateway/worker-environments/service.test.ts, and 25 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #104294
Summary: This PR is the replayable-live-events implementation candidate for the canonical cloud-workers feature; the two merged related PRs are prerequisites rather than replacements.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Fix both prior P2 blockers and add exact regression coverage for cross-agent global activity and the separate-frame capacity race.
  • Attach redacted final-head live reconnect/replay or session WebSocket/Control UI evidence.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR reports tests and static checks but supplies no inspectable final-head live worker reconnect/replay trace, gateway or WebSocket output, Control UI recording, or linked runtime artifact; redact credentials, IPs, phone numbers, private endpoints, and session data before posting, then update the PR body to trigger review or ask a maintainer to comment @clawsweeper re-review.

Risk before merge

  • [P1] Merging the current head can silently lose an acknowledged worker live event when a later expected frame hits active-run capacity before the earlier event's deferred gateway projection completes.
  • [P1] Merging the current head can make one agent's hidden worker run mark another agent's global session active with no corresponding abortable run ID.
  • [P1] The contributor has not supplied inspectable after-fix runtime evidence for reconnect, replay, deduplication, and final session fanout on the exact head.

Maintainer options:

  1. Fix both exact-head blockers (recommended)
    Scope projected global runs by agent, preserve earlier ACKed claims through a later capacity failure, add focused regression coverage, and provide live proof before merge.
  2. Pause the streaming slice
    Keep the merged worker-ingress and transcript prerequisites, but hold this PR if ownership and deferred-fanout lifetime need a broader redesign.

Next step before merge

  • [P1] The contributor must correct two exact-head defects and provide real behavior proof; this maintainer-protected, broad gateway/session feature is not suitable for automated repair routing.

Security
Cleared: The final diff keeps live events behind the closed authenticated worker dispatcher with feature, credential/session, owner-epoch, strict schema, and sanitization checks; no separate security or supply-chain regression was found.

Review findings

  • [P2] Scope projected global runs to the requested agent — src/gateway/server-methods/session-active-runs.ts:115-118
  • [P2] Keep ACKed claims through a later head capacity reset — src/gateway/worker-environments/live-events.ts:658-661
Review details

Best possible solution:

Preserve the existing single fanout architecture, but pass agent scope into projected-run matching and retain already-emitted claims until queued gateway projection has settled; add exact regression tests for both paths and attach redacted final-head live reconnect/replay evidence before merge.

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

Yes at source level. The deterministic paths are a cross-agent global session query and a separate subsequent expected frame that hits capacity before the prior ACKed event's deferred gateway handler runs; no real-runtime reproduction artifact is attached.

Is this the best way to solve the issue?

No on the current head. Reusing the existing fanout is the narrow maintainable architecture, but the implementation does not yet preserve its established agent-scoping and event-ownership lifetime invariants.

Full review comments:

  • [P2] Scope projected global runs to the requested agent — src/gateway/server-methods/session-active-runs.ts:115-118
    Pass agentId and defaultAgentId into projected-run matching and apply the same global-session filter used for tracked runs. Otherwise another agent's hidden worker run can make this session report active with no abortable runIds; this prior blocker remains on the final head.
    Confidence: 0.99
  • [P2] Keep ACKed claims through a later head capacity reset — src/gateway/worker-environments/live-events.ts:658-661
    A subsequent expected frame can hit capacity with buffered unset and publishedPrefix false, so this branch still calls clearWindow() and releases claims for events ACKed by earlier calls before deferred gateway fanout consumes them. Retain prior claims until projection settles or avoid clearing the existing window for this failure; the buffered-tail fix does not cover this path.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P2: This opt-in feature has two concrete correctness blockers in gateway/session behavior, but it is not yet a shipped regression affecting current users.
  • merge-risk: 🚨 message-delivery: A later capacity reset can release a claim for an acknowledged event before deferred session fanout consumes it.
  • merge-risk: 🚨 session-state: Projected active-run matching can cross the established agent boundary for global sessions.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR reports tests and static checks but supplies no inspectable final-head live worker reconnect/replay trace, gateway or WebSocket output, Control UI recording, or linked runtime artifact; redact credentials, IPs, phone numbers, private endpoints, and session data before posting, then update the PR body to trigger review or ask a maintainer to comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +1890, Tests +1030, Docs 0. Total +2920 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 19 2098 208 +1890
Tests 13 1054 24 +1030
Docs 1 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 33 3154 234 +2920

Acceptance criteria:

  • [P1] pnpm test src/gateway/server-methods/session-active-runs.test.ts.
  • [P1] pnpm test src/gateway/worker-environments/live-events.test.ts.
  • [P1] pnpm test src/gateway/session-message-events.test.ts.
  • [P1] pnpm test src/gateway/server-chat.agent-events.test.ts.

What I checked:

  • Projected-run scope defect: The projected-run lookup receives session keys and session ID but not agentId or defaultAgentId, unlike the sibling tracked-run matcher that explicitly scopes the global session by agent. (src/gateway/server-methods/session-active-runs.ts:115, d7ee851e4531)
  • ACKed claim lifetime defect: When a subsequent expected head hits capacity with no buffered frame and no prefix published in that call, the receiver clears the whole window, releasing claims belonging to events ACKed by earlier calls before deferred fanout is guaranteed to finish. (src/gateway/worker-environments/live-events.ts:658, d7ee851e4531)
  • Review continuity: Both prior P2 review threads remain unresolved, non-outdated, and attached to the exact final head; buffered-tail retention did not make the separate later-head capacity finding obsolete. (d7ee851e4531)
  • Focused test coverage: The branch covers replay, capacity, resync, terminal fencing, detach, exclusivity, session rebinding, and WebSocket local-equivalence, but not a separate next-frame capacity reset racing the prior ACKed event's deferred projection. (src/gateway/worker-environments/live-events.test.ts:176, d7ee851e4531)
  • Real behavior proof gap: The PR reports Testbox tests and static checks but contains no inspectable final-head live reconnect/replay trace, gateway or WebSocket output, recording, or linked runtime artifact. (d7ee851e4531)
  • Feature provenance: Merged worker-ingress and transcript-commit prerequisites established the cloud-worker protocol and session implementation line extended by this PR. (src/gateway/worker-environments/service.ts:1, 04f945fabe47)

Likely related people:

  • steipete: Authored and merged the worker-role and durable transcript-commit prerequisites and has prior merged history across the worker environment, gateway protocol, and session integration surfaces extended here. (role: feature owner and prerequisite merger; confidence: high; commits: b80ab618c3de, 04f945fabe47; files: src/gateway/worker-environments/service.ts, src/gateway/server/ws-connection/worker-connection.ts, packages/gateway-protocol/src/schema/worker-admission.ts)
  • vincentkoc: Current-main history attributes the active-run matcher, agent-event ownership baseline, and recent session-accessor work to this contributor, including the global-agent boundary the PR must preserve. (role: recent session and agent-runtime contributor; confidence: medium; commits: f8db32b938aa, 5e453f3c726a; files: src/gateway/server-methods/session-active-runs.ts, src/infra/agent-events.ts, src/config/sessions/session-accessor.sqlite.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (3 earlier review cycles)
  • reviewed 2026-07-12T10:28:54.168Z sha 968e6afeadf6e5cef2ab6baebd96135770826af2 :: needs real behavior proof before merge. :: [P2] Scope projected global runs to the requested agent | [P3] Await the owned-event projection in the test
  • reviewed 2026-07-12T11:51:00.234Z sha 2119dd51bd1989f0858298c261f7e4ff3dd2aca8 :: needs real behavior proof before merge. :: [P2] Scope projected global runs to the requested agent
  • reviewed 2026-07-12T11:58:32.025Z sha 2119dd51bd1989f0858298c261f7e4ff3dd2aca8 :: needs real behavior proof before merge. :: [P2] Scope projected global runs to the requested agent | [P2] Keep ACKed live claims until queued projections complete

@steipete
steipete force-pushed the claude/cloud-workers-live-events branch from 968e6af to 2119dd5 Compare July 12, 2026 11:43

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2119dd51bd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}
if (failed.details.reason === "capacity-exceeded" && !publishedPrefix) {
// A fresh head cannot advance. Reset its cursor and release every claim.
clearWindow(window);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Keep ACKed live claims until queued projections run

When a new head event hits capacity-exceeded, this immediately clearWindow()s and releases every existing claim, including prior events that were already ACKed. Gateway fanout is deferred through dispatchEventHandler() in src/gateway/server-runtime-subscriptions.ts, and createAgentEventHandler() drops owned events once getAgentRunContextOwnerStatus() is no longer active; so if a worker sends a second run before the async handler processes the first ACKed live event, the first event can be silently lost from session subscribers. Defer releasing existing claims until the in-flight projection has settled, or avoid gating already-emitted events on a claim that this reset releases.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 12, 2026
@steipete
steipete force-pushed the claude/cloud-workers-live-events branch from 2119dd5 to d7ee851 Compare July 12, 2026 12:37
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 12, 2026
@steipete
steipete merged commit 4289c6c into main Jul 12, 2026
114 of 116 checks passed
@steipete
steipete deleted the claude/cloud-workers-live-events branch July 12, 2026 12:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 13, 2026
…session fanout (openclaw#105275)

* feat(protocol): add worker live-event frames

* feat(gateway): fan out replayable worker live events

* feat(gateway): add worker live-event replay receiver

* docs(protocol): document worker live events

* fix(gateway): preserve deferred worker live events

* test(gateway): cover deferred worker event projection

* refactor(gateway): revert async projection layer

* fix(gateway): retain buffered worker live events

* fix(gateway): guard buffered terminal admission

* fix(plugin-sdk): trim worker live-event declarations
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 docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant