Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: WIP Multiplayer (#5733)

Oleg Isonena2cfcbb7be38
diff --git a/apps/builder/.env b/apps/builder/.env
index 1f68cabc83..1a9cafa86d 100644
--- a/apps/builder/.env
+++ b/apps/builder/.env
@@ -85,8 +85,4 @@ PLANS='[
# TRPC_SERVER_URL=
# TRPC_SERVER_API_TOKEN=
-# AI Features
-# OPENAI_KEY=
-# OPENAI_ORG=
-
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index e58525484a..4466ae7e36 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -35,6 +35,7 @@ import {
subscribeModifierKeys,
$stagingUsername,
$stagingPassword,
+ $user,
} from "~/shared/nano-states";
import { $project } from "~/shared/sync/data-stores";
import { $settings, type Settings } from "./shared/client-settings";
@@ -67,6 +68,7 @@ import { DeleteUnusedCssVariablesDialog } from "~/builder/shared/css-variable-ut
import { DeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";
import { KeyboardShortcutsDialog } from "./features/keyboard-shortcuts-dialog";
import { TokenConflictDialog } from "~/shared/token-conflict-dialog";
+import type { User } from "~/shared/db/user.server";
import {
initCopyPaste,
@@ -231,6 +233,7 @@ export type BuilderProps = {
projectId: string;
authToken?: string;
authPermit: AuthPermit;
+ user?: User;
role: Role | "own";
authTokenPermissions: TokenPermissions;
planFeatures: PlanFeatures;
@@ -255,6 +258,7 @@ export const Builder = (props: BuilderProps) => {
// additional data stores
$authPermit.set(authPermit);
$authToken.set(authToken);
+ $user.set(props.user);
setSharedStores(props);
$authTokenPermissions.set(authTokenPermissions);
$stagingUsername.set(stagingUsername);
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
index da8fc8f5aa..553f57df39 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
@@ -87,12 +87,12 @@ export const CanvasTools = () => {
<>
{isPreviewMode === false && (
<>
- <CollaborativeCursors />
{isStylePanelGridVisible && <GridGuides />}
<SelectedInstanceOutline />
<HoveredInstanceOutline />
<CollaborativeInstanceOutline />
<BlockChildHoveredInstanceOutline />
+ <CollaborativeCursors />
<TextEditorContextMenu />
<CanvasInstanceContextMenu />
</>
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.test.ts b/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.test.ts
index 46779bde68..d817aec664 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.test.ts
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, test } from "vitest";
import { __testing__ } from "./collaborative-cursors";
const {
+ getCollaboratorLabel,
+ computePredictedCursor,
shouldSkipCollaborator,
hasCursorPosition,
computeCursorCoordinates,
@@ -10,6 +12,12 @@ const {
} = __testing__;
describe("collaborative-cursors helpers", () => {
+ test("getCollaboratorLabel trims names and skips empty labels", () => {
+ expect(getCollaboratorLabel({ name: " Ada " })).toBe("Ada");
+ expect(getCollaboratorLabel({ name: " " })).toBeUndefined();
+ expect(getCollaboratorLabel({})).toBeUndefined();
+ });
+
test("shouldSkipCollaborator returns true only for different known pages", () => {
expect(
shouldSkipCollaborator({
@@ -86,6 +94,80 @@ describe("collaborative-cursors helpers", () => {
expect(isWithinLayer({ x: 999, y: 999, layerRect: undefined })).toBe(true);
});
+ test("computePredictedCursor extrapolates from cursor velocity", () => {
+ expect(
+ computePredictedCursor({
+ current: { x: 20, y: 30, time: 100 },
+ previous: { x: 10, y: 10, time: 0 },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ }).coordinates
+ ).toEqual({ x: 28, y: 46 });
+ });
+
+ test("computePredictedCursor smooths velocity across updates", () => {
+ const prediction = computePredictedCursor({
+ current: { x: 20, y: 0, time: 100 },
+ previous: { x: 10, y: 0, time: 0, velocity: { x: 0.3, y: 0 } },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ });
+
+ expect(prediction.coordinates.x).toBe(36);
+ expect(prediction.velocity.x).toBe(0.2);
+ });
+
+ test("computePredictedCursor resets velocity when direction reverses", () => {
+ const prediction = computePredictedCursor({
+ current: { x: 90, y: 0, time: 100 },
+ previous: { x: 100, y: 0, time: 0, velocity: { x: 0.5, y: 0 } },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ });
+
+ expect(prediction.coordinates.x).toBe(82);
+ expect(prediction.velocity.x).toBe(-0.1);
+ });
+
+ test("computePredictedCursor skips stale samples", () => {
+ expect(
+ computePredictedCursor({
+ current: { x: 20, y: 30, time: 500 },
+ previous: { x: 10, y: 10, time: 0 },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ }).coordinates
+ ).toEqual({ x: 20, y: 30 });
+ });
+
+ test("computePredictedCursor stops predicting when the cursor stops", () => {
+ const prediction = computePredictedCursor({
+ current: { x: 20, y: 30, time: 100 },
+ previous: { x: 20, y: 30, time: 0, velocity: { x: 0.5, y: 0 } },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ });
+
+ expect(prediction.coordinates).toEqual({ x: 20, y: 30 });
+ expect(prediction.velocity).toEqual({ x: 0, y: 0 });
+ });
+
+ test("computePredictedCursor caps prediction distance", () => {
+ const result = computePredictedCursor({
+ current: { x: 200, y: 0, time: 10 },
+ previous: { x: 0, y: 0, time: 0 },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ }).coordinates;
+
+ expect(result.x).toBe(280);
+ expect(result.y).toBe(0);
+ });
+
+ test("computePredictedCursor clamps prediction to layer", () => {
+ expect(
+ computePredictedCursor({
+ current: { x: 490, y: 390, time: 100 },
+ previous: { x: 450, y: 350, time: 0 },
+ layerRect: { left: 0, top: 0, width: 500, height: 400 },
+ }).coordinates
+ ).toEqual({ x: 500, y: 400 });
+ });
+
test("toRenderableCollaboratorCursor returns coordinates only for visible collaborator cursor", () => {
const layerRect = { left: 0, top: 0, width: 1200, height: 800 };
const canvasRect = { left: 100, top: 200, width: 800, height: 600 };
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.tsx
index eeccd0118e..c3b3e13452 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.tsx
@@ -1,5 +1,5 @@
import { useStore } from "@nanostores/react";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { css, type Rect } from "@webstudio-is/design-system";
import {
$collaborators,
@@ -27,6 +27,160 @@ const cursorStyle = css({
willChange: "transform",
});
+const cursorLabelStyle = css({
+ position: "absolute",
+ top: 14,
+ left: 12,
+ padding: "2px 6px",
+ borderRadius: 3,
+ color: "white",
+ fontSize: 11,
+ fontWeight: 500,
+ lineHeight: "16px",
+ whiteSpace: "nowrap",
+ boxShadow: "0 1px 2px rgb(0 0 0 / 20%)",
+});
+
+const getCollaboratorLabel = (collaborator: CollaboratorInfo) => {
+ const name = collaborator.name?.trim();
+ if (name === undefined || name.length === 0) {
+ return;
+ }
+ return name;
+};
+
+type CursorCoordinates = {
+ x: number;
+ y: number;
+};
+
+type CursorVelocity = {
+ x: number;
+ y: number;
+};
+
+type CursorSample = CursorCoordinates & {
+ time: number;
+ velocity?: CursorVelocity;
+};
+
+const CURSOR_PREDICTION_MS = 80;
+const CURSOR_VELOCITY_SMOOTHING = 0.5;
+const MAX_PREDICTION_SAMPLE_MS = 250;
+const MAX_PREDICTION_DISTANCE = 80;
+const ZERO_CURSOR_VELOCITY = { x: 0, y: 0 };
+
+const clampCoordinate = ({
+ value,
+ max,
+}: {
+ value: number;
+ max: number | undefined;
+}) => {
+ if (max === undefined) {
+ return value;
+ }
+ return Math.min(Math.max(value, 0), max);
+};
+
+const capPredictionDistance = ({
+ x,
+ y,
+}: CursorCoordinates): CursorCoordinates => {
+ const distance = Math.hypot(x, y);
+ if (distance <= MAX_PREDICTION_DISTANCE) {
+ return { x, y };
+ }
+ const scale = MAX_PREDICTION_DISTANCE / distance;
+ return {
+ x: x * scale,
+ y: y * scale,
+ };
+};
+
+const toCursorCoordinates = (sample: CursorSample): CursorCoordinates => ({
+ x: sample.x,
+ y: sample.y,
+});
+
+const computeSmoothedVelocity = ({
+ measuredVelocity,
+ previousVelocity,
+}: {
+ measuredVelocity: CursorVelocity;
+ previousVelocity: CursorVelocity | undefined;
+}) => {
+ if (previousVelocity === undefined) {
+ return measuredVelocity;
+ }
+ const dot =
+ measuredVelocity.x * previousVelocity.x +
+ measuredVelocity.y * previousVelocity.y;
+ if (dot < 0) {
+ return measuredVelocity;
+ }
+ return {
+ x:
+ previousVelocity.x * (1 - CURSOR_VELOCITY_SMOOTHING) +
+ measuredVelocity.x * CURSOR_VELOCITY_SMOOTHING,
+ y:
+ previousVelocity.y * (1 - CURSOR_VELOCITY_SMOOTHING) +
+ measuredVelocity.y * CURSOR_VELOCITY_SMOOTHING,
+ };
+};
+
+const computePredictedCursor = ({
+ current,
+ previous,
+ layerRect,
+}: {
+ current: CursorSample;
+ previous: CursorSample | undefined;
+ layerRect: Rect | undefined;
+}): { coordinates: CursorCoordinates; velocity: CursorVelocity } => {
+ if (previous === undefined) {
+ return {
+ coordinates: toCursorCoordinates(current),
+ velocity: ZERO_CURSOR_VELOCITY,
+ };
+ }
+ const elapsed = current.time - previous.time;
+ if (
+ elapsed <= 0 ||
+ elapsed > MAX_PREDICTION_SAMPLE_MS ||
+ (current.x === previous.x && current.y === previous.y)
+ ) {
+ return {
+ coordinates: toCursorCoordinates(current),
+ velocity: ZERO_CURSOR_VELOCITY,
+ };
+ }
+ const velocity = computeSmoothedVelocity({
+ measuredVelocity: {
+ x: (current.x - previous.x) / elapsed,
+ y: (current.y - previous.y) / elapsed,
+ },
+ previousVelocity: previous.velocity,
+ });
+ const prediction = capPredictionDistance({
+ x: velocity.x * CURSOR_PREDICTION_MS,
+ y: velocity.y * CURSOR_PREDICTION_MS,
+ });
+ return {
+ coordinates: {
+ x: clampCoordinate({
+ value: current.x + prediction.x,
+ max: layerRect?.width,
+ }),
+ y: clampCoordinate({
+ value: current.y + prediction.y,
+ max: layerRect?.height,
+ }),
+ },
+ velocity,
+ };
+};
+
const shouldSkipCollaborator = ({
currentPageId,
collaboratorPageId,
@@ -143,6 +297,82 @@ const areInstanceSelectorsEqual = (
return left.every((id, index) => id === right[index]);
};
+const CollaborativeCursor = ({
+ color,
+ coordinates,
+ label,
+ layerRect,
+ sampleTime,
+}: {
+ color: string | undefined;
+ coordinates: CursorCoordinates;
+ label: string | undefined;
+ layerRect: Rect | undefined;
+ sampleTime: number | undefined;
+}) => {
+ const elementRef = useRef<HTMLDivElement>(null);
+ const previousSampleRef = useRef<CursorSample>();
+ const { x, y } = coordinates;
+ const layerWidth = layerRect?.width;
+ const layerHeight = layerRect?.height;
+
+ useLayoutEffect(() => {
+ const element = elementRef.current;
+ if (element === null) {
+ return;
+ }
+ const currentSample = {
+ x,
+ y,
+ time: sampleTime ?? Date.now(),
+ };
+ const predictionLayerRect =
+ layerWidth === undefined || layerHeight === undefined
+ ? undefined
+ : { left: 0, top: 0, width: layerWidth, height: layerHeight };
+ const prediction = computePredictedCursor({
+ current: currentSample,
+ previous: previousSampleRef.current,
+ layerRect: predictionLayerRect,
+ });
+ element.style.transform = `translate3d(${prediction.coordinates.x}px, ${prediction.coordinates.y}px, 0)`;
+ previousSampleRef.current = {
+ ...currentSample,
+ velocity: prediction.velocity,
+ };
+ }, [x, y, layerHeight, layerWidth, sampleTime]);
+
+ return (
+ <div
+ ref={elementRef}
+ className={cursorStyle()}
+ style={{
+ color,
+ }}
+ >
+ <svg
+ width="14"
+ height="20"
+ viewBox="0 0 14 20"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M1 1.5L1 17.7L4.8 13.4L8 19L11 17.4L7.8 11.8L13 11.8L1 1.5Z"
+ fill="currentColor"
+ stroke="white"
+ strokeWidth="1"
+ />
+ </svg>
+ {label && (
+ <div className={cursorLabelStyle()} style={{ backgroundColor: color }}>
+ {label}
+ </div>
+ )}
+ </div>
+ );
+};
+
export const CollaborativeCursors = () => {
const collaborators = useStore($collaborators);
const canvasRect = useStore($canvasRect);
@@ -202,34 +432,18 @@ export const CollaborativeCursors = () => {
return;
}
- const { x, y } = coordinates;
-
const color = collaboratorColors.get(clientId);
+ const label = getCollaboratorLabel(collaborator);
return (
- <div
+ <CollaborativeCursor
key={clientId}
- className={cursorStyle()}
- style={{
- color,
- transform: `translate3d(${x}px, ${y}px, 0)`,
- }}
- >
- <svg
- width="14"
- height="20"
- viewBox="0 0 14 20"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- d="M1 1.5L1 17.7L4.8 13.4L8 19L11 17.4L7.8 11.8L13 11.8L1 1.5Z"
- fill="currentColor"
- stroke="white"
- strokeWidth="1"
- />
- </svg>
- </div>
+ color={color}
+ coordinates={coordinates}
+ label={label}
+ layerRect={layerRect}
+ sampleTime={collaborator.lastSeen}
+ />
);
})}
</div>
@@ -237,6 +451,8 @@ export const CollaborativeCursors = () => {
};
export const __testing__ = {
+ getCollaboratorLabel,
+ computePredictedCursor,
shouldSkipCollaborator,
hasCursorPosition,
computeCursorCoordinates,
diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsx
index 6d9a322f2d..b04ec59cfd 100644
--- a/apps/builder/app/routes/_ui.(builder).tsx
+++ b/apps/builder/app/routes/_ui.(builder).tsx
@@ -37,6 +37,7 @@ import {
isFetchDestination,
} from "~/services/destinations.server";
import { loader as authWsLoader } from "./auth.ws";
+import { getUserById } from "~/shared/db/user.server";
export { ErrorBoundary } from "~/shared/error/error-boundary";
export const links = () => {
@@ -211,6 +212,10 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {
}
const { planFeatures, purchases } = context;
+ const user =
+ context.authorization.type === "user"
+ ? await getUserById(context, context.authorization.userId)
+ : undefined;
if (project.userId === null) {
throw new AuthorizationError("Project must have project userId defined");
@@ -253,6 +258,7 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {
authToken,
authTokenPermissions,
authPermit,
+ user,
role,
planFeatures,
purchases,
diff --git a/apps/builder/app/shared/awareness.test.tsx b/apps/builder/app/shared/awareness.test.tsx
index 3fb549e8df..a274b0a727 100644
--- a/apps/builder/app/shared/awareness.test.tsx
+++ b/apps/builder/app/shared/awareness.test.tsx
@@ -1,9 +1,10 @@
import { afterEach, expect, test, vi } from "vitest";
import { $awareness, __testing__, startPointerTracking } from "./awareness";
-const { $pointerPosition } = __testing__;
+const { $pointerPosition, getUserAwareness } = __testing__;
import { findPageAndSelectorByInstanceId } from "./instance-utils";
import { $selectedPageId } from "./nano-states/pages";
+import { $user } from "./nano-states/misc";
import { createDefaultPages } from "@webstudio-is/project-build";
import { $, renderData } from "@webstudio-is/template";
@@ -54,9 +55,61 @@ afterEach(async () => {
vi.useRealTimers();
$selectedPageId.set(undefined);
$pointerPosition.set(undefined);
+ $user.set(undefined);
await Promise.resolve();
});
+test("user awareness uses username and avatar", async () => {
+ const user = {
+ username: " Ada ",
+ email: "[email protected]",
+ image: "https://example.com/avatar.png",
+ } as NonNullable<Parameters<typeof $user.set>[0]>;
+
+ expect(getUserAwareness(user)).toEqual({
+ name: "Ada",
+ avatarUrl: "https://example.com/avatar.png",
+ });
+});
+
+test("user awareness falls back to email", async () => {
+ const user = {
+ username: "",
+ email: "[email protected]",
+ image: "",
+ } as NonNullable<Parameters<typeof $user.set>[0]>;
+
+ expect(getUserAwareness(user)).toEqual({
+ });
+});
+
+test("awareness includes user identity", async () => {
+ const listener = vi.fn();
+ const unsubscribe = $awareness.listen(listener);
+ const user = {
+ username: "Ada",
+ email: "[email protected]",
+ image: "https://example.com/avatar.png",
+ } as NonNullable<Parameters<typeof $user.set>[0]>;
+
+ await Promise.resolve();
+ listener.mockClear();
+
+ $user.set(user);
+ await Promise.resolve();
+
+ expect(listener.mock.calls[0]?.[0]).toEqual({
+ avatarUrl: "https://example.com/avatar.png",
+ name: "Ada",
+ pageId: undefined,
+ pointerPosition: undefined,
+ selectedInstanceIds: undefined,
+ });
+
+ unsubscribe();
+});
+
test("awareness updates are coalesced into one microtask", async () => {
const listener = vi.fn();
const unsubscribe = $awareness.listen(listener);
diff --git a/apps/builder/app/shared/awareness.ts b/apps/builder/app/shared/awareness.ts
index 29054e3d41..7ce403deed 100644
--- a/apps/builder/app/shared/awareness.ts
+++ b/apps/builder/app/shared/awareness.ts
@@ -2,21 +2,35 @@ import { atom, computed } from "nanostores";
import type { Rect } from "@webstudio-is/design-system";
import type { CollaboratorInfo } from "@webstudio-is/sync-client";
import { $selectedInstanceSelector } from "./nano-states/instances";
+import { $user } from "./nano-states/misc";
import { $selectedPageId } from "./nano-states/pages";
-const POINTER_FPS_LIMIT = 8;
+const POINTER_FPS_LIMIT = 5;
const POINTER_FRAME_MS = Math.ceil(1000 / POINTER_FPS_LIMIT);
export type Awareness = Pick<
CollaboratorInfo,
- "pageId" | "selectedInstanceIds" | "pointerPosition"
+ "name" | "avatarUrl" | "pageId" | "selectedInstanceIds" | "pointerPosition"
>;
export const $pointerPosition = atom<CollaboratorInfo["pointerPosition"]>();
+const getUserAwareness = (user: ReturnType<typeof $user.get>) => {
+ if (user === undefined) {
+ return {};
+ }
+ const name = user.username?.trim() || user.email?.trim();
+ const avatarUrl = user.image || undefined;
+ return {
+ ...(name === undefined || name.length === 0 ? {} : { name }),
+ ...(avatarUrl === undefined || avatarUrl.length === 0 ? {} : { avatarUrl }),
+ };
+};
+
const $computedAwareness = computed(
- [$pointerPosition, $selectedPageId, $selectedInstanceSelector],
- (pointerPosition, pageId, selectedInstanceIds): Awareness => ({
+ [$pointerPosition, $selectedPageId, $selectedInstanceSelector, $user],
+ (pointerPosition, pageId, selectedInstanceIds, user): Awareness => ({
+ ...getUserAwareness(user),
pageId,
selectedInstanceIds,
pointerPosition,
@@ -160,4 +174,4 @@ export const startPointerTracking = () => {
};
};
-export const __testing__ = { $pointerPosition };
+export const __testing__ = { $pointerPosition, getUserAwareness };
diff --git a/apps/builder/app/shared/share-project/share-project-container.tsx b/apps/builder/app/shared/share-project/share-project-container.tsx
index ef3c8356e9..8941db411a 100644
--- a/apps/builder/app/shared/share-project/share-project-container.tsx
+++ b/apps/builder/app/shared/share-project/share-project-container.tsx
@@ -4,7 +4,7 @@ import { builderUrl } from "~/shared/router-utils";
import { trpcClient } from "../trpc/trpc-client";
import { ShareProject, type LinkOptions } from "./share-project";
import { useStore } from "@nanostores/react";
-import { $permissions } from "../nano-states";
+import { $permissions, $purchases } from "../nano-states";
const useShareProjectContainer = (projectId: string) => {
const {
@@ -99,6 +99,7 @@ type ShareButtonProps = {
*/
export const ShareProjectContainer = ({ projectId }: ShareButtonProps) => {
const { allowAdditionalPermissions } = useStore($permissions);
+ const purchases = useStore($purchases);
const {
links,
handleChangeDebounced,
@@ -110,6 +111,7 @@ export const ShareProjectContainer = ({ projectId }: ShareButtonProps) => {
return (
<ShareProject
allowAdditionalPermissions={allowAdditionalPermissions}
+ isFreePlan={purchases.length === 0}
links={links}
onChange={handleChangeDebounced}
onDelete={handleDelete}
diff --git a/apps/builder/app/shared/share-project/share-project.stories.tsx b/apps/builder/app/shared/share-project/share-project.stories.tsx
index 776fba0ce2..89bc1c380d 100644
--- a/apps/builder/app/shared/share-project/share-project.stories.tsx
+++ b/apps/builder/app/shared/share-project/share-project.stories.tsx
@@ -113,6 +113,7 @@ const ShareProjectPopover = ({
<ShareProjectComponent
{...props}
allowAdditionalPermissions={false}
+ isFreePlan={true}
isPending={false}
builderUrl={builderUrl}
/>
diff --git a/apps/builder/app/shared/share-project/share-project.test.tsx b/apps/builder/app/shared/share-project/share-project.test.tsx
new file mode 100644
index 0000000000..5afa20fc56
--- /dev/null
+++ b/apps/builder/app/shared/share-project/share-project.test.tsx
@@ -0,0 +1,34 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { expect, test } from "vitest";
+import { ShareLinkSecurityNotice, ShareProject } from "./share-project";
+
+const shareProjectProps = {
+ links: [],
+ onChange: () => {},
+ onDelete: () => {},
+ onCreate: () => {},
+ builderUrl: () => "https://example.com",
+ isPending: false,
+ allowAdditionalPermissions: false,
+};
+
+test("warns about sharing links over insecure channels", () => {
+ const markup = renderToStaticMarkup(<ShareLinkSecurityNotice />);
+
+ expect(markup).toContain("Sharing links over insecure channels");
+ expect(markup).toContain("Team plan");
+ expect(markup).toContain("https://webstudio.is/pricing");
+ expect(markup).toContain("Upgrade");
+});
+
+test("shows security notice only on free plan", () => {
+ expect(
+ renderToStaticMarkup(<ShareProject {...shareProjectProps} isFreePlan />)
+ ).toContain("Sharing links over insecure channels");
+
+ expect(
+ renderToStaticMarkup(
+ <ShareProject {...shareProjectProps} isFreePlan={false} />
+ )
+ ).not.toContain("Sharing links over insecure channels");
+});
diff --git a/apps/builder/app/shared/share-project/share-project.tsx b/apps/builder/app/shared/share-project/share-project.tsx
index 1f068343b7..385796b485 100644
--- a/apps/builder/app/shared/share-project/share-project.tsx
+++ b/apps/builder/app/shared/share-project/share-project.tsx
@@ -30,12 +30,14 @@ import {
IconButton,
Checkbox,
Grid,
+ PanelBanner,
} from "@webstudio-is/design-system";
import {
CopyIcon,
EllipsesIcon,
PlusIcon,
InfoCircleIcon,
+ UpgradeIcon,
} from "@webstudio-is/icons";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { useIds } from "../form-utils";
@@ -50,6 +52,37 @@ const Item = (props: ComponentProps<typeof Flex>) => (
/>
);
+const PricingUpgradeLink = ({
+ children = "Upgrade",
+}: {
+ children?: string;
+}) => (
+ <Link
+ className={buttonStyle({ color: "gradient" })}
+ color="contrast"
+ underline="none"
+ href="https://webstudio.is/pricing"
+ target="_blank"
+ >
+ {children}
+ </Link>
+);
+
+export const ShareLinkSecurityNotice = () => (
+ <PanelBanner variant="warning">
+ <Text>
+ Sharing links over insecure channels can expose project access. Upgrade to
+ the Team plan for safer collaboration with realtime multiplayer.
+ </Text>
+ <Flex align="center" gap={1}>
+ <UpgradeIcon />
+ <Link color="inherit" target="_blank" href="https://webstudio.is/pricing">
+ Upgrade
+ </Link>
+ </Flex>
+ </PanelBanner>
+);
+
type PermissionProps = {
title: string;
info: ReactNode;
@@ -176,15 +209,7 @@ const Menu = ({
<br />
Upgrade to a Pro account to set additional permissions.
<br /> <br />
- <Link
- className={buttonStyle({ color: "gradient" })}
- color="contrast"
- underline="none"
- href="https://webstudio.is/pricing"
- target="_blank"
- >
- Upgrade
- </Link>
+ <PricingUpgradeLink />
</>
)}
</Flex>
@@ -267,15 +292,7 @@ const Menu = ({
Upgrade to a Pro account to share with Content Edit
permissions.
<br /> <br />
- <Link
- className={buttonStyle({ color: "gradient" })}
- color="contrast"
- underline="none"
- href="https://webstudio.is/pricing"
- target="_blank"
- >
- Upgrade
- </Link>
+ <PricingUpgradeLink />
</>
)}
</Flex>
@@ -336,15 +353,7 @@ const Menu = ({
<br />
Upgrade to a Pro account to share with Admin permissions.
<br /> <br />
- <Link
- className={buttonStyle({ color: "gradient" })}
- color="contrast"
- underline="none"
- href="https://webstudio.is/pricing"
- target="_blank"
- >
- Upgrade
- </Link>
+ <PricingUpgradeLink />
</>
)}
</Flex>
@@ -445,6 +454,7 @@ type ShareProjectProps = {
builderUrl: SharedLinkItemType["builderUrl"];
isPending: boolean;
allowAdditionalPermissions: boolean;
+ isFreePlan: boolean;
};
const animateCollapsibleHeight = keyframes({
@@ -472,6 +482,7 @@ export const ShareProject = ({
builderUrl,
isPending,
allowAdditionalPermissions,
+ isFreePlan,
}: ShareProjectProps) => {
const items = links.map((link) => (
<Fragment key={link.token}>
@@ -509,6 +520,13 @@ export const ShareProject = ({
return (
<Flex direction="column" css={{ width: theme.spacing[33] }}>
+ {isFreePlan && (
+ <>
+ <ShareLinkSecurityNotice />
+ <Separator />
+ </>
+ )}
+
<Collapsible.Root open={items.length > 0}>
<Collapsible.Content className={collapsibleStyle()}>
{items}
diff --git a/apps/builder/app/shared/sync/patch/patch-normalize.server.ts b/apps/builder/app/shared/sync/patch/patch-normalize.server.ts
index 5010c39947..d9418f03e1 100644
--- a/apps/builder/app/shared/sync/patch/patch-normalize.server.ts
+++ b/apps/builder/app/shared/sync/patch/patch-normalize.server.ts
@@ -1,6 +1,7 @@
import type { Project } from "@webstudio-is/project";
import type { BuildPatchTransaction } from "@webstudio-is/project/index.server";
import type { Build } from "@webstudio-is/project-build";
+import { stripRevisePatchesFromPayload } from "@webstudio-is/sync-client";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
export type PatchWriter =
@@ -32,23 +33,11 @@ export type PatchData<Entry extends PatchDataEntry = PatchDataEntry> = {
entries: Entry[];
};
-const stripRevisePatchesFromPatchTransaction = (
+const normalizePatchTransaction = (
transaction: BuildPatchTransaction
): BuildPatchTransaction => {
- let changed = false;
- const payload = transaction.payload.map((change) => {
- if (Object.hasOwn(change, "revisePatches") === false) {
- return change;
- }
- changed = true;
- const { revisePatches: _revisePatches, ...rest } =
- change as typeof change & {
- revisePatches?: unknown;
- };
- return rest;
- });
-
- if (changed === false) {
+ const payload = stripRevisePatchesFromPayload(transaction.payload);
+ if (payload === transaction.payload) {
return transaction;
}
return { ...transaction, payload };
@@ -73,7 +62,7 @@ export const normalizePatchRequest = <Entry extends PatchDataEntry>(
clientVersion: data.version,
entries: data.entries.map((entry) => ({
seq: entry.seq,
- transaction: stripRevisePatchesFromPatchTransaction(entry.transaction),
+ transaction: normalizePatchTransaction(entry.transaction),
writer: getWriter(entry),
})),
};
diff --git a/apps/builder/app/shared/sync/sync-client.test.ts b/apps/builder/app/shared/sync/sync-client.test.ts
new file mode 100644
index 0000000000..1890f5f524
--- /dev/null
+++ b/apps/builder/app/shared/sync/sync-client.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, test } from "vitest";
+import { __testing__ } from "./sync-client";
+
+const { resolveMultiplayerRelayUrl } = __testing__;
+
+describe("resolveMultiplayerRelayUrl", () => {
+ test("keeps configured absolute URL outside local wstd.dev", () => {
+ expect(
+ resolveMultiplayerRelayUrl(
+ "https://apps.webstudio.is/collab-relay",
+ "https://builder.webstudio.is/builder/project-id"
+ )
+ ).toBe("https://apps.webstudio.is/collab-relay");
+ });
+
+ test("keeps configured absolute URL on local wstd.dev", () => {
+ expect(
+ resolveMultiplayerRelayUrl(
+ "https://apps.webstudio.is/collab-relay",
+ "https://p-project-id.wstd.dev:5173/builder/project-id"
+ )
+ ).toBe("https://apps.webstudio.is/collab-relay");
+ });
+
+ test("proxies relative relay URLs through the local wstd.dev dev server", () => {
+ expect(
+ resolveMultiplayerRelayUrl(
+ "/collab-relay",
+ "https://p-project-id.wstd.dev:5173/builder/project-id"
+ )
+ ).toBe("https://p-project-id.wstd.dev:5173/collab-relay");
+ });
+
+ test("supports relative relay URLs", () => {
+ expect(
+ resolveMultiplayerRelayUrl(
+ "/collab-relay",
+ "https://builder.webstudio.is/builder/project-id"
+ )
+ ).toBe("https://builder.webstudio.is/collab-relay");
+ });
+});
diff --git a/apps/builder/app/shared/sync/sync-client.ts b/apps/builder/app/shared/sync/sync-client.ts
index 4e76a970c7..c738c85c42 100644
--- a/apps/builder/app/shared/sync/sync-client.ts
+++ b/apps/builder/app/shared/sync/sync-client.ts
@@ -37,17 +37,22 @@ type SyncModeClient = {
onDataLoaded(data: LoadedBuilderData): void;
};
-const resolveMultiplayerRelayUrl = (relayUrl: string) => {
- if (typeof window === "undefined") {
+const resolveMultiplayerRelayUrl = (
+ relayUrl: string,
+ currentHref = typeof window === "undefined" ? undefined : window.location.href
+) => {
+ if (currentHref === undefined) {
return relayUrl;
}
- const configuredUrl = new URL(relayUrl, window.location.origin);
- const currentUrl = new URL(window.location.href);
+ const currentUrl = new URL(currentHref);
+ const configuredUrl = new URL(relayUrl, currentUrl.origin);
+ const isRelativeRelayUrl =
+ relayUrl.startsWith("/") || relayUrl.startsWith(".");
const isLocalWstdDev =
currentUrl.hostname === "wstd.dev" ||
currentUrl.hostname.endsWith(".wstd.dev");
- if (isLocalWstdDev && currentUrl.port === "5173") {
+ if (isRelativeRelayUrl && isLocalWstdDev && currentUrl.port === "5173") {
return new URL(configuredUrl.pathname, currentUrl.origin).href;
}
@@ -87,7 +92,7 @@ export const initializeClientSync = ({
signal: AbortSignal;
onReady?: () => void;
}) => {
- const multiplayerRelayUrl = isFeatureEnabled("collabRelay")
+ const multiplayerRelayUrl = isFeatureEnabled("multiplayer")
? publicStaticEnv.COLLAB_RELAY_URL?.trim() || undefined
: undefined;
const resolvedMultiplayerRelayUrl =
@@ -166,3 +171,7 @@ export const destroyClientSync = () => {
};
export const getSyncClient = () => client;
+
+export const __testing__ = {
+ resolveMultiplayerRelayUrl,
+};
diff --git a/apps/builder/vite.config.ts b/apps/builder/vite.config.ts
index a9bec86157..04fef1f220 100644
--- a/apps/builder/vite.config.ts
+++ b/apps/builder/vite.config.ts
@@ -33,7 +33,7 @@ export default defineConfig(({ mode }) => {
}
const env = loadEnv(mode, __dirname, "");
- const collabRelayProxyTarget =
+ const multiplayerRelayProxyTarget =
process.env.COLLAB_RELAY_PROXY_TARGET ??
env.COLLAB_RELAY_PROXY_TARGET ??
"http://127.0.0.1:1999";
@@ -126,7 +126,7 @@ export default defineConfig(({ mode }) => {
host: "wstd.dev",
proxy: {
"/collab-relay": {
- target: collabRelayProxyTarget,
+ target: multiplayerRelayProxyTarget,
ws: true,
},
},
diff --git a/packages/feature-flags/src/flags.ts b/packages/feature-flags/src/flags.ts
index fc900c9be5..4e8ce063a0 100644
--- a/packages/feature-flags/src/flags.ts
+++ b/packages/feature-flags/src/flags.ts
@@ -2,5 +2,4 @@
export const internalComponents = false;
export const unsupportedBrowsers = false;
export const resourceProp = false;
-export const tailwind = false;
-export const collabRelay = false;
+export const multiplayer = false;
diff --git a/packages/multiplayer-protocol/package.json b/packages/multiplayer-protocol/package.json
index ab1de78e2f..253eb6e263 100644
--- a/packages/multiplayer-protocol/package.json
+++ b/packages/multiplayer-protocol/package.json
@@ -15,7 +15,7 @@
"sideEffects": false,
"scripts": {
"typecheck": "tsgo --noEmit",
- "test": "vitest run"
+ "test": "vitest run --passWithNoTests"
},
"devDependencies": {
"@webstudio-is/tsconfig": "workspace:*",
diff --git a/packages/multiplayer-protocol/src/index.ts b/packages/multiplayer-protocol/src/index.ts
index 457fc25195..c8fb05814b 100644
--- a/packages/multiplayer-protocol/src/index.ts
+++ b/packages/multiplayer-protocol/src/index.ts
@@ -106,41 +106,6 @@ export type RelayServerMessage =
| ErrorMessage
| PresenceMessage;
-export const stripRevisePatchesFromTransaction = (
- transaction: Transaction
-): Transaction => {
- if (transaction.object !== "server" || !Array.isArray(transaction.payload)) {
- return transaction;
- }
-
- let changed = false;
- const nextPayload = transaction.payload.map((entry) => {
- if (
- entry === null ||
- typeof entry !== "object" ||
- Array.isArray(entry) ||
- !Object.hasOwn(entry, "revisePatches")
- ) {
- return entry;
- }
- changed = true;
- const { revisePatches: _revisePatches, ...rest } = entry as Record<
- string,
- unknown
- >;
- return rest;
- });
-
- if (!changed) {
- return transaction;
- }
-
- return {
- ...transaction,
- payload: nextPayload,
- };
-};
-
export interface OperationOrder {
actorId: string;
clientSeq: number;
diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.ts
index 9bcc292d14..e89ded7e96 100644
--- a/packages/project/src/db/build-patch-core.ts
+++ b/packages/project/src/db/build-patch-core.ts
@@ -57,6 +57,14 @@ export type BuildPatchUpdateResult =
| { status: "version_mismatched"; errors: string }
| { status: "error"; errors: string };
+export const singlePlayerVersionMismatchError =
+ "You are currently in single-player mode. The project has been edited in a different tab, browser, or by another user. Realtime collaboration, also known as multiplayer, is available on the Team plan and helps avoid this conflict. Please reload the page to get the latest version.";
+
+export const singlePlayerVersionMismatchResult = {
+ status: "version_mismatched",
+ errors: singlePlayerVersionMismatchError,
+} as const satisfies BuildPatchUpdateResult;
+
export const createBuildPatchUpdate = async ({
build,
clientVersion,
@@ -81,10 +89,7 @@ export const createBuildPatchUpdate = async ({
return { status: "ok", assetPatches: [], nextVersion: serverVersion };
}
- return {
- status: "version_mismatched",
- errors: `You are currently in single-player mode. The project has been edited in a different tab, browser, or by another user. Please reload the page to get the latest version.`,
- };
+ return singlePlayerVersionMismatchResult;
}
const buildData: {
diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.ts
index 183aff27f4..e4f3149f28 100644
--- a/packages/project/src/db/build-patch.test.ts
+++ b/packages/project/src/db/build-patch.test.ts
@@ -9,7 +9,10 @@ import {
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { Patch } from "immer";
import { patchBuild, type BuildPatchTransaction } from "./build-patch";
-import { createBuildPatchUpdate } from "./build-patch-core";
+import {
+ createBuildPatchUpdate,
+ singlePlayerVersionMismatchResult,
+} from "./build-patch-core";
const server = createTestServer();
@@ -163,7 +166,7 @@ describe("patchBuild", () => {
createContext()
);
- expect(result.status).toBe("version_mismatched");
+ expect(result).toEqual(singlePlayerVersionMismatchResult);
});
test("returns version_mismatched when optimistic update affects no rows", async () => {
@@ -182,7 +185,7 @@ describe("patchBuild", () => {
createContext()
);
- expect(result.status).toBe("version_mismatched");
+ expect(result).toEqual(singlePlayerVersionMismatchResult);
});
test("rejects unknown namespaces", async () => {
diff --git a/packages/project/src/db/build-patch.ts b/packages/project/src/db/build-patch.ts
index f43dee95de..c2d1e4e331 100644
--- a/packages/project/src/db/build-patch.ts
+++ b/packages/project/src/db/build-patch.ts
@@ -6,6 +6,7 @@ import type { Project } from "./project";
import { updatePreviewImage } from "./project";
import {
createBuildPatchUpdate,
+ singlePlayerVersionMismatchResult,
type BuildPatchChange,
type BuildPatchTransaction,
} from "./build-patch-core";
@@ -73,10 +74,7 @@ export const patchBuild = async (
}
if (update.count === 0) {
- return {
- status: "version_mismatched",
- errors: `You are currently in single-player mode. The project has been edited in a different tab, browser, or by another user. Please reload the page to get the latest version.`,
- };
+ return singlePlayerVersionMismatchResult;
}
if (result.previewImageAssetId !== undefined) {
diff --git a/packages/sync-client/src/index.ts b/packages/sync-client/src/index.ts
index 6b57eba248..f0fa214ada 100644
--- a/packages/sync-client/src/index.ts
+++ b/packages/sync-client/src/index.ts
@@ -30,8 +30,11 @@ export type {
export {
persistenceBacklogErrorMessage,
rateLimitedErrorMessage,
- stripRevisePatchesFromTransaction,
} from "@webstudio-is/multiplayer-protocol";
+export {
+ stripRevisePatchesFromPayload,
+ stripRevisePatchesFromTransaction,
+} from "./transaction-utils";
export { $collaborators } from "./multiplayer/collab-state";
export {
$hasUnsavedSyncChanges,
diff --git a/packages/sync-client/src/multiplayer/websocket-emitter.ts b/packages/sync-client/src/multiplayer/websocket-emitter.ts
index b43b867b20..c2a231b14e 100644
--- a/packages/sync-client/src/multiplayer/websocket-emitter.ts
+++ b/packages/sync-client/src/multiplayer/websocket-emitter.ts
@@ -21,7 +21,7 @@ import type {
RelayClientMessage,
RelayServerMessage,
} from "@webstudio-is/multiplayer-protocol";
-import { stripRevisePatchesFromTransaction } from "@webstudio-is/multiplayer-protocol";
+import { stripRevisePatchesFromTransaction } from "../transaction-utils";
interface MessageCallbacks
extends Pick<
diff --git a/packages/multiplayer-protocol/src/index.test.ts b/packages/sync-client/src/transaction-utils.test.ts
similarity index 69%
rename from packages/multiplayer-protocol/src/index.test.ts
rename to packages/sync-client/src/transaction-utils.test.ts
index cd5e54cb88..94c84ee93e 100644
--- a/packages/multiplayer-protocol/src/index.test.ts
+++ b/packages/sync-client/src/transaction-utils.test.ts
@@ -1,5 +1,27 @@
import { describe, expect, test } from "vitest";
-import { stripRevisePatchesFromTransaction } from ".";
+import {
+ stripRevisePatchesFromPayload,
+ stripRevisePatchesFromTransaction,
+} from "./transaction-utils";
+
+describe("stripRevisePatchesFromPayload", () => {
+ test("removes revisePatches from array payload entries", () => {
+ const payload = [
+ {
+ namespace: "instances",
+ patches: [{ op: "add", path: ["x"], value: 1 }],
+ revisePatches: [{ op: "remove", path: ["x"] }],
+ },
+ ];
+
+ expect(stripRevisePatchesFromPayload(payload)).toEqual([
+ {
+ namespace: "instances",
+ patches: [{ op: "add", path: ["x"], value: 1 }],
+ },
+ ]);
+ });
+});
describe("stripRevisePatchesFromTransaction", () => {
test("removes revisePatches from server payload entries", () => {
diff --git a/packages/sync-client/src/transaction-utils.ts b/packages/sync-client/src/transaction-utils.ts
new file mode 100644
index 0000000000..38b5d6d863
--- /dev/null
+++ b/packages/sync-client/src/transaction-utils.ts
@@ -0,0 +1,49 @@
+import type { Transaction } from "./types";
+
+export const stripRevisePatchesFromPayload = <Payload>(
+ payload: Payload
+): Payload => {
+ if (!Array.isArray(payload)) {
+ return payload;
+ }
+ let changed = false;
+ const nextPayload = payload.map((entry) => {
+ if (
+ entry === null ||
+ typeof entry !== "object" ||
+ Array.isArray(entry) ||
+ !Object.hasOwn(entry, "revisePatches")
+ ) {
+ return entry;
+ }
+ changed = true;
+ const { revisePatches: _revisePatches, ...rest } = entry as Record<
+ string,
+ unknown
+ >;
+ return rest;
+ });
+
+ if (!changed) {
+ return payload;
+ }
+ return nextPayload as Payload;
+};
+
+export const stripRevisePatchesFromTransaction = (
+ transaction: Transaction
+): Transaction => {
+ if (transaction.object !== "server") {
+ return transaction;
+ }
+
+ const payload = stripRevisePatchesFromPayload(transaction.payload);
+ if (payload === transaction.payload) {
+ return transaction;
+ }
+
+ return {
+ ...transaction,
+ payload,
+ };
+};