Skip to content

feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) - #1392

Merged
realcodesiman merged 17 commits into
feat/realtime-protocol-v2-integrationfrom
feat/realtime-protocol-v2-pr5a
Oct 18, 2026
Merged

realcodesiman merged 17 commits into
feat/realtime-protocol-v2-integrationfrom
feat/realtime-protocol-v2-pr5a

Conversation

@realcodesiman

@realcodesiman realcodesiman commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Part of a 3-PR stack splitting #1349 into reviewable pieces, in merge order:

  1. This PR — @chatbotx.io/realtime-protocol contracts (schemas, auth, event envelopes), the publish side (queueWorkspaceRealtimeEvent, publishGuestRealtimeEvent, publishWorkspaceMemberRealtimeEvent), apps/worker consumers, and integrations/chatbotx + integrations/webchat (both depend on the new shapes).
  2. feat(realtime): implement protocol v2 #1349 PR 2/3 — the uWebSockets realtime gateway (apps/realtime).
  3. feat(realtime): implement protocol v2 #1349 PR 3/3 — builder client cutover + packages/partysocket-config cleanup.

Each PR is reviewable and buildable/testable on its own; the stack is intended to merge together with no release in between. See #1349 for the original combined diff and discussion.

This PR

  • packages/realtime-protocol, packages/business, packages/database, packages/redis, packages/sdk
  • apps/worker
  • integrations/chatbotx, integrations/webchat
  • A handful of builder server actions that publish realtime events (messages/actions/*, workspace-members/actions/*, integration-whatsapp/calling/actions/answer-voip-call.action.ts, integration-messenger/actions/reconnect-callback.ts)

Round-5 review fixes included

  • route is now required (enforced by both the TS discriminated union and a Zod refine) for conversation-scoped event types, closing a gap where assigned-scope members silently never got an event. Fixes all 6 routeless publish sites: delete/edit message, call-summary, conversation service (updateReadStatus/markReadByOutbound), and whatsappCallPermissionUpdated (a permission-mode change is most relevant to whoever is assigned to the conversation, unlike a ringing/active call's workspace-wide broadcast).
  • iatMs (millisecond mint time) added to member tokens; revoke-marker checks compare against it instead of the floored, whole-second JWT iat.
  • signRealtimeToken is now module-private; signPresenceReportToken/verifyPresenceReportToken wrappers added for the one external caller that needs it.
  • inFlightByWorkspace now stores the raw append promise so the shutdown drain can observe real failures.
  • A revoke-failure warning now surfaces to the two single-call-site workspace-member actions instead of failing silently.

Verification

  • pnpm --filter @chatbotx.io/realtime-protocol test — 60/60
  • pnpm --filter @chatbotx.io/business test — 5250/5250 (7 pre-existing skips)
  • pnpm --filter worker test — 3202/3202
  • pnpm --filter builder check-types — clean
  • pnpm lint — clean

Verification after a3f705f

  • pnpm lint — passed
  • pnpm --filter builder check-types — passed
  • pnpm --filter worker check-types — passed
  • pnpm --filter @chatbotx.io/business check-types — passed
  • pnpm --filter @chatbotx.io/database check-types — passed
  • pnpm --filter builder test — 917 files passed; 8,134 tests passed, 2 skipped
  • pnpm --filter worker test — 301 files and 3,811 tests passed
  • pnpm --filter @chatbotx.io/business test — 407 files passed, 7 skipped; 6,978 tests passed, 23 skipped
  • pnpm --filter @chatbotx.io/database test — 101 files passed, 20 skipped; 1,377 tests passed, 187 skipped

…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.
…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.
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).
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.
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.
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.
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.
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5a branch from c3b2f26 to 5b7757e Compare October 18, 2026 01:47
@realcodesiman
realcodesiman changed the base branch from main to feat/realtime-protocol-v2-integration October 18, 2026 06:11
@realcodesiman
realcodesiman merged commit ac0e12f into feat/realtime-protocol-v2-integration Oct 18, 2026
4 checks passed
@realcodesiman
realcodesiman deleted the feat/realtime-protocol-v2-pr5a branch October 18, 2026 12:49
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 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
…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 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant