Repository navigation
Feat/realtime protocol v2 integration - #1517
Merged
Merged
Conversation
realcodesiman
force-pushed
the
feat/realtime-protocol-v2-integration
branch
2 times, most recently
from
October 20, 2026 02:40
af90855 to
dfdef20
Compare
…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
* 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
force-pushed
the
feat/realtime-protocol-v2-integration
branch
from
October 20, 2026 07:29
dfdef20 to
7a6ddaa
Compare
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.
No description provided.