Skip to content

fix(realtime): bind the socket to the organization the client is viewing - #17

Merged
pulkitxm merged 5 commits into
mainfrom
fix/active-organization
Jul 23, 2026
Merged

pulkitxm merged 5 commits into
mainfrom
fix/active-organization

Conversation

@pulkitxm

Copy link
Copy Markdown
Member

Resolve the active organization through one shared helper and let the client state which workspace its socket is for, so the page and the realtime stream can never disagree.

@pulkitxm

Copy link
Copy Markdown
Member Author

Playwright pass rate over five consecutive full-suite runs (pnpm --filter @orbit/web exec playwright test, reseeded before every run):

  • before: 0/5. issues.spec.ts and same-user-tabs.spec.ts failed on their realtime assertions in 4 of the 5 runs, and second-workspace-realtime.spec.ts failed in all 5. The realtime log confirmed the cause: the page rendered org_noveum_demo while the same user's sockets reported organizationId: cc6d740e-..., the second workspace.
  • after: 5/5, 7 tests each run.

pnpm verify is green: lint, comment policy, typecheck and unit tests, 8/8 tasks.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The change centralizes active-membership selection, adds organization-aware realtime authentication and close codes, propagates organization IDs through realtime clients and web providers, and adds unit, integration, reconnect, and end-to-end coverage.

Changes

Active organization and realtime scoping

Layer / File(s) Summary
Centralized membership selection
packages/core/src/org/active-organization.ts, packages/core/src/org/active-organization.test.ts, packages/core/src/index.ts, apps/web/src/lib/auth/principal.ts, apps/mcp/src/create-key.ts
Memberships are selected by stated organization or deterministic oldest-membership fallback, with consumers updated to use the shared selector.
Organization-aware realtime authentication
packages/shared/src/events/index.ts, apps/realtime/src/auth.ts, apps/realtime/src/server.ts, apps/realtime/src/test-helpers.ts, apps/realtime/src/active-organization.test.ts
WebSocket credentials accept an organization ID, authentication returns typed rejection reasons, and the server maps unauthorized and forbidden cases to close codes covered by integration tests.
Client and web organization propagation
packages/realtime-client/src/*, apps/realtime/src/client-reconnect.test.ts, apps/web/src/lib/realtime/provider.tsx, apps/web/src/features/inbox/inbox-realtime.tsx, apps/web/src/app/(app)/inbox/page.tsx
Organization IDs are required by realtime client and provider contracts, included in WebSocket URLs, passed from web principals, and used to prevent reconnects after forbidden closures.
Workspace switching validation
apps/web/e2e/second-workspace-realtime.spec.ts
A Playwright scenario verifies realtime content propagation after creating a second workspace and returning to the initial workspace.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant WebApp
  participant RealtimeClient
  participant RealtimeServer
  participant MembershipAuth
  WebApp->>RealtimeClient: Create client with organizationId
  RealtimeClient->>RealtimeServer: Connect with token and organizationId
  RealtimeServer->>MembershipAuth: Authenticate connection and resolve membership
  MembershipAuth-->>RealtimeServer: Principal or rejection reason
  RealtimeServer-->>RealtimeClient: Ready response or close code
  RealtimeClient-->>WebApp: Scoped realtime state or disposed connection
Loading

Possibly related PRs

  • Noveum/orbit#3: Introduced related principal membership resolution logic used by the active-organization selection update.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: binding the realtime socket to the client’s active organization.
Description check ✅ Passed The description is directly related to the PR and accurately summarizes the shared organization helper and socket scoping change.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/active-organization

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Checkov (3.3.8)
apps/realtime/package.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'


Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/web/e2e/second-workspace-realtime.spec.ts (1)

4-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Validate E2E environment configuration with Zod.

ORBIT_E2E_BASE_URL and ORBIT_E2E_SHOTS are external inputs and are used without validation. Parse them once with an e2eConfigSchema before deriving these constants.

Proposed change
+import { z } from 'zod';
+
+const e2eConfigSchema = z.object({
+  ORBIT_E2E_BASE_URL: z.url().optional(),
+  ORBIT_E2E_SHOTS: z.string().min(1).optional(),
+});
+
+const e2eConfig = e2eConfigSchema.parse(process.env);
-const BASE = process.env['ORBIT_E2E_BASE_URL'] ?? 'http://localhost:3011';
-const SHOTS = process.env['ORBIT_E2E_SHOTS'] ?? 'test-results';
+const BASE = e2eConfig.ORBIT_E2E_BASE_URL ?? 'http://localhost:3011';
+const SHOTS = e2eConfig.ORBIT_E2E_SHOTS ?? 'test-results';

As per coding guidelines, “Validate every external input with Zod.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/e2e/second-workspace-realtime.spec.ts` around lines 4 - 5, Define an
e2eConfigSchema with Zod for ORBIT_E2E_BASE_URL and ORBIT_E2E_SHOTS, parse the
relevant process.env values once, and derive BASE and SHOTS from the validated
result. Preserve the existing defaults while ensuring both external inputs are
validated before use.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/realtime/src/server.ts`:
- Around line 75-79: Update the request parsing flow around
connectionOrganizationIdSchema.safeParse to distinguish an absent organizationId
from a present invalid value: preserve null only when the parameter is absent,
and reject or close the request when parsing fails. Ensure malformed empty and
overlong organizationId values cannot fall back to the active organization, and
add coverage for both cases.

In `@apps/web/e2e/second-workspace-realtime.spec.ts`:
- Around line 29-32: Update the membership timestamp mutation in the realtime
workspace test so the first membership’s createdAt is changed to a distinct
value rather than set to membership.createdAt unchanged. Preserve the existing
update targeting schema.member.id and ensure the resulting timestamps produce
the intended active-membership precedence after the second workspace is created.

---

Nitpick comments:
In `@apps/web/e2e/second-workspace-realtime.spec.ts`:
- Around line 4-5: Define an e2eConfigSchema with Zod for ORBIT_E2E_BASE_URL and
ORBIT_E2E_SHOTS, parse the relevant process.env values once, and derive BASE and
SHOTS from the validated result. Preserve the existing defaults while ensuring
both external inputs are validated before use.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 61523d23-94f6-40bb-b798-0c8087f789d8

📥 Commits

Reviewing files that changed from the base of the PR and between c099693 and 4280a09.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (19)
  • apps/mcp/src/create-key.ts
  • apps/realtime/package.json
  • apps/realtime/src/active-organization.test.ts
  • apps/realtime/src/auth.ts
  • apps/realtime/src/client-reconnect.test.ts
  • apps/realtime/src/server.ts
  • apps/realtime/src/test-helpers.ts
  • apps/web/e2e/second-workspace-realtime.spec.ts
  • apps/web/src/app/(app)/inbox/page.tsx
  • apps/web/src/features/inbox/inbox-realtime.tsx
  • apps/web/src/lib/auth/principal.ts
  • apps/web/src/lib/realtime/provider.tsx
  • packages/core/src/index.ts
  • packages/core/src/org/active-organization.test.ts
  • packages/core/src/org/active-organization.ts
  • packages/realtime-client/src/index.ts
  • packages/realtime-client/src/react.test.tsx
  • packages/realtime-client/src/react.tsx
  • packages/shared/src/events/index.ts

Comment on lines +75 to +79
const stated = connectionOrganizationIdSchema.safeParse(url.searchParams.get('organizationId'));
return {
token: url.searchParams.get('token') ?? '',
organizationId: stated.success ? stated.data : null,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject malformed stated organization IDs instead of falling back.

At Line 75, a present-but-invalid organizationId becomes null, so authentication selects the active organization. Distinguish an absent parameter from a parse failure and close malformed requests; add coverage for organizationId= and overlong values.

As per coding guidelines, “Validate every external input with Zod.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/realtime/src/server.ts` around lines 75 - 79, Update the request parsing
flow around connectionOrganizationIdSchema.safeParse to distinguish an absent
organizationId from a present invalid value: preserve null only when the
parameter is absent, and reject or close the request when parsing fails. Ensure
malformed empty and overlong organizationId values cannot fall back to the
active organization, and add coverage for both cases.

Source: Coding guidelines

Comment on lines +29 to +32
await db
.update(schema.member)
.set({ createdAt: membership.createdAt })
.where(eq(schema.member.id, membership.id));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Actually update the first membership timestamp.

This writes createdAt back unchanged, so it cannot alter active-membership precedence after creating the second workspace. The test can therefore pass without exercising the intended differing active-organization state.

Proposed change
   await db
     .update(schema.member)
-    .set({ createdAt: membership.createdAt })
+    .set({ createdAt: new Date() })
     .where(eq(schema.member.id, membership.id));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await db
.update(schema.member)
.set({ createdAt: membership.createdAt })
.where(eq(schema.member.id, membership.id));
await db
.update(schema.member)
.set({ createdAt: new Date() })
.where(eq(schema.member.id, membership.id));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/e2e/second-workspace-realtime.spec.ts` around lines 29 - 32, Update
the membership timestamp mutation in the realtime workspace test so the first
membership’s createdAt is changed to a distinct value rather than set to
membership.createdAt unchanged. Preserve the existing update targeting
schema.member.id and ensure the resulting timestamps produce the intended
active-membership precedence after the second workspace is created.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant