Skip to content

feat(realtime): client cutover to realtime-protocol v2 (PR 3/3) - #1394

Closed
realcodesiman wants to merge 13 commits into
feat/realtime-protocol-v2-integrationfrom
feat/realtime-protocol-v2-pr5c
Closed

realcodesiman wants to merge 13 commits into
feat/realtime-protocol-v2-integrationfrom
feat/realtime-protocol-v2-pr5c

Conversation

@realcodesiman

Copy link
Copy Markdown
Contributor

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

  1. feat(realtime): add realtime-protocol v2 contracts and publish side (PR 1/3) #1392 (PR 1/3) — realtime-protocol contracts + publish side.
  2. fix(realtime): harden gateway socket lifecycle #1393 (PR 2/3) — the uWebSockets gateway.
  3. This PR — builder client cutover + cleanup.

Base is PR 2/3; diff shown here is only this PR's own changes. Intended to merge together with no release in between — this PR deletes packages/partysocket-config, which PRs 1 and 2 no longer depend on but haven't themselves removed.

This PR

  • WorkspaceRealtimeProvider/useWorkspaceRealtimeEvents, the workspace realtime shell + connection-status banner, chat-realtime.tsx.
  • The webchat guest client (webchat-realtime.tsx, webchat-realtime-frames.ts, guest-sesssion-store.ts).
  • Deletes packages/partysocket-config (fully superseded).
  • Updates docs/realtime.md, docs/websocket.md, docs/whatsapp-calling-voip.md, README.md, AGENTS.md, .agents/skills.

Round-5 review fixes included

  • Added createRealtimeFrameReader (realtime-protocol, landed in PR 1/3) and switched both clients to it, removing their duplicated parse/heartbeat/dedup logic.
  • The workspace client now resyncs on an invalid batch envelope too (previously only logged); both clients' invalid-batch and schema-invalid-event resync triggers share one 2s throttle, so a burst of either can't storm invalidateQueries().
  • Fixed two docs/realtime.md errors: added the missing backpressure-drop 4002 reason, and corrected a 4002 reconnect to describe jittered backoff instead of "immediately".
  • Found and fixed a genuine bug the client cutover surfaced: the webchat guest client was validating its wire frames with the workspace-only, route-required batch schema — every real messageCreated frame a guest socket ever receives would have failed validation, since guest delivery is never route-filtered. Fixed by switching it to the new realtimeGuestBatchEnvelopeSchema (added to PR 1/3).

Tests added

  • RealtimeSocket fires onClose at most once even if the underlying close handler is invoked twice.
  • createRealtimeFrameReader unit tests (heartbeat filtering, seq dedup/reset, throttled resync).
  • Coverage for the new guest-batch route-less schema and the workspace client's new invalid-batch resync + throttle.

Verification

  • pnpm --filter @chatbotx.io/realtime-protocol test — 61/61
  • pnpm --filter builder check-types — clean
  • pnpm --filter builder test — 749/749 files, 5879/5881 tests (2 pre-existing skips)
  • pnpm lint — clean
  • Full-stack file-coverage audit: every file the original feat(realtime): implement protocol v2 #1349 diff touches is accounted for across this 3-PR stack (plus the round-5-only additions noted above), confirmed via a 3-way diff reconciliation against the original combined branch.

…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.
@github-actions github-actions Bot added the feature New feature or request label Oct 2, 2026
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.
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5b branch from 18719e3 to 1fdd419 Compare October 2, 2026 23:01
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5c branch from b547d9d to dfc0550 Compare October 2, 2026 23:01
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
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5b branch from 1fdd419 to 3de17a7 Compare October 2, 2026 23:21
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5c branch from dfc0550 to 528b541 Compare October 2, 2026 23:21
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.
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.
- 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.
…n 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.
Migrates the builder client off the old PartyKit-based
@chatbotx.io/partysocket-config package onto the new uWS gateway from
PR 2/3: WorkspaceRealtimeProvider/useWorkspaceRealtimeEvents, the
workspace realtime shell + connection-status banner, chat-realtime.tsx,
and the webchat guest client (webchat-realtime.tsx,
webchat-realtime-frames.ts, guest-sesssion-store.ts). Deletes
packages/partysocket-config (fully superseded) and updates
docs/realtime.md, docs/websocket.md, docs/whatsapp-calling-voip.md,
README.md, AGENTS.md, and .agents/skills to describe the new gateway.

Carries forward PR 1/3's round-5 realtimeRevokeWarning i18n key (lost
by checking out messages/*.json wholesale from the pre-round-5
baseline) and fixes the one genuine production bug the client cutover
surfaced: the guest webchat client was parsing its wire frames with
realtimeBatchEnvelopeSchema, whose route-required refine (round-5
finding #1) is workspace-broadcast-only — guest delivery is never
route-filtered, so every real messageCreated frame the webchat client
received would have failed validation. Switched it to the new
realtimeGuestBatchEnvelopeSchema (added to PR 1/3).
- Use the new createRealtimeFrameReader (PR 1/3) from both realtime
  clients (workspace provider, webchat guest client), replacing their
  duplicated JSON-parse/heartbeat-filter/batch-schema-validate/seq-dedup
  logic.
- The workspace provider now resyncs on an invalid batch envelope too
  (previously only logged), and both clients' resync triggers — invalid
  batch and per-event schema-invalid — share the frame reader's 2s
  throttle, so a burst of either can't storm invalidateQueries().
- Fix two docs/realtime.md errors: add the missing backpressure-drop
  4002 reason, and describe a 4002 reconnect as jittered backoff
  (same exponential schedule as 4000), not "immediately".
- Add a regression test confirming RealtimeSocket's onClose guard
  fires at most once per socket even if the underlying close handler
  is invoked twice.
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5b branch from 3de17a7 to 4f48144 Compare October 2, 2026 23:30
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5c branch from 528b541 to 0419909 Compare October 2, 2026 23:30
@realcodesiman
realcodesiman force-pushed the feat/realtime-protocol-v2-pr5b branch from 4f48144 to 70b4cb5 Compare October 18, 2026 13:09
Base automatically changed from feat/realtime-protocol-v2-pr5b to feat/realtime-protocol-v2-integration October 19, 2026 02:17
@realcodesiman
realcodesiman deleted the feat/realtime-protocol-v2-pr5c branch October 19, 2026 08:42
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