Repository navigation
feat(realtime): implement protocol v2 - #1349
Closed
realcodesiman wants to merge 10 commits into
Closed
realcodesiman wants to merge 10 commits into
realcodesiman wants to merge 10 commits into
Conversation
- gateway rejects new sockets past REALTIME_MAX_CONNECTIONS with close code 4003 and a jittered retryAfter hint instead of degrading - windowed structured metrics for the gateway (sends, publishes, drops, overload closes, token rejections, active shards) and the relay publisher (events, bytes, flushes, errors by event type) - consolidate the duplicated stream-id comparator into isRealtimeSeqAfter in @chatbotx.io/realtime-protocol, used by the gateway, stream reader, workspace provider, and webchat socket - extract createWebchatFrameHandler for the guest webchat socket, adding the heartbeat-frame and duplicate-delivery guards the workspace socket already had - move remaining direct repository/db access in builder actions and worker handlers behind business services (messageService, integrationWebchatService.findOrCreateGuestConversation, integrationService.create, whatsappVoipCallService, whatsappFlowService, workspaceMemberService) per the action/API -> service -> repository chain
- scope guest pub/sub topics by workspace id, not just guest conversation id, to stop guest events leaking across workspaces when conversation ids collide - stop blocking message/typing handlers on realtime publish; fire and forget with error logging instead (webchat integration, flow-step sender, workspace message actions) - cap connections per workspace and per guest, add a forced connection lifetime, and let a malformed stream entry log and skip instead of aborting the whole replay batch - fix whatsapp voip signaling to use Promise.allSettled so one rejected notification can't swallow the rest - persist the server's overload retryAfter across foreground/online events so waking tabs don't reconnect in lockstep - on resync, invalidate the full query cache (not just chat) since other cached views can drift during a gap; refetch latest guest messages on reconnect - add guest token route rate limiting and align docs (AGENTS.md/integration-channel skill) with the REALTIME_PROXY_URL rename and the custom WebSocket transport
Unused skill not referenced by any workflow; drop it and its CLAUDE.md routing entry.
…aths - RealtimeSocket: only reset reconnect attempt counter after the socket stays open past minUptimeBeforeResetMs, so a resync-then-immediate-close loop keeps backing off instead of hot-looping; stop reconnecting entirely once getUrl rejects with RealtimeFatalError (e.g. a 401/403 token mint), surfacing a terminal "closed" connectionStatus to the webchat widget with a reload affordance - realtime-token route: reject legacy digits-only guest conversation ids outright (400) instead of looking up a possibly-owned conversation, since those ids carry no proof of caller identity - gateway: cap total guest connections per workspace (REALTIME_MAX_GUEST_CONNECTIONS_PER_WORKSPACE) in addition to the per-guest-conversation cap, so one tenant's webchat spike can't starve the global guest pool; cork paired writeStatus+end calls; listen() resolves the bound port for port:0 callers - realtime-stream-publisher: open the Redis connection with commandTimeout/maxRetriesPerRequest so a hung xadd during an outage can't stall fire-and-forget and awaited publishers forever - realtime-broadcast: retry transient revoke-append failures - promote two swallowed logger.warn calls to logger.error where the failure is actionable (workspace member deletion, inbox team lookup)
- Distinguish terminal member-revoke (deleted) from a non-terminal reauth (permissions/team change or lifetime expiry) with new close code 4004; stale revokes older than a reconnect's token iat are ignored instead of killing an already-reauthorized socket - Count in-flight upgrades per workspace/guest key so a burst of concurrent connects can't all race past the same stale capacity check - Parse coalesced workspace-events stream records event-by-event so one envelope a rolling-deploy skew can't parse doesn't drop the whole batch; force an affected workspace's sockets to resync instead of silently running with a gap - Mint-401/403 on the workspace connect token now throws a RealtimeFatalError instead of retrying forever against a dead credential; guest widget flips to "closed" after sustained non-fatal retry failures instead of showing "connecting" forever - Defer the resync-count bump (which drives a full invalidateQueries) until the reconnect actually opens, not at close time, closing the gap where an event could land uncaught - Validate the messageCreated wire payload with zod instead of an unchecked cast; add coerced-date fields to MessageResource so the JSON round trip parses - Bounded retry on the realtime stream publish and the guest-facing publish path so a transient Redis blip doesn't silently drop an event with no gap signal - Release the streamReader workspace slot when res.upgrade() itself throws post-activation, and coalesce repeated token-rejection logs into one err-carrying warn per window - Add WorkspaceRealtimeStatusBanner surfacing sustained connection trouble to the user instead of a silently stale inbox
- gateway: jitter connection-lifetime timers (+/-15%) so sockets opened around the same time don't reauth-close in lockstep; drop retained replay entries once consumed instead of holding them for the socket's whole lifetime - delivery/gateway: send an empty-batch cursor frame when a reconnect replays zero live records, so a quiet tab gets a real stream cursor instead of a synthetic "0-0" that forces a full resync next reconnect - stream-reader/gateway: count and log events dropped from a parsed-but-partially-invalid coalesced record, folding them into the malformedRecords metric instead of discarding them silently - realtime-token route: add a per-workspace rate limit on guest token minting, independent of the spoofable per-IP check, so one workspace can't alone exhaust the gateway's per-workspace guest connection cap - main: catch gateway.close()/listen() errors and force-exit on a failed start instead of hanging on open redis/stream handles - webchat-realtime: dedupe the connect-failure bookkeeping shared by onClose/onError - guest-session-store: sort merged realtime messages by createdAt so out-of-order delivery can't shuffle the transcript
- reject reconnects from a still-unexpired pre-revoke token even when the connect carries no lastSeq, via a TTL'd realtime:revoked marker checked against the token's iat - extract loadReplay into apps/realtime/src/replay.ts and bound its shard scan so a noisy-neighbor-heavy shard can't turn replay into an unbounded Redis scan - resync every workspace sharing a shard when an invalid stream record has no recoverable workspaceId, and resync every locally-connected workspace after the stream reader's Redis connection recovers from an error - stop RealtimeSocket from double-firing onError+onClose for the same WebSocket failure; give the client heartbeat timeout its own named close code instead of a bare 4000 - route message-send-error realtime events (recordMessageSendError / clearMessageSendError) to the conversation's assigned team/user instead of broadcasting unrouted - extract incrementKeyedCount/decrementKeyedCount into a shared helper; allow presenceReportIntervalMs override for tests - update docs/realtime.md and .env.example for the above
This was referenced Oct 2, 2026
Contributor
Author
|
Split into 3 stacked, independently reviewable PRs (merge order; intended to merge together with no release in between):
Each PR builds/typechecks/tests standalone and includes the round-5 review fixes relevant to its scope. Leaving this PR open until the stack is reviewed/merged. |
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch.
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
- Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review.
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
A verification replay (pr5's own diff applied onto current main) found that these 3 channel-select pages + create-first-workspace.ts (and their 4 tests) were accidentally included in this PR's checkout during reconciliation — confirmed via `git diff <merge-base> feat/realtime-protocol-v2-pr5` that the original PR #1349 makes ZERO changes to any of them. Carrying them through the split had reverted main's own later sessionExpired error-handling feature on these files back to its pre-feature state. Restored to origin/main's content, removing them from this PR's scope entirely — they were never part of the realtime work.
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch.
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
- Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review.
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch.
realcodesiman
added a commit
that referenced
this pull request
Oct 2, 2026
- Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review.
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
…PR 1/3)
Checkout of apps/worker, integrations/chatbotx, integrations/webchat,
packages/{realtime-protocol,business,database,redis,sdk}, and the builder
server actions that publish realtime events, from the reconciled
feat/realtime-protocol-v2-pr5 + origin/main merge.
Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps
packages/partysocket-config in place; packages/realtime-protocol is
additive. integrations/webchat folded into this PR (not pr5c) because
apps/worker depends on it directly and its typing-broadcast handlers
already use the new publishGuestRealtimeEvent shape that
packages/business introduces here.
Round-5 fixes land in follow-up commits on this branch.
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
…h side
- Make route required for conversation-scoped event types in
RealtimeEventData via a discriminated union, enforced at both the TS
type level and a zod superRefine on the workspace-broadcast envelope.
Fixes the 6 routeless publish sites: delete-message, edit-message,
call-summary, conversation/service.ts's updateReadStatus and
markReadByOutbound, and the two messageCreated sites introduced by
the main-merge reconciliation (record-delivered-private-reply,
thread-control/service.ts). whatsapp-call-permission-grant.ts was
already routeless-safe (not conversation-scoped).
- Add a RealtimeTargetedEventData type (route always optional) for the
single-recipient guest/member-send delivery paths, which are never
route-filtered.
- Add an iatMs claim (millisecond-precision mint time) to member-connect
tokens, fixing the floored-iat false-401 on a same-second reconnect.
- Make signRealtimeToken private; add signPresenceReportToken /
verifyPresenceReportToken so every purpose mints through its own typed
wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to
use the new wrapper.
- Export RealtimeCloseCode.
- Store the raw append (not a .catch-wrapped copy) in
inFlightByWorkspace so the shutdown drain's allSettled can observe and
log a real failure.
- Report a revoke failure to the caller: delete/update-workspace-member
actions return { revokeWarning }, surfaced as a toast; inbox-team
service's 5 call sites keep their existing logged-and-swallowed
best-effort retry (unchanged scope per the fix's own "cheap" framing).
- Tests: messageIdAssigned routing (new, was uncovered), iatMs round
trip, route-required schema refine, presence-report token wrappers.
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
…PR 1/3)
Checkout of apps/worker, integrations/chatbotx, integrations/webchat,
packages/{realtime-protocol,business,database,redis,sdk}, and the builder
server actions that publish realtime events, from the reconciled
feat/realtime-protocol-v2-pr5 + origin/main merge.
Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps
packages/partysocket-config in place; packages/realtime-protocol is
additive. integrations/webchat folded into this PR (not pr5c) because
apps/worker depends on it directly and its typing-broadcast handlers
already use the new publishGuestRealtimeEvent shape that
packages/business introduces here.
Round-5 fixes land in follow-up commits on this branch.
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
…h side
- Make route required for conversation-scoped event types in
RealtimeEventData via a discriminated union, enforced at both the TS
type level and a zod superRefine on the workspace-broadcast envelope.
Fixes the 6 routeless publish sites: delete-message, edit-message,
call-summary, conversation/service.ts's updateReadStatus and
markReadByOutbound, and the two messageCreated sites introduced by
the main-merge reconciliation (record-delivered-private-reply,
thread-control/service.ts). whatsapp-call-permission-grant.ts was
already routeless-safe (not conversation-scoped).
- Add a RealtimeTargetedEventData type (route always optional) for the
single-recipient guest/member-send delivery paths, which are never
route-filtered.
- Add an iatMs claim (millisecond-precision mint time) to member-connect
tokens, fixing the floored-iat false-401 on a same-second reconnect.
- Make signRealtimeToken private; add signPresenceReportToken /
verifyPresenceReportToken so every purpose mints through its own typed
wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to
use the new wrapper.
- Export RealtimeCloseCode.
- Store the raw append (not a .catch-wrapped copy) in
inFlightByWorkspace so the shutdown drain's allSettled can observe and
log a real failure.
- Report a revoke failure to the caller: delete/update-workspace-member
actions return { revokeWarning }, surfaced as a toast; inbox-team
service's 5 call sites keep their existing logged-and-swallowed
best-effort retry (unchanged scope per the fix's own "cheap" framing).
- Tests: messageIdAssigned routing (new, was uncovered), iatMs round
trip, route-required schema refine, presence-report token wrappers.
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
…PR 1/3) (#1392) * feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) Checkout of apps/worker, integrations/chatbotx, integrations/webchat, packages/{realtime-protocol,business,database,redis,sdk}, and the builder server actions that publish realtime events, from the reconciled feat/realtime-protocol-v2-pr5 + origin/main merge. Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps packages/partysocket-config in place; packages/realtime-protocol is additive. integrations/webchat folded into this PR (not pr5c) because apps/worker depends on it directly and its typing-broadcast handlers already use the new publishGuestRealtimeEvent shape that packages/business introduces here. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): close PR #1349 round-5 findings for contracts + publish side - Make route required for conversation-scoped event types in RealtimeEventData via a discriminated union, enforced at both the TS type level and a zod superRefine on the workspace-broadcast envelope. Fixes the 6 routeless publish sites: delete-message, edit-message, call-summary, conversation/service.ts's updateReadStatus and markReadByOutbound, and the two messageCreated sites introduced by the main-merge reconciliation (record-delivered-private-reply, thread-control/service.ts). whatsapp-call-permission-grant.ts was already routeless-safe (not conversation-scoped). - Add a RealtimeTargetedEventData type (route always optional) for the single-recipient guest/member-send delivery paths, which are never route-filtered. - Add an iatMs claim (millisecond-precision mint time) to member-connect tokens, fixing the floored-iat false-401 on a same-second reconnect. - Make signRealtimeToken private; add signPresenceReportToken / verifyPresenceReportToken so every purpose mints through its own typed wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to use the new wrapper. - Export RealtimeCloseCode. - Store the raw append (not a .catch-wrapped copy) in inFlightByWorkspace so the shutdown drain's allSettled can observe and log a real failure. - Report a revoke failure to the caller: delete/update-workspace-member actions return { revokeWarning }, surfaced as a toast; inbox-team service's 5 call sites keep their existing logged-and-swallowed best-effort retry (unchanged scope per the fix's own "cheap" framing). - Tests: messageIdAssigned routing (new, was uncovered), iatMs round trip, route-required schema refine, presence-report token wrappers. * test(builder): fix tests left stale by the realtime-protocol migration These test files were never brought over when the realtime-protocol v2 contracts landed, so they still mocked the old broadcastToWorkspaceParty/partysocket-config/database-repository shapes, or the old IntegrationContext.platform shape (internalRealtimeUrl/getRealtimeBroadcastAuthHeaders instead of publishGuestRealtimeEvent), instead of what their sources now use (67 failing/type-erroring tests across 6 builder files). Also pulls in the matching platform-context mock fix for 7 marketing integrations whose tests shared the old IntegrationContext shape. delete-message.action.ts/edit-message.action.ts also needed routeForConversation added to their realtime-protocol mock now that route is required on conversation-scoped events (round-5 finding #1). * fix(realtime): add a route-less batch envelope schema for guest sockets realtimeBatchEnvelopeSchema's route-required refine is workspace- broadcast-only (round-5 finding #1), but the guest webchat client was reusing the same schema for its own wire frames — a guest socket's delivery is never route-filtered, so every conversation-scoped event it receives (e.g. messageCreated) correctly has no route, meaning the client would reject every real frame it gets. Adds realtimeGuestBatchEnvelopeSchema (bare envelope, no route requirement) for guest clients to use instead. * feat(realtime): add createRealtimeFrameReader shared client frame parser Both realtime clients (workspace provider, webchat guest client) duplicate the same JSON-parse/heartbeat-filter/batch-schema-validate/ seq-dedup logic, differing only in which batch envelope schema they validate against and how they dispatch each event afterward. createRealtimeFrameReader extracts the shared parsing/dedup mechanics, plus a throttled (2s default) onResyncNeeded so a burst of invalid batches — or per-event validation failures a caller reports via reportInvalidEvent, sharing the same throttle window — can't storm a resync. Used by both clients in PR 3/3. * fix(realtime): route the whatsappCallPermissionUpdated broadcast The 6th routeless publish site from the round-5 review: a permission- mode change (whether outbound calling is enabled for this contact) is most relevant to whoever is actually assigned to the conversation, unlike a ringing/active call's workspace-wide broadcast (the other whatsappCall* event types) — treat it as conversation-scoped like message events. Moves RealtimeEventWhatsappCallPermissionUpdated into RealtimeConversationScopedEventData, adds it to CONVERSATION_SCOPED_EVENT_TYPES, widens ChannelSendErrorContext's conversation pick to include assignedUserId/assignedInboxTeamId (both real callers already have the full ConversationModel), and routes the publish call via routeForConversation. * test(realtime): cover whatsappCallPermissionUpdated's route requirement Schema-level regression for the 6th routeless publish site (round-5 finding #1): confirms the newly added CONVERSATION_SCOPED_EVENT_TYPES membership actually rejects a routeless batch entry and accepts a routed one, not just the worker-level reconciler test. * fix(realtime): harden event delivery and member revocation * fix(realtime): harden stream delivery and assignment routing * fix(connections): update refresh platform stub * fix(realtime): resolve rebase integration conflicts * chore: fix test * feat(realtime): relay workspace events through Redis streams * fix(realtime): harden Redis stream relay cutover * fix(realtime): harden stream delivery and shutdown * refactor(worker): remove realtime drain re-export * fix(realtime): await event delivery before request completion
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch.
realcodesiman
added a commit
that referenced
this pull request
Oct 18, 2026
- Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review.
realcodesiman
added a commit
that referenced
this pull request
Oct 19, 2026
* feat(realtime): add the uWebSockets gateway (PR 2/3) Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): round-5 review fixes for the uWS gateway (PR 2/3) - Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review. * test(builder): add missing coverage for the guest/member connect token routes realtime-connect-token-api.test.ts and guest-realtime-token-route.test.ts test features/realtime/api/private.ts and app/api/guest/realtime-token/route.ts respectively, both already part of this PR, but were never brought over. * fix(realtime): preserve token issuance across rebase * fix(realtime): harden gateway replay and guest token issuance * fix(realtime): harden gateway socket lifecycle * fix(realtime): harden stream recovery and guest token handling * fix(realtime): harden gateway fault handling * docs(realtime): document gateway listener settings * revert(realtime): remove gateway listener documentation
realcodesiman
added a commit
that referenced
this pull request
Oct 19, 2026
…PR 1/3) (#1392) * feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) Checkout of apps/worker, integrations/chatbotx, integrations/webchat, packages/{realtime-protocol,business,database,redis,sdk}, and the builder server actions that publish realtime events, from the reconciled feat/realtime-protocol-v2-pr5 + origin/main merge. Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps packages/partysocket-config in place; packages/realtime-protocol is additive. integrations/webchat folded into this PR (not pr5c) because apps/worker depends on it directly and its typing-broadcast handlers already use the new publishGuestRealtimeEvent shape that packages/business introduces here. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): close PR #1349 round-5 findings for contracts + publish side - Make route required for conversation-scoped event types in RealtimeEventData via a discriminated union, enforced at both the TS type level and a zod superRefine on the workspace-broadcast envelope. Fixes the 6 routeless publish sites: delete-message, edit-message, call-summary, conversation/service.ts's updateReadStatus and markReadByOutbound, and the two messageCreated sites introduced by the main-merge reconciliation (record-delivered-private-reply, thread-control/service.ts). whatsapp-call-permission-grant.ts was already routeless-safe (not conversation-scoped). - Add a RealtimeTargetedEventData type (route always optional) for the single-recipient guest/member-send delivery paths, which are never route-filtered. - Add an iatMs claim (millisecond-precision mint time) to member-connect tokens, fixing the floored-iat false-401 on a same-second reconnect. - Make signRealtimeToken private; add signPresenceReportToken / verifyPresenceReportToken so every purpose mints through its own typed wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to use the new wrapper. - Export RealtimeCloseCode. - Store the raw append (not a .catch-wrapped copy) in inFlightByWorkspace so the shutdown drain's allSettled can observe and log a real failure. - Report a revoke failure to the caller: delete/update-workspace-member actions return { revokeWarning }, surfaced as a toast; inbox-team service's 5 call sites keep their existing logged-and-swallowed best-effort retry (unchanged scope per the fix's own "cheap" framing). - Tests: messageIdAssigned routing (new, was uncovered), iatMs round trip, route-required schema refine, presence-report token wrappers. * test(builder): fix tests left stale by the realtime-protocol migration These test files were never brought over when the realtime-protocol v2 contracts landed, so they still mocked the old broadcastToWorkspaceParty/partysocket-config/database-repository shapes, or the old IntegrationContext.platform shape (internalRealtimeUrl/getRealtimeBroadcastAuthHeaders instead of publishGuestRealtimeEvent), instead of what their sources now use (67 failing/type-erroring tests across 6 builder files). Also pulls in the matching platform-context mock fix for 7 marketing integrations whose tests shared the old IntegrationContext shape. delete-message.action.ts/edit-message.action.ts also needed routeForConversation added to their realtime-protocol mock now that route is required on conversation-scoped events (round-5 finding #1). * fix(realtime): add a route-less batch envelope schema for guest sockets realtimeBatchEnvelopeSchema's route-required refine is workspace- broadcast-only (round-5 finding #1), but the guest webchat client was reusing the same schema for its own wire frames — a guest socket's delivery is never route-filtered, so every conversation-scoped event it receives (e.g. messageCreated) correctly has no route, meaning the client would reject every real frame it gets. Adds realtimeGuestBatchEnvelopeSchema (bare envelope, no route requirement) for guest clients to use instead. * feat(realtime): add createRealtimeFrameReader shared client frame parser Both realtime clients (workspace provider, webchat guest client) duplicate the same JSON-parse/heartbeat-filter/batch-schema-validate/ seq-dedup logic, differing only in which batch envelope schema they validate against and how they dispatch each event afterward. createRealtimeFrameReader extracts the shared parsing/dedup mechanics, plus a throttled (2s default) onResyncNeeded so a burst of invalid batches — or per-event validation failures a caller reports via reportInvalidEvent, sharing the same throttle window — can't storm a resync. Used by both clients in PR 3/3. * fix(realtime): route the whatsappCallPermissionUpdated broadcast The 6th routeless publish site from the round-5 review: a permission- mode change (whether outbound calling is enabled for this contact) is most relevant to whoever is actually assigned to the conversation, unlike a ringing/active call's workspace-wide broadcast (the other whatsappCall* event types) — treat it as conversation-scoped like message events. Moves RealtimeEventWhatsappCallPermissionUpdated into RealtimeConversationScopedEventData, adds it to CONVERSATION_SCOPED_EVENT_TYPES, widens ChannelSendErrorContext's conversation pick to include assignedUserId/assignedInboxTeamId (both real callers already have the full ConversationModel), and routes the publish call via routeForConversation. * test(realtime): cover whatsappCallPermissionUpdated's route requirement Schema-level regression for the 6th routeless publish site (round-5 finding #1): confirms the newly added CONVERSATION_SCOPED_EVENT_TYPES membership actually rejects a routeless batch entry and accepts a routed one, not just the worker-level reconciler test. * fix(realtime): harden event delivery and member revocation * fix(realtime): harden stream delivery and assignment routing * fix(connections): update refresh platform stub * fix(realtime): resolve rebase integration conflicts * chore: fix test * feat(realtime): relay workspace events through Redis streams * fix(realtime): harden Redis stream relay cutover * fix(realtime): harden stream delivery and shutdown * refactor(worker): remove realtime drain re-export * fix(realtime): await event delivery before request completion
realcodesiman
added a commit
that referenced
this pull request
Oct 19, 2026
* feat(realtime): add the uWebSockets gateway (PR 2/3) Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): round-5 review fixes for the uWS gateway (PR 2/3) - Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review. * test(builder): add missing coverage for the guest/member connect token routes realtime-connect-token-api.test.ts and guest-realtime-token-route.test.ts test features/realtime/api/private.ts and app/api/guest/realtime-token/route.ts respectively, both already part of this PR, but were never brought over. * fix(realtime): preserve token issuance across rebase * fix(realtime): harden gateway replay and guest token issuance * fix(realtime): harden gateway socket lifecycle * fix(realtime): harden stream recovery and guest token handling * fix(realtime): harden gateway fault handling * docs(realtime): document gateway listener settings * revert(realtime): remove gateway listener documentation
realcodesiman
added a commit
that referenced
this pull request
Oct 20, 2026
…PR 1/3) (#1392) * feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) Checkout of apps/worker, integrations/chatbotx, integrations/webchat, packages/{realtime-protocol,business,database,redis,sdk}, and the builder server actions that publish realtime events, from the reconciled feat/realtime-protocol-v2-pr5 + origin/main merge. Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps packages/partysocket-config in place; packages/realtime-protocol is additive. integrations/webchat folded into this PR (not pr5c) because apps/worker depends on it directly and its typing-broadcast handlers already use the new publishGuestRealtimeEvent shape that packages/business introduces here. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): close PR #1349 round-5 findings for contracts + publish side - Make route required for conversation-scoped event types in RealtimeEventData via a discriminated union, enforced at both the TS type level and a zod superRefine on the workspace-broadcast envelope. Fixes the 6 routeless publish sites: delete-message, edit-message, call-summary, conversation/service.ts's updateReadStatus and markReadByOutbound, and the two messageCreated sites introduced by the main-merge reconciliation (record-delivered-private-reply, thread-control/service.ts). whatsapp-call-permission-grant.ts was already routeless-safe (not conversation-scoped). - Add a RealtimeTargetedEventData type (route always optional) for the single-recipient guest/member-send delivery paths, which are never route-filtered. - Add an iatMs claim (millisecond-precision mint time) to member-connect tokens, fixing the floored-iat false-401 on a same-second reconnect. - Make signRealtimeToken private; add signPresenceReportToken / verifyPresenceReportToken so every purpose mints through its own typed wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to use the new wrapper. - Export RealtimeCloseCode. - Store the raw append (not a .catch-wrapped copy) in inFlightByWorkspace so the shutdown drain's allSettled can observe and log a real failure. - Report a revoke failure to the caller: delete/update-workspace-member actions return { revokeWarning }, surfaced as a toast; inbox-team service's 5 call sites keep their existing logged-and-swallowed best-effort retry (unchanged scope per the fix's own "cheap" framing). - Tests: messageIdAssigned routing (new, was uncovered), iatMs round trip, route-required schema refine, presence-report token wrappers. * test(builder): fix tests left stale by the realtime-protocol migration These test files were never brought over when the realtime-protocol v2 contracts landed, so they still mocked the old broadcastToWorkspaceParty/partysocket-config/database-repository shapes, or the old IntegrationContext.platform shape (internalRealtimeUrl/getRealtimeBroadcastAuthHeaders instead of publishGuestRealtimeEvent), instead of what their sources now use (67 failing/type-erroring tests across 6 builder files). Also pulls in the matching platform-context mock fix for 7 marketing integrations whose tests shared the old IntegrationContext shape. delete-message.action.ts/edit-message.action.ts also needed routeForConversation added to their realtime-protocol mock now that route is required on conversation-scoped events (round-5 finding #1). * fix(realtime): add a route-less batch envelope schema for guest sockets realtimeBatchEnvelopeSchema's route-required refine is workspace- broadcast-only (round-5 finding #1), but the guest webchat client was reusing the same schema for its own wire frames — a guest socket's delivery is never route-filtered, so every conversation-scoped event it receives (e.g. messageCreated) correctly has no route, meaning the client would reject every real frame it gets. Adds realtimeGuestBatchEnvelopeSchema (bare envelope, no route requirement) for guest clients to use instead. * feat(realtime): add createRealtimeFrameReader shared client frame parser Both realtime clients (workspace provider, webchat guest client) duplicate the same JSON-parse/heartbeat-filter/batch-schema-validate/ seq-dedup logic, differing only in which batch envelope schema they validate against and how they dispatch each event afterward. createRealtimeFrameReader extracts the shared parsing/dedup mechanics, plus a throttled (2s default) onResyncNeeded so a burst of invalid batches — or per-event validation failures a caller reports via reportInvalidEvent, sharing the same throttle window — can't storm a resync. Used by both clients in PR 3/3. * fix(realtime): route the whatsappCallPermissionUpdated broadcast The 6th routeless publish site from the round-5 review: a permission- mode change (whether outbound calling is enabled for this contact) is most relevant to whoever is actually assigned to the conversation, unlike a ringing/active call's workspace-wide broadcast (the other whatsappCall* event types) — treat it as conversation-scoped like message events. Moves RealtimeEventWhatsappCallPermissionUpdated into RealtimeConversationScopedEventData, adds it to CONVERSATION_SCOPED_EVENT_TYPES, widens ChannelSendErrorContext's conversation pick to include assignedUserId/assignedInboxTeamId (both real callers already have the full ConversationModel), and routes the publish call via routeForConversation. * test(realtime): cover whatsappCallPermissionUpdated's route requirement Schema-level regression for the 6th routeless publish site (round-5 finding #1): confirms the newly added CONVERSATION_SCOPED_EVENT_TYPES membership actually rejects a routeless batch entry and accepts a routed one, not just the worker-level reconciler test. * fix(realtime): harden event delivery and member revocation * fix(realtime): harden stream delivery and assignment routing * fix(connections): update refresh platform stub * fix(realtime): resolve rebase integration conflicts * chore: fix test * feat(realtime): relay workspace events through Redis streams * fix(realtime): harden Redis stream relay cutover * fix(realtime): harden stream delivery and shutdown * refactor(worker): remove realtime drain re-export * fix(realtime): await event delivery before request completion
realcodesiman
added a commit
that referenced
this pull request
Oct 20, 2026
* feat(realtime): add the uWebSockets gateway (PR 2/3) Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): round-5 review fixes for the uWS gateway (PR 2/3) - Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review. * test(builder): add missing coverage for the guest/member connect token routes realtime-connect-token-api.test.ts and guest-realtime-token-route.test.ts test features/realtime/api/private.ts and app/api/guest/realtime-token/route.ts respectively, both already part of this PR, but were never brought over. * fix(realtime): preserve token issuance across rebase * fix(realtime): harden gateway replay and guest token issuance * fix(realtime): harden gateway socket lifecycle * fix(realtime): harden stream recovery and guest token handling * fix(realtime): harden gateway fault handling * docs(realtime): document gateway listener settings * revert(realtime): remove gateway listener documentation
realcodesiman
added a commit
that referenced
this pull request
Oct 20, 2026
…PR 1/3) (#1392) * feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) Checkout of apps/worker, integrations/chatbotx, integrations/webchat, packages/{realtime-protocol,business,database,redis,sdk}, and the builder server actions that publish realtime events, from the reconciled feat/realtime-protocol-v2-pr5 + origin/main merge. Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps packages/partysocket-config in place; packages/realtime-protocol is additive. integrations/webchat folded into this PR (not pr5c) because apps/worker depends on it directly and its typing-broadcast handlers already use the new publishGuestRealtimeEvent shape that packages/business introduces here. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): close PR #1349 round-5 findings for contracts + publish side - Make route required for conversation-scoped event types in RealtimeEventData via a discriminated union, enforced at both the TS type level and a zod superRefine on the workspace-broadcast envelope. Fixes the 6 routeless publish sites: delete-message, edit-message, call-summary, conversation/service.ts's updateReadStatus and markReadByOutbound, and the two messageCreated sites introduced by the main-merge reconciliation (record-delivered-private-reply, thread-control/service.ts). whatsapp-call-permission-grant.ts was already routeless-safe (not conversation-scoped). - Add a RealtimeTargetedEventData type (route always optional) for the single-recipient guest/member-send delivery paths, which are never route-filtered. - Add an iatMs claim (millisecond-precision mint time) to member-connect tokens, fixing the floored-iat false-401 on a same-second reconnect. - Make signRealtimeToken private; add signPresenceReportToken / verifyPresenceReportToken so every purpose mints through its own typed wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to use the new wrapper. - Export RealtimeCloseCode. - Store the raw append (not a .catch-wrapped copy) in inFlightByWorkspace so the shutdown drain's allSettled can observe and log a real failure. - Report a revoke failure to the caller: delete/update-workspace-member actions return { revokeWarning }, surfaced as a toast; inbox-team service's 5 call sites keep their existing logged-and-swallowed best-effort retry (unchanged scope per the fix's own "cheap" framing). - Tests: messageIdAssigned routing (new, was uncovered), iatMs round trip, route-required schema refine, presence-report token wrappers. * test(builder): fix tests left stale by the realtime-protocol migration These test files were never brought over when the realtime-protocol v2 contracts landed, so they still mocked the old broadcastToWorkspaceParty/partysocket-config/database-repository shapes, or the old IntegrationContext.platform shape (internalRealtimeUrl/getRealtimeBroadcastAuthHeaders instead of publishGuestRealtimeEvent), instead of what their sources now use (67 failing/type-erroring tests across 6 builder files). Also pulls in the matching platform-context mock fix for 7 marketing integrations whose tests shared the old IntegrationContext shape. delete-message.action.ts/edit-message.action.ts also needed routeForConversation added to their realtime-protocol mock now that route is required on conversation-scoped events (round-5 finding #1). * fix(realtime): add a route-less batch envelope schema for guest sockets realtimeBatchEnvelopeSchema's route-required refine is workspace- broadcast-only (round-5 finding #1), but the guest webchat client was reusing the same schema for its own wire frames — a guest socket's delivery is never route-filtered, so every conversation-scoped event it receives (e.g. messageCreated) correctly has no route, meaning the client would reject every real frame it gets. Adds realtimeGuestBatchEnvelopeSchema (bare envelope, no route requirement) for guest clients to use instead. * feat(realtime): add createRealtimeFrameReader shared client frame parser Both realtime clients (workspace provider, webchat guest client) duplicate the same JSON-parse/heartbeat-filter/batch-schema-validate/ seq-dedup logic, differing only in which batch envelope schema they validate against and how they dispatch each event afterward. createRealtimeFrameReader extracts the shared parsing/dedup mechanics, plus a throttled (2s default) onResyncNeeded so a burst of invalid batches — or per-event validation failures a caller reports via reportInvalidEvent, sharing the same throttle window — can't storm a resync. Used by both clients in PR 3/3. * fix(realtime): route the whatsappCallPermissionUpdated broadcast The 6th routeless publish site from the round-5 review: a permission- mode change (whether outbound calling is enabled for this contact) is most relevant to whoever is actually assigned to the conversation, unlike a ringing/active call's workspace-wide broadcast (the other whatsappCall* event types) — treat it as conversation-scoped like message events. Moves RealtimeEventWhatsappCallPermissionUpdated into RealtimeConversationScopedEventData, adds it to CONVERSATION_SCOPED_EVENT_TYPES, widens ChannelSendErrorContext's conversation pick to include assignedUserId/assignedInboxTeamId (both real callers already have the full ConversationModel), and routes the publish call via routeForConversation. * test(realtime): cover whatsappCallPermissionUpdated's route requirement Schema-level regression for the 6th routeless publish site (round-5 finding #1): confirms the newly added CONVERSATION_SCOPED_EVENT_TYPES membership actually rejects a routeless batch entry and accepts a routed one, not just the worker-level reconciler test. * fix(realtime): harden event delivery and member revocation * fix(realtime): harden stream delivery and assignment routing * fix(connections): update refresh platform stub * fix(realtime): resolve rebase integration conflicts * chore: fix test * feat(realtime): relay workspace events through Redis streams * fix(realtime): harden Redis stream relay cutover * fix(realtime): harden stream delivery and shutdown * refactor(worker): remove realtime drain re-export * fix(realtime): await event delivery before request completion
realcodesiman
added a commit
that referenced
this pull request
Oct 20, 2026
* feat(realtime): add the uWebSockets gateway (PR 2/3) Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): round-5 review fixes for the uWS gateway (PR 2/3) - Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review. * test(builder): add missing coverage for the guest/member connect token routes realtime-connect-token-api.test.ts and guest-realtime-token-route.test.ts test features/realtime/api/private.ts and app/api/guest/realtime-token/route.ts respectively, both already part of this PR, but were never brought over. * fix(realtime): preserve token issuance across rebase * fix(realtime): harden gateway replay and guest token issuance * fix(realtime): harden gateway socket lifecycle * fix(realtime): harden stream recovery and guest token handling * fix(realtime): harden gateway fault handling * docs(realtime): document gateway listener settings * revert(realtime): remove gateway listener documentation
realcodesiman
added a commit
that referenced
this pull request
Oct 20, 2026
* feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) (#1392) * feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) Checkout of apps/worker, integrations/chatbotx, integrations/webchat, packages/{realtime-protocol,business,database,redis,sdk}, and the builder server actions that publish realtime events, from the reconciled feat/realtime-protocol-v2-pr5 + origin/main merge. Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps packages/partysocket-config in place; packages/realtime-protocol is additive. integrations/webchat folded into this PR (not pr5c) because apps/worker depends on it directly and its typing-broadcast handlers already use the new publishGuestRealtimeEvent shape that packages/business introduces here. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): close PR #1349 round-5 findings for contracts + publish side - Make route required for conversation-scoped event types in RealtimeEventData via a discriminated union, enforced at both the TS type level and a zod superRefine on the workspace-broadcast envelope. Fixes the 6 routeless publish sites: delete-message, edit-message, call-summary, conversation/service.ts's updateReadStatus and markReadByOutbound, and the two messageCreated sites introduced by the main-merge reconciliation (record-delivered-private-reply, thread-control/service.ts). whatsapp-call-permission-grant.ts was already routeless-safe (not conversation-scoped). - Add a RealtimeTargetedEventData type (route always optional) for the single-recipient guest/member-send delivery paths, which are never route-filtered. - Add an iatMs claim (millisecond-precision mint time) to member-connect tokens, fixing the floored-iat false-401 on a same-second reconnect. - Make signRealtimeToken private; add signPresenceReportToken / verifyPresenceReportToken so every purpose mints through its own typed wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to use the new wrapper. - Export RealtimeCloseCode. - Store the raw append (not a .catch-wrapped copy) in inFlightByWorkspace so the shutdown drain's allSettled can observe and log a real failure. - Report a revoke failure to the caller: delete/update-workspace-member actions return { revokeWarning }, surfaced as a toast; inbox-team service's 5 call sites keep their existing logged-and-swallowed best-effort retry (unchanged scope per the fix's own "cheap" framing). - Tests: messageIdAssigned routing (new, was uncovered), iatMs round trip, route-required schema refine, presence-report token wrappers. * test(builder): fix tests left stale by the realtime-protocol migration These test files were never brought over when the realtime-protocol v2 contracts landed, so they still mocked the old broadcastToWorkspaceParty/partysocket-config/database-repository shapes, or the old IntegrationContext.platform shape (internalRealtimeUrl/getRealtimeBroadcastAuthHeaders instead of publishGuestRealtimeEvent), instead of what their sources now use (67 failing/type-erroring tests across 6 builder files). Also pulls in the matching platform-context mock fix for 7 marketing integrations whose tests shared the old IntegrationContext shape. delete-message.action.ts/edit-message.action.ts also needed routeForConversation added to their realtime-protocol mock now that route is required on conversation-scoped events (round-5 finding #1). * fix(realtime): add a route-less batch envelope schema for guest sockets realtimeBatchEnvelopeSchema's route-required refine is workspace- broadcast-only (round-5 finding #1), but the guest webchat client was reusing the same schema for its own wire frames — a guest socket's delivery is never route-filtered, so every conversation-scoped event it receives (e.g. messageCreated) correctly has no route, meaning the client would reject every real frame it gets. Adds realtimeGuestBatchEnvelopeSchema (bare envelope, no route requirement) for guest clients to use instead. * feat(realtime): add createRealtimeFrameReader shared client frame parser Both realtime clients (workspace provider, webchat guest client) duplicate the same JSON-parse/heartbeat-filter/batch-schema-validate/ seq-dedup logic, differing only in which batch envelope schema they validate against and how they dispatch each event afterward. createRealtimeFrameReader extracts the shared parsing/dedup mechanics, plus a throttled (2s default) onResyncNeeded so a burst of invalid batches — or per-event validation failures a caller reports via reportInvalidEvent, sharing the same throttle window — can't storm a resync. Used by both clients in PR 3/3. * fix(realtime): route the whatsappCallPermissionUpdated broadcast The 6th routeless publish site from the round-5 review: a permission- mode change (whether outbound calling is enabled for this contact) is most relevant to whoever is actually assigned to the conversation, unlike a ringing/active call's workspace-wide broadcast (the other whatsappCall* event types) — treat it as conversation-scoped like message events. Moves RealtimeEventWhatsappCallPermissionUpdated into RealtimeConversationScopedEventData, adds it to CONVERSATION_SCOPED_EVENT_TYPES, widens ChannelSendErrorContext's conversation pick to include assignedUserId/assignedInboxTeamId (both real callers already have the full ConversationModel), and routes the publish call via routeForConversation. * test(realtime): cover whatsappCallPermissionUpdated's route requirement Schema-level regression for the 6th routeless publish site (round-5 finding #1): confirms the newly added CONVERSATION_SCOPED_EVENT_TYPES membership actually rejects a routeless batch entry and accepts a routed one, not just the worker-level reconciler test. * fix(realtime): harden event delivery and member revocation * fix(realtime): harden stream delivery and assignment routing * fix(connections): update refresh platform stub * fix(realtime): resolve rebase integration conflicts * chore: fix test * feat(realtime): relay workspace events through Redis streams * fix(realtime): harden Redis stream relay cutover * fix(realtime): harden stream delivery and shutdown * refactor(worker): remove realtime drain re-export * fix(realtime): await event delivery before request completion * fix(realtime): harden gateway socket lifecycle (#1393) * feat(realtime): add the uWebSockets gateway (PR 2/3) Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts, parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts, lib/connection-tags.ts, partykit.json and their tests) with the new uWebSockets-based gateway, delivery, replay, and stream-reader modules from the reconciled feat/realtime-protocol-v2-pr5 branch. Also: - Builder token/auth routes: guest realtime-token mint, workspace-presence report route, features/realtime/api/private.ts, env.ts, and the api rate-limit config. Deletes the now-unused app/api/realtime/verify-origin/route.ts. - Migrates apps/realtime/src/lib/presence-report.ts and the builder's workspace-presence report route (+ its test) off the generic signRealtimeToken (made private in PR1) onto the new signPresenceReportToken / verifyPresenceReportToken wrappers. The route's test also switches its token-minting imports from the old @chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and fixes a dead cross-purpose-rejection test that referenced a REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a real member-connect token instead). - .env.example, docker-compose.dev.yml config for the new gateway. Part of the PR #1349 3-way split. Base: pr5a. Round-5 fixes land in follow-up commits on this branch. * fix(realtime): round-5 review fixes for the uWS gateway (PR 2/3) - Fail closed on the revoke-marker read: wrap it in try/catch (503 on a Redis error instead of hanging the upgrade), NaN-guard a corrupted marker value (treated as revoked), and compare the marker against the token's millisecond iatMs (added in PR 1) instead of the floored, whole-second JWT iat. Re-check the marker again right before the final res.upgrade(), closing the activation/replay race window. - Add 4 iatMs-boundary tests covering the strict-> comparison. - Mirror the guest upgrade catch's counter release in the member replay-failed catch: a second res.upgrade() failure now releases the pending-upgrade counters immediately instead of leaking them forever (open() never fires to release them otherwise). - Track a shard's "tainted up to" stream id in the stream reader and check it in both the workspace and guest open handlers after gap-fill replay: a pending upgrade whose activation+replay completed before an invalid record arrived, but whose open() runs after, now gets a forced resync close instead of opening with a silent, confirmed gap. - Fix the N+k parallel-upgrades test (was asserting on a close EVENT, unreliable for genuinely same-tick opens in this transport even though the server-sent close frame does land) and the multi-tab presence dedupe test (same close-event unreliability on 3-socket cleanup, unrelated to the behavior under test) to use readyState instead; add a presenceReportCoalesceMs test hook so the dedupe test no longer needs a flaky real 1100ms wait. Both are un-skipped. - Add resyncShard/resyncAllWorkspaces wiring tests exercising the real stream-reader poll loop end to end. - Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests. - Split gateway.ts into gateway-workspace-socket.ts and gateway-guest-socket.ts, extracting the shared armLifetimeTimer, readUpgradeRequest, and acquireSlot/releaseSlot helpers into gateway-shared.ts (all < 800 lines; gateway.ts was 1043). See PR #1349 round-5 review. * test(builder): add missing coverage for the guest/member connect token routes realtime-connect-token-api.test.ts and guest-realtime-token-route.test.ts test features/realtime/api/private.ts and app/api/guest/realtime-token/route.ts respectively, both already part of this PR, but were never brought over. * fix(realtime): preserve token issuance across rebase * fix(realtime): harden gateway replay and guest token issuance * fix(realtime): harden gateway socket lifecycle * fix(realtime): harden stream recovery and guest token handling * fix(realtime): harden gateway fault handling * docs(realtime): document gateway listener settings * revert(realtime): remove gateway listener documentation * feat(realtime): integrate realtime protocol v2 * fix(realtime): harden protocol v2 reconnect handling * fix(realtime): preserve assignment locks with response sla * test: fix auth test * fix(realtime): decode guest conversation ids once
hello-jackytruong
referenced
this pull request
in hello-jackytruong/ChatWorkAI
Nov 22, 2026
* feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) (#1392)
* feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3)
Checkout of apps/worker, integrations/chatbotx, integrations/webchat,
packages/{realtime-protocol,business,database,redis,sdk}, and the builder
server actions that publish realtime events, from the reconciled
feat/realtime-protocol-v2-pr5 + origin/main merge.
Part of the PR #1349 3-way split (pr5a/pr5b/pr5c). Keeps
packages/partysocket-config in place; packages/realtime-protocol is
additive. integrations/webchat folded into this PR (not pr5c) because
apps/worker depends on it directly and its typing-broadcast handlers
already use the new publishGuestRealtimeEvent shape that
packages/business introduces here.
Round-5 fixes land in follow-up commits on this branch.
* fix(realtime): close PR #1349 round-5 findings for contracts + publish side
- Make route required for conversation-scoped event types in
RealtimeEventData via a discriminated union, enforced at both the TS
type level and a zod superRefine on the workspace-broadcast envelope.
Fixes the 6 routeless publish sites: delete-message, edit-message,
call-summary, conversation/service.ts's updateReadStatus and
markReadByOutbound, and the two messageCreated sites introduced by
the main-merge reconciliation (record-delivered-private-reply,
thread-control/service.ts). whatsapp-call-permission-grant.ts was
already routeless-safe (not conversation-scoped).
- Add a RealtimeTargetedEventData type (route always optional) for the
single-recipient guest/member-send delivery paths, which are never
route-filtered.
- Add an iatMs claim (millisecond-precision mint time) to member-connect
tokens, fixing the floored-iat false-401 on a same-second reconnect.
- Make signRealtimeToken private; add signPresenceReportToken /
verifyPresenceReportToken so every purpose mints through its own typed
wrapper. PR2 must update apps/realtime/src/lib/presence-report.ts to
use the new wrapper.
- Export RealtimeCloseCode.
- Store the raw append (not a .catch-wrapped copy) in
inFlightByWorkspace so the shutdown drain's allSettled can observe and
log a real failure.
- Report a revoke failure to the caller: delete/update-workspace-member
actions return { revokeWarning }, surfaced as a toast; inbox-team
service's 5 call sites keep their existing logged-and-swallowed
best-effort retry (unchanged scope per the fix's own "cheap" framing).
- Tests: messageIdAssigned routing (new, was uncovered), iatMs round
trip, route-required schema refine, presence-report token wrappers.
* test(builder): fix tests left stale by the realtime-protocol migration
These test files were never brought over when the realtime-protocol v2
contracts landed, so they still mocked the old
broadcastToWorkspaceParty/partysocket-config/database-repository shapes,
or the old IntegrationContext.platform shape
(internalRealtimeUrl/getRealtimeBroadcastAuthHeaders instead of
publishGuestRealtimeEvent), instead of what their sources now use (67
failing/type-erroring tests across 6 builder files). Also pulls in the
matching platform-context mock fix for 7 marketing integrations whose
tests shared the old IntegrationContext shape.
delete-message.action.ts/edit-message.action.ts also needed
routeForConversation added to their realtime-protocol mock now that
route is required on conversation-scoped events (round-5 finding #1).
* fix(realtime): add a route-less batch envelope schema for guest sockets
realtimeBatchEnvelopeSchema's route-required refine is workspace-
broadcast-only (round-5 finding #1), but the guest webchat client was
reusing the same schema for its own wire frames — a guest socket's
delivery is never route-filtered, so every conversation-scoped event
it receives (e.g. messageCreated) correctly has no route, meaning the
client would reject every real frame it gets. Adds
realtimeGuestBatchEnvelopeSchema (bare envelope, no route requirement)
for guest clients to use instead.
* feat(realtime): add createRealtimeFrameReader shared client frame parser
Both realtime clients (workspace provider, webchat guest client)
duplicate the same JSON-parse/heartbeat-filter/batch-schema-validate/
seq-dedup logic, differing only in which batch envelope schema they
validate against and how they dispatch each event afterward.
createRealtimeFrameReader extracts the shared parsing/dedup mechanics,
plus a throttled (2s default) onResyncNeeded so a burst of invalid
batches — or per-event validation failures a caller reports via
reportInvalidEvent, sharing the same throttle window — can't storm a
resync. Used by both clients in PR 3/3.
* fix(realtime): route the whatsappCallPermissionUpdated broadcast
The 6th routeless publish site from the round-5 review: a permission-
mode change (whether outbound calling is enabled for this contact) is
most relevant to whoever is actually assigned to the conversation,
unlike a ringing/active call's workspace-wide broadcast (the other
whatsappCall* event types) — treat it as conversation-scoped like
message events.
Moves RealtimeEventWhatsappCallPermissionUpdated into
RealtimeConversationScopedEventData, adds it to
CONVERSATION_SCOPED_EVENT_TYPES, widens ChannelSendErrorContext's
conversation pick to include assignedUserId/assignedInboxTeamId (both
real callers already have the full ConversationModel), and routes the
publish call via routeForConversation.
* test(realtime): cover whatsappCallPermissionUpdated's route requirement
Schema-level regression for the 6th routeless publish site (round-5
finding #1): confirms the newly added CONVERSATION_SCOPED_EVENT_TYPES
membership actually rejects a routeless batch entry and accepts a
routed one, not just the worker-level reconciler test.
* fix(realtime): harden event delivery and member revocation
* fix(realtime): harden stream delivery and assignment routing
* fix(connections): update refresh platform stub
* fix(realtime): resolve rebase integration conflicts
* chore: fix test
* feat(realtime): relay workspace events through Redis streams
* fix(realtime): harden Redis stream relay cutover
* fix(realtime): harden stream delivery and shutdown
* refactor(worker): remove realtime drain re-export
* fix(realtime): await event delivery before request completion
* fix(realtime): harden gateway socket lifecycle (#1393)
* feat(realtime): add the uWebSockets gateway (PR 2/3)
Replaces apps/realtime's old PartyKit-based gateway (parties/workspaces.ts,
parties/guests.ts, server.ts, lib/auth.ts, lib/realtime-auth.ts,
lib/connection-tags.ts, partykit.json and their tests) with the new
uWebSockets-based gateway, delivery, replay, and stream-reader modules
from the reconciled feat/realtime-protocol-v2-pr5 branch.
Also:
- Builder token/auth routes: guest realtime-token mint, workspace-presence
report route, features/realtime/api/private.ts, env.ts, and the api
rate-limit config. Deletes the now-unused
app/api/realtime/verify-origin/route.ts.
- Migrates apps/realtime/src/lib/presence-report.ts and the builder's
workspace-presence report route (+ its test) off the generic
signRealtimeToken (made private in PR1) onto the new
signPresenceReportToken / verifyPresenceReportToken wrappers. The
route's test also switches its token-minting imports from the old
@chatbotx.io/partysocket-config to @chatbotx.io/realtime-protocol, and
fixes a dead cross-purpose-rejection test that referenced a
REALTIME_TOKEN_PURPOSE.broadcast key that doesn't exist (now mints a
real member-connect token instead).
- .env.example, docker-compose.dev.yml config for the new gateway.
Part of the PR #1349 3-way split. Base: pr5a.
Round-5 fixes land in follow-up commits on this branch.
* fix(realtime): round-5 review fixes for the uWS gateway (PR 2/3)
- Fail closed on the revoke-marker read: wrap it in try/catch (503 on a
Redis error instead of hanging the upgrade), NaN-guard a corrupted
marker value (treated as revoked), and compare the marker against the
token's millisecond iatMs (added in PR 1) instead of the floored,
whole-second JWT iat. Re-check the marker again right before the final
res.upgrade(), closing the activation/replay race window.
- Add 4 iatMs-boundary tests covering the strict-> comparison.
- Mirror the guest upgrade catch's counter release in the member
replay-failed catch: a second res.upgrade() failure now releases the
pending-upgrade counters immediately instead of leaking them forever
(open() never fires to release them otherwise).
- Track a shard's "tainted up to" stream id in the stream reader and
check it in both the workspace and guest open handlers after gap-fill
replay: a pending upgrade whose activation+replay completed before an
invalid record arrived, but whose open() runs after, now gets a forced
resync close instead of opening with a silent, confirmed gap.
- Fix the N+k parallel-upgrades test (was asserting on a close EVENT,
unreliable for genuinely same-tick opens in this transport even though
the server-sent close frame does land) and the multi-tab presence
dedupe test (same close-event unreliability on 3-socket cleanup,
unrelated to the behavior under test) to use readyState instead; add a
presenceReportCoalesceMs test hook so the dedupe test no longer needs a
flaky real 1100ms wait. Both are un-skipped.
- Add resyncShard/resyncAllWorkspaces wiring tests exercising the real
stream-reader poll loop end to end.
- Add MAX_REPLAY_ENTRIES / MAX_REPLAY_SCAN_ENTRIES replay-bounds tests.
- Split gateway.ts into gateway-workspace-socket.ts and
gateway-guest-socket.ts, extracting the shared armLifetimeTimer,
readUpgradeRequest, and acquireSlot/releaseSlot helpers into
gateway-shared.ts (all < 800 lines; gateway.ts was 1043).
See PR #1349 round-5 review.
* test(builder): add missing coverage for the guest/member connect token routes
realtime-connect-token-api.test.ts and guest-realtime-token-route.test.ts
test features/realtime/api/private.ts and app/api/guest/realtime-token/route.ts
respectively, both already part of this PR, but were never brought over.
* fix(realtime): preserve token issuance across rebase
* fix(realtime): harden gateway replay and guest token issuance
* fix(realtime): harden gateway socket lifecycle
* fix(realtime): harden stream recovery and guest token handling
* fix(realtime): harden gateway fault handling
* docs(realtime): document gateway listener settings
* revert(realtime): remove gateway listener documentation
* feat(realtime): integrate realtime protocol v2
* fix(realtime): harden protocol v2 reconnect handling
* fix(realtime): preserve assignment locks with response sla
* test: fix auth test
* fix(realtime): decode guest conversation ids once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Changes
apps/realtime: add gateway configuration, protocol framing, authentication, metrics, and workspace/guest party routing.apps/builder: mint scoped realtime tokens, connect through the gateway, and resync chat and webchat clients.packages/business,packages/partysocket-config,packages/database,packages/redis,apps/worker, andintegrations/chatbotx: route and publish scoped realtime events.docs/realtime.mdand realtime, builder, business, worker, integration, and package tests: document and cover the protocol cutover.Test plan