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: workspace seat billing at invite time, persist pending invites (#5680)

Oleg Isonen90f92c58d319
diff --git a/apps/builder/.env b/apps/builder/.env
index a024ac86da..20af7f231d 100644
--- a/apps/builder/.env
+++ b/apps/builder/.env
@@ -73,7 +73,9 @@ PLANS='[
"name": "Team",
"extends": "Pro",
"features": {
- "maxWorkspaces": 20
+ "maxWorkspaces": 20,
+ "minSeats": 5,
+ "maxSeatsPerWorkspace": 20
}
}
]'
diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsx
index 615712459f..02c882f27f 100644
--- a/apps/builder/app/dashboard/dashboard.tsx
+++ b/apps/builder/app/dashboard/dashboard.tsx
@@ -234,6 +234,14 @@ export const Dashboard = () => {
currentWorkspaceId,
} = data;
const currentWorkspace = workspaces?.find((w) => w.id === currentWorkspaceId);
+
+ // Workspace ID in the URL but not found — it was deleted or the user was removed.
+ // Redirect to the default dashboard to avoid a broken state.
+ if (currentWorkspaceId !== undefined && currentWorkspace === undefined) {
+ navigate(dashboardPath("projects"), { replace: true });
+ return null;
+ }
+
const isWorkspaceSuspended = isDowngradedForMember(currentWorkspace);
const hasProjects = projects.length > 0 || isWorkspaceSuspended;
const isDefaultWorkspace =
@@ -360,6 +368,7 @@ export const Dashboard = () => {
publisherHost={publisherHost}
projectsTags={user.projectsTags}
currentWorkspaceId={currentWorkspaceId}
+ workspace={currentWorkspace}
isWorkspaceSuspended={isWorkspaceSuspended}
/>
)}
diff --git a/apps/builder/app/dashboard/projects/projects.tsx b/apps/builder/app/dashboard/projects/projects.tsx
index 7a08b40a33..83d2c65b2c 100644
--- a/apps/builder/app/dashboard/projects/projects.tsx
+++ b/apps/builder/app/dashboard/projects/projects.tsx
@@ -13,6 +13,7 @@ import {
} from "@webstudio-is/design-system";
import { RepeatGridIcon, ListViewIcon } from "@webstudio-is/icons";
import type { DashboardProject } from "@webstudio-is/dashboard";
+import type { WorkspaceWithRelation } from "@webstudio-is/project";
import { ProjectCard } from "./project-card";
import { CreateProject } from "./project-dialogs";
import { Header, Main } from "../shared/layout";
@@ -29,7 +30,7 @@ import {
type SortField,
} from "./sort";
import { AlertIcon } from "@webstudio-is/icons";
-import { SEAT_SUSPENDED_MESSAGE } from "~/shared/notifications/seat-suspended";
+import { getSeatSuspendedMessage } from "~/shared/notifications/seat-suspended";
import { ProjectsList } from "./projects-list";
export const ProjectsGrid = ({
@@ -68,6 +69,7 @@ type ProjectsProps = {
publisherHost: string;
projectsTags: User["projectsTags"];
currentWorkspaceId?: string;
+ workspace?: WorkspaceWithRelation;
isWorkspaceSuspended?: boolean;
};
@@ -175,7 +177,7 @@ export const Projects = (props: ProjectsProps) => {
</Flex>
<Flex css={{ paddingInline: theme.spacing[13] }}>
{projects.length === 0 ? (
- props.isWorkspaceSuspended ? (
+ props.isWorkspaceSuspended && props.workspace !== undefined ? (
<Flex
css={{
paddingBlock: theme.spacing[20],
@@ -188,7 +190,9 @@ export const Projects = (props: ProjectsProps) => {
<AlertIcon color={panelBannerIconColor} />
<Text variant="regularBold">Workspace suspended</Text>
</Flex>
- <Text variant="regular">{SEAT_SUSPENDED_MESSAGE}</Text>
+ <Text variant="regular">
+ {getSeatSuspendedMessage(props.workspace.name)}
+ </Text>
</PanelBanner>
</Flex>
) : (
diff --git a/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx b/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx
index f99df6184c..7e2bf0f63c 100644
--- a/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx
+++ b/apps/builder/app/dashboard/workspace/manage-members-dialog.tsx
@@ -61,7 +61,6 @@ type MemberRowProps = {
relation: Role;
canRemove: boolean;
onRemove: () => void;
- onChangeRole: (role: Role) => void;
}
);
@@ -82,38 +81,39 @@ const MemberRow = (props: MemberRowProps) => {
);
}
- const value = role === "pending" ? props.relation : localRole;
-
- const handleChange =
- role === "pending"
- ? props.onChangeRole
- : (newRole: Role) => {
- setError(undefined);
- setLocalRole(newRole);
- updateMutation.send(
- {
- workspaceId: props.workspaceId,
- memberUserId: props.userId,
- relation: newRole,
- },
- (result) => {
- if (result && "error" in result) {
- setError(result.error);
- setLocalRole(props.relation);
- return;
- }
- props.onRefresh();
- revalidator.revalidate();
- }
- );
- };
+ if (role === "pending") {
+ return (
+ <Text color="subtle" variant="regular">
+ Pending
+ </Text>
+ );
+ }
return (
<RoleSelect
color="ghost"
- value={value}
- onChange={handleChange}
- disabled={!props.canRemove || role === "pending"}
+ value={localRole}
+ onChange={(newRole: Role) => {
+ setError(undefined);
+ setLocalRole(newRole);
+ updateMutation.send(
+ {
+ workspaceId: props.workspaceId,
+ memberUserId: props.userId,
+ relation: newRole,
+ },
+ (result) => {
+ if (result && "error" in result) {
+ setError(result.error);
+ setLocalRole(props.relation);
+ return;
+ }
+ props.onRefresh();
+ revalidator.revalidate();
+ }
+ );
+ }}
+ disabled={!props.canRemove}
/>
);
})();
@@ -205,18 +205,12 @@ const MemberList = ({
workspaceId,
canRemove,
refreshKey,
- invitedEmails,
onRefresh,
- onRemoveInvited,
- onChangeInvitedRole,
}: {
workspaceId: string;
canRemove: boolean;
refreshKey: number;
- invitedEmails: Map<string, { relation: Role; notificationId: string }>;
onRefresh: () => void;
- onRemoveInvited: (email: string) => void;
- onChangeInvitedRole: (email: string, relation: Role) => void;
}) => {
const { load, data } = trpcClient.workspace.listMembers.useQuery();
@@ -234,15 +228,7 @@ const MemberList = ({
);
}
- const { owner, members } = result;
-
- // Show invited emails that aren't already in the real member list.
- // This makes behavior identical for existing vs non-existing emails,
- // preventing email enumeration.
- const knownEmails = new Set(members.map((m) => m.email));
- const pendingEntries = [...invitedEmails].filter(
- ([email]) => knownEmails.has(email) === false
- );
+ const { owner, members, pendingInvites } = result;
let index = 0;
@@ -263,16 +249,20 @@ const MemberList = ({
onRefresh={onRefresh}
/>
))}
- {pendingEntries.map(([email, { relation }]) => (
+ {pendingInvites.map((invite) => (
<MemberRow
- key={email}
- email={email}
+ key={invite.notificationId}
+ email={invite.email}
role="pending"
- relation={relation}
+ relation={invite.relation as Role}
canRemove={canRemove}
index={index++}
- onRemove={() => onRemoveInvited(email)}
- onChangeRole={(newRole) => onChangeInvitedRole(email, newRole)}
+ onRemove={() => {
+ nativeClient.notification.cancel
+ .mutate({ notificationId: invite.notificationId })
+ .then(() => onRefresh())
+ .catch(() => {});
+ }}
/>
))}
</Box>
@@ -297,9 +287,6 @@ export const ManageMembersDialog = ({
const [membersKey, setMembersKey] = useState(0);
const [inviting, setInviting] = useState(false);
const [inviteRelation, setInviteRelation] = useState<Role>("viewers");
- const [invitedEmails, setInvitedEmails] = useState<
- Map<string, { relation: Role; notificationId: string }>
- >(new Map());
useEffect(() => {
if (isOpen && isOwner) {
@@ -325,7 +312,6 @@ export const ManageMembersDialog = ({
setInviting(true);
const failed: string[] = [];
- const succeeded: { email: string; notificationId: string }[] = [];
for (const email of emails) {
try {
const result = await nativeClient.workspace.addMember.mutate({
@@ -333,9 +319,7 @@ export const ManageMembersDialog = ({
email,
relation: inviteRelation,
});
- if (result.success) {
- succeeded.push({ email, notificationId: result.notificationId });
- } else {
+ if (!result.success) {
failed.push(`${email}: ${result.error}`);
}
} catch (error) {
@@ -347,16 +331,6 @@ export const ManageMembersDialog = ({
setInviting(false);
- if (succeeded.length > 0) {
- setInvitedEmails((prev) => {
- const next = new Map(prev);
- for (const { email, notificationId } of succeeded) {
- next.set(email, { relation: inviteRelation, notificationId });
- }
- return next;
- });
- }
-
if (failed.length > 0) {
setErrors(failed);
} else {
@@ -421,35 +395,7 @@ export const ManageMembersDialog = ({
workspaceId={workspace.id}
canRemove={isOwner}
refreshKey={membersKey}
- invitedEmails={invitedEmails}
onRefresh={() => setMembersKey((key) => key + 1)}
- onRemoveInvited={(email) => {
- const entry = invitedEmails.get(email);
- if (entry) {
- // Fire-and-forget: cancel the server-side notification.
- // For fake IDs (non-existent users) this fails silently,
- // preserving anti-enumeration.
- nativeClient.notification.cancel
- .mutate({ notificationId: entry.notificationId })
- .catch(() => {});
- }
- setInvitedEmails((prev) => {
- const next = new Map(prev);
- next.delete(email);
- return next;
- });
- }}
- onChangeInvitedRole={(email, relation) => {
- setInvitedEmails((prev) => {
- const existing = prev.get(email);
- if (existing === undefined) {
- return prev;
- }
- const next = new Map(prev);
- next.set(email, { ...existing, relation });
- return next;
- });
- }}
/>
</Flex>
</ScrollAreaNative>
diff --git a/apps/builder/app/services/notification-router.server.ts b/apps/builder/app/services/notification-router.server.ts
new file mode 100644
index 0000000000..58329354f8
--- /dev/null
+++ b/apps/builder/app/services/notification-router.server.ts
@@ -0,0 +1,67 @@
+import { z } from "zod";
+import {
+ router,
+ procedure,
+ createErrorResponse,
+} from "@webstudio-is/trpc-interface/index.server";
+import { notification as notificationApi } from "@webstudio-is/project/index.server";
+
+export const notificationRouter = router({
+ list: procedure.query(async ({ ctx }) => {
+ try {
+ const notifications = await notificationApi.list(ctx);
+ return { success: true as const, data: notifications };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ count: procedure.query(async ({ ctx }) => {
+ try {
+ const total = await notificationApi.count(ctx);
+ return { success: true as const, data: total };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ accept: procedure
+ .input(
+ z.object({
+ notificationId: z.string(),
+ targetWorkspaceId: z.string().optional(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await notificationApi.accept(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ decline: procedure
+ .input(z.object({ notificationId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await notificationApi.decline(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ cancel: procedure
+ .input(z.object({ notificationId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await notificationApi.cancel(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+});
+
+export type NotificationRouter = typeof notificationRouter;
diff --git a/apps/builder/app/services/trcp-router.server.ts b/apps/builder/app/services/trcp-router.server.ts
index 70030e526f..4044848b6d 100644
--- a/apps/builder/app/services/trcp-router.server.ts
+++ b/apps/builder/app/services/trcp-router.server.ts
@@ -1,16 +1,14 @@
import { router } from "@webstudio-is/trpc-interface/index.server";
import { domainRouter } from "@webstudio-is/domain/index.server";
-import {
- projectRouter,
- workspaceRouter,
- notificationRouter,
-} from "@webstudio-is/project/index.server";
+import { projectRouter } from "@webstudio-is/project/index.server";
import { authorizationTokenRouter } from "@webstudio-is/authorization-token/index.server";
import { dashboardProjectRouter } from "@webstudio-is/dashboard/index.server";
import { marketplaceRouter } from "~/shared/marketplace/router.server";
import { subscriptionRouter } from "~/shared/polly/subscription-router.server";
import { userRouter } from "./user-router.server";
import { logoutRouter } from "./logout-router.server";
+import { notificationRouter } from "./notification-router.server";
+import { workspaceRouter } from "./workspace-router.server";
export const appRouter = router({
user: userRouter,
diff --git a/apps/builder/app/services/workspace-router.server.ts b/apps/builder/app/services/workspace-router.server.ts
new file mode 100644
index 0000000000..a4a40727f3
--- /dev/null
+++ b/apps/builder/app/services/workspace-router.server.ts
@@ -0,0 +1,355 @@
+import { z } from "zod";
+import {
+ router,
+ procedure,
+ createErrorResponse,
+} from "@webstudio-is/trpc-interface/index.server";
+import { workspace as workspaceApi } from "@webstudio-is/project/index.server";
+import { getPlanInfo } from "~/shared/db/plan-features.server";
+import { roles } from "@webstudio-is/trpc-interface/authorize";
+import env from "~/env/env.server";
+
+const Name = z.string().min(2).max(100);
+const Relation = z.enum(roles);
+
+type UpdateSeatsResult =
+ | { type: "success"; seats: number }
+ | { type: "error"; error: string };
+
+const updateSeats = async ({
+ userId,
+ subscriptionId,
+ newQuantity,
+ minSeats,
+ maxSeats,
+}: {
+ userId: string;
+ subscriptionId: string;
+ newQuantity: number;
+ minSeats: number;
+ maxSeats: number;
+}): Promise<UpdateSeatsResult | null> => {
+ if (!env.PAYMENT_WORKER_URL || !env.PAYMENT_WORKER_TOKEN) {
+ return null;
+ }
+
+ const url = `${env.PAYMENT_WORKER_URL}/seats/update`;
+
+ const response = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${env.PAYMENT_WORKER_TOKEN}`,
+ },
+ body: JSON.stringify({
+ userId,
+ subscriptionId,
+ newQuantity,
+ minSeats,
+ maxSeats,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `Payment worker /seats/update responded with ${response.status}`
+ );
+ }
+
+ return (await response.json()) as UpdateSeatsResult;
+};
+
+/**
+ * Syncs the Stripe seat quantity for the owner of a given workspace.
+ * Called after adding or removing members.
+ * Throws on payment worker errors so the caller can decide whether to soft-fail.
+ */
+const syncOwnerSeats = async (
+ workspaceId: string,
+ ctx: Parameters<typeof workspaceApi.countAllMembers>[1]
+) => {
+ const workspaceResult = await ctx.postgrest.client
+ .from("Workspace")
+ .select("userId")
+ .eq("id", workspaceId)
+ .eq("isDeleted", false)
+ .maybeSingle();
+
+ if (workspaceResult.error || workspaceResult.data === null) {
+ return;
+ }
+
+ const ownerId = workspaceResult.data.userId;
+ const planInfo = await getPlanInfo(ownerId, ctx.postgrest);
+ const { planFeatures, purchases } = planInfo;
+
+ const subscription = purchases.find((p) => p.subscriptionId !== undefined);
+ if (subscription?.subscriptionId === undefined) {
+ return;
+ }
+
+ const memberCount = await workspaceApi.countAllMembers(ownerId, ctx);
+
+ const result = await updateSeats({
+ userId: ownerId,
+ subscriptionId: subscription.subscriptionId,
+ newQuantity: memberCount,
+ minSeats: planFeatures.minSeats,
+ maxSeats: planFeatures.maxSeatsPerWorkspace,
+ });
+
+ if (result === null) {
+ return;
+ }
+
+ if (result.type === "error") {
+ throw new Error(`Payment worker rejected seat update: ${result.error}`);
+ }
+};
+
+export const workspaceRouter = router({
+ create: procedure
+ .input(z.object({ name: Name }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const workspace = await workspaceApi.create(
+ { ...input, maxWorkspaces: ctx.planFeatures.maxWorkspaces },
+ ctx
+ );
+ return { success: true as const, data: workspace };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ rename: procedure
+ .input(z.object({ workspaceId: z.string(), name: Name }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const workspace = await workspaceApi.rename(input, ctx);
+ return { success: true as const, data: workspace };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ delete: procedure
+ .input(
+ z.object({
+ workspaceId: z.string(),
+ deleteProjects: z.boolean().optional(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await workspaceApi.remove(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ list: procedure.query(async ({ ctx }) => {
+ try {
+ if (ctx.authorization.type !== "user") {
+ return { success: true as const, data: [] };
+ }
+ const workspaces = await workspaceApi.findMany(
+ ctx.authorization.userId,
+ ctx
+ );
+ return { success: true as const, data: workspaces };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ addMember: procedure
+ .input(
+ z.object({
+ workspaceId: z.string(),
+ email: z.string().email(),
+ relation: Relation,
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ if (ctx.planFeatures.maxWorkspaces <= 1) {
+ throw new Error("Upgrade your plan to invite members to workspaces.");
+ }
+
+ const { maxSeatsPerWorkspace } = ctx.planFeatures;
+ if (maxSeatsPerWorkspace > 0) {
+ const [membersResult, pendingResult] = await Promise.all([
+ ctx.postgrest.client
+ .from("WorkspaceMember")
+ .select("userId", { count: "exact", head: true })
+ .eq("workspaceId", input.workspaceId)
+ .is("removedAt", null),
+ ctx.postgrest.client
+ .from("Notification")
+ .select("id", { count: "exact", head: true })
+ .eq("type", "workspaceInvite")
+ .eq("status", "pending")
+ .filter("payload->>workspaceId", "eq", input.workspaceId),
+ ]);
+
+ if (membersResult.error) {
+ throw membersResult.error;
+ }
+ if (pendingResult.error) {
+ throw pendingResult.error;
+ }
+
+ const currentCount =
+ (membersResult.count ?? 0) + (pendingResult.count ?? 0);
+ if (currentCount >= maxSeatsPerWorkspace) {
+ throw new Error(
+ `This workspace has reached its seat limit of ${maxSeatsPerWorkspace}. Remove a member or upgrade your plan to invite more.`
+ );
+ }
+ }
+
+ const { notificationId } = await workspaceApi.addMember(input, ctx);
+
+ // Charge the seat at invite time (Figma model).
+ // Soft-fail: the invite is already created, billing is best-effort.
+ await syncOwnerSeats(input.workspaceId, ctx).catch((error) => {
+ console.error(
+ "[payment-worker] Failed to bill seat on invite:",
+ error
+ );
+ });
+
+ return { success: true as const, notificationId };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ updateRole: procedure
+ .input(
+ z.object({
+ workspaceId: z.string(),
+ memberUserId: z.string(),
+ relation: Relation,
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ if (ctx.planFeatures.maxWorkspaces <= 1) {
+ throw new Error(
+ "Upgrade your plan to manage workspace member roles."
+ );
+ }
+ await workspaceApi.updateRole(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ removeMember: procedure
+ .input(z.object({ workspaceId: z.string(), memberUserId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await workspaceApi.removeMember(input, ctx);
+
+ // Release the seat immediately on removal.
+ await syncOwnerSeats(input.workspaceId, ctx).catch((error) => {
+ console.error(
+ "[payment-worker] Failed to release seat on member removal:",
+ error
+ );
+ });
+
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ listMembers: procedure
+ .input(z.object({ workspaceId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ try {
+ const members = await workspaceApi.listMembers(input, ctx);
+ return { success: true as const, data: members };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ moveProject: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ targetWorkspaceId: z.string(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const targetWorkspace = await ctx.postgrest.client
+ .from("Workspace")
+ .select("userId")
+ .eq("id", input.targetWorkspaceId)
+ .eq("isDeleted", false)
+ .maybeSingle();
+
+ if (targetWorkspace.error) {
+ throw targetWorkspace.error;
+ }
+
+ if (targetWorkspace.data === null) {
+ throw new Error("Target workspace not found");
+ }
+
+ const ownerPlan = await ctx.getOwnerPlanFeatures(
+ targetWorkspace.data.userId
+ );
+
+ if (ownerPlan.maxWorkspaces <= 1) {
+ throw new Error(
+ "Upgrade your plan to move projects between workspaces."
+ );
+ }
+ await workspaceApi.moveProject(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ transferProject: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ recipientEmail: z.string().email(),
+ targetWorkspaceId: z.string().optional(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await workspaceApi.transferProject(input, ctx);
+ return { success: true as const };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+
+ findSharedWorkspacesByOwnerEmail: procedure
+ .input(z.object({ email: z.string().email() }))
+ .query(async ({ input, ctx }) => {
+ try {
+ const workspaces = await workspaceApi.findSharedWorkspacesByOwnerEmail(
+ input,
+ ctx
+ );
+ return { success: true as const, data: workspaces };
+ } catch (error) {
+ return createErrorResponse(error);
+ }
+ }),
+});
+
+export type WorkspaceRouter = typeof workspaceRouter;
diff --git a/apps/builder/app/shared/notifications/seat-suspended.ts b/apps/builder/app/shared/notifications/seat-suspended.ts
index 88fe670667..7ee66dec02 100644
--- a/apps/builder/app/shared/notifications/seat-suspended.ts
+++ b/apps/builder/app/shared/notifications/seat-suspended.ts
@@ -1,4 +1,4 @@
export const SEAT_SUSPENDED_TOAST_ID = "seat-suspended";
-export const SEAT_SUSPENDED_MESSAGE =
- "Your editing access to this workspace has been paused because the owner's plan doesn't include enough seats. Please reach out to the workspace owner to upgrade their plan or add more seats.";
+export const getSeatSuspendedMessage = (workspaceName: string) =>
+ `Your editing access to "${workspaceName}" has been paused because the owner's plan doesn't include enough seats. Please reach out to the workspace owner to upgrade their plan or add more seats.`;
diff --git a/apps/builder/app/shared/notifications/subscription.tsx b/apps/builder/app/shared/notifications/subscription.tsx
index 5d0094b30b..4e4806884d 100644
--- a/apps/builder/app/shared/notifications/subscription.tsx
+++ b/apps/builder/app/shared/notifications/subscription.tsx
@@ -15,7 +15,7 @@ import { toast, Link } from "@webstudio-is/design-system";
import { showBrowserNotification } from "./browser-notification";
import {
SEAT_SUSPENDED_TOAST_ID,
- SEAT_SUSPENDED_MESSAGE,
+ getSeatSuspendedMessage,
} from "./seat-suspended";
import { publicStaticEnv } from "~/env/env.static";
@@ -84,9 +84,9 @@ export const startSubscription = () => {
// Bump the counter so React listeners know to revalidate.
$shouldRevalidateProjects.set($shouldRevalidateProjects.get() + 1);
});
- manager.subscribe("seatSuspended", (suspended) => {
- if (suspended) {
- toast.error(SEAT_SUSPENDED_MESSAGE, {
+ manager.subscribe("seatSuspended", (seatSuspended) => {
+ if (seatSuspended !== false) {
+ toast.error(getSeatSuspendedMessage(seatSuspended), {
id: SEAT_SUSPENDED_TOAST_ID,
duration: Number.POSITIVE_INFINITY,
});
diff --git a/apps/builder/app/shared/permissions.test.ts b/apps/builder/app/shared/permissions.test.ts
index 28514561bc..66b375547e 100644
--- a/apps/builder/app/shared/permissions.test.ts
+++ b/apps/builder/app/shared/permissions.test.ts
@@ -30,6 +30,8 @@ const proPlan = {
maxWorkspaces: 0,
maxProjectsAllowedPerUser: 100,
maxAssetsPerProject: 500,
+ minSeats: 0,
+ maxSeatsPerWorkspace: 0,
};
const freePlan = {
@@ -45,6 +47,8 @@ const freePlan = {
maxWorkspaces: 0,
maxProjectsAllowedPerUser: 2,
maxAssetsPerProject: 50,
+ minSeats: 0,
+ maxSeatsPerWorkspace: 0,
};
describe("getPermissions", () => {
diff --git a/apps/builder/app/shared/polly/topic-resolvers.server.ts b/apps/builder/app/shared/polly/topic-resolvers.server.ts
index 9635401d90..e0d99741c6 100644
--- a/apps/builder/app/shared/polly/topic-resolvers.server.ts
+++ b/apps/builder/app/shared/polly/topic-resolvers.server.ts
@@ -31,7 +31,7 @@ const resolvers: TopicResolvers = {
// Find all workspaces where the user is a non-owner active member.
const memberships = await ctx.postgrest.client
.from("WorkspaceMember")
- .select("workspaceId, workspace:Workspace!inner(userId)")
+ .select("workspaceId, workspace:Workspace!inner(userId, name)")
.eq("userId", userId)
.is("removedAt", null);
@@ -41,7 +41,9 @@ const resolvers: TopicResolvers = {
// Filter out workspaces owned by the user (shouldn't be any, but be safe).
const sharedWorkspaces = memberships.data.filter(
- (m) => (m.workspace as unknown as { userId: string }).userId !== userId
+ (m) =>
+ (m.workspace as unknown as { userId: string; name: string }).userId !==
+ userId
);
if (sharedWorkspaces.length === 0) {
@@ -55,7 +57,8 @@ const resolvers: TopicResolvers = {
const features = planResult.planFeatures;
if (features.maxWorkspaces <= 1) {
- return true;
+ return (m.workspace as unknown as { userId: string; name: string })
+ .name;
}
}
diff --git a/apps/builder/app/shared/polly/types.ts b/apps/builder/app/shared/polly/types.ts
index 8a6ba136d3..b922d5b741 100644
--- a/apps/builder/app/shared/polly/types.ts
+++ b/apps/builder/app/shared/polly/types.ts
@@ -33,8 +33,8 @@ export type Notifications = Awaited<ReturnType<typeof notification.list>>;
export type TopicRegistry = {
notifications: Notifications;
projectCount: number;
- /** True when the current user's seat in a shared workspace is suspended. */
- seatSuspended: boolean;
+ /** Workspace name when the current user's seat in a shared workspace is suspended, false otherwise. */
+ seatSuspended: string | false;
/** The builder's deployed version string (GITHUB_SHA or "local"). */
builderVersion: string;
};
diff --git a/packages/project/src/db/workspace.ts b/packages/project/src/db/workspace.ts
index 0e81af43e7..e3f9d8c3ea 100644
--- a/packages/project/src/db/workspace.ts
+++ b/packages/project/src/db/workspace.ts
@@ -8,6 +8,7 @@ import { defaultRole, type Role } from "@webstudio-is/trpc-interface/authorize";
import {
type WorkspaceInvitePayload,
type ProjectTransferPayload,
+ NOTIFICATION_TTL_MS,
} from "../shared/notification-schema";
import { create as createNotification } from "./notification";
@@ -287,8 +288,10 @@ const assertOwner = async (
};
/**
- * Count all current members (non-removed) across all non-deleted workspaces owned by userId.
- * The owner is NOT counted — this returns only invited member records.
+ * Count all current members (non-removed) plus pending invites across all
+ * non-deleted workspaces owned by userId.
+ * The owner is NOT counted.
+ * Pending invites are included because seats are billed at invite time.
*/
export const countAllMembers = async (
userId: string,
@@ -310,17 +313,37 @@ export const countAllMembers = async (
const workspaceIds = workspaces.data.map((w) => w.id);
- const result = await context.postgrest.client
- .from("WorkspaceMember")
- .select("userId", { count: "exact", head: true })
- .in("workspaceId", workspaceIds)
- .is("removedAt", null);
-
- if (result.error) {
- throw result.error;
- }
-
- return result.count ?? 0;
+ const [membersResult, pendingResult] = await Promise.all([
+ context.postgrest.client
+ .from("WorkspaceMember")
+ .select("userId", { count: "exact", head: true })
+ .in("workspaceId", workspaceIds)
+ .is("removedAt", null),
+ context.postgrest.client
+ .from("Notification")
+ .select("id", { count: "exact", head: true })
+ .eq("type", "workspaceInvite")
+ .eq("senderId", userId)
+ .eq("status", "pending")
+ .gte(
+ "createdAt",
+ new Date(Date.now() - NOTIFICATION_TTL_MS).toISOString()
+ ),
+ ]);
+
+ if (membersResult.error) {
+ throw membersResult.error;
+ }
+ if (pendingResult.error) {
+ throw pendingResult.error;
+ }
+
+ // Avoid double-counting: a pending invite recipient who is also already
+ // a member would be in both sets. This is theoretically impossible
+ // (addMember guards against it) but we subtract to be safe by using the
+ // total of accepted members + non-accepted pending invites.
+ // Simple approximation: accepted + pending counts (small overlap risk is acceptable).
+ return (membersResult.count ?? 0) + (pendingResult.count ?? 0);
};
export const addMember = async (
@@ -518,10 +541,41 @@ export const listMembers = async (
throw members.error;
}
- // Fetch user info for all members plus the owner
+ // Fetch pending workspace invite notifications for this workspace.
+ // Only visible to the owner (already verified above).
+ const pendingInvites =
+ workspace.data.userId === userId
+ ? await context.postgrest.client
+ .from("Notification")
+ .select("id, recipientId, payload, createdAt")
+ .eq("type", "workspaceInvite")
+ .eq("senderId", workspace.data.userId)
+ .eq("status", "pending")
+ .gte(
+ "createdAt",
+ new Date(Date.now() - NOTIFICATION_TTL_MS).toISOString()
+ )
+ .order("createdAt", { ascending: false })
+ : { data: [], error: null };
+
+ if (pendingInvites.error) {
+ throw pendingInvites.error;
+ }
+
+ // Filter to only invites for this specific workspace.
+ const acceptedUserIds = new Set(members.data.map((m) => m.userId));
+ const pendingForWorkspace = pendingInvites.data.filter((n) => {
+ const payload = n.payload as unknown as Partial<WorkspaceInvitePayload>;
+ return (
+ payload.workspaceId === workspaceId && !acceptedUserIds.has(n.recipientId)
+ );
+ });
+
+ // Fetch user info for members, owner, and pending invite recipients.
const allUserIds = [
workspace.data.userId,
...members.data.map((m) => m.userId),
+ ...pendingForWorkspace.map((n) => n.recipientId),
];
const uniqueUserIds = [...new Set(allUserIds)];
@@ -551,6 +605,16 @@ export const listMembers = async (
email: usersById.get(m.userId)?.email ?? "",
username: usersById.get(m.userId)?.username ?? "",
})),
+ pendingInvites: pendingForWorkspace.map((n) => {
+ const payload = n.payload as unknown as WorkspaceInvitePayload;
+ return {
+ notificationId: n.id,
+ recipientId: n.recipientId,
+ relation: payload.relation,
+ createdAt: n.createdAt,
+ email: usersById.get(n.recipientId)?.email ?? "",
+ };
+ }),
};
};
diff --git a/packages/trpc-interface/src/shared/plan-features.ts b/packages/trpc-interface/src/shared/plan-features.ts
index 4098cb9635..3206280f23 100644
--- a/packages/trpc-interface/src/shared/plan-features.ts
+++ b/packages/trpc-interface/src/shared/plan-features.ts
@@ -18,6 +18,8 @@ export const PlanFeaturesSchema = z.object({
maxWorkspaces: z.number().nonnegative(),
maxProjectsAllowedPerUser: z.number().nonnegative(),
maxAssetsPerProject: z.number().nonnegative(),
+ minSeats: z.number().nonnegative(),
+ maxSeatsPerWorkspace: z.number().nonnegative(),
});
export type PlanFeatures = z.infer<typeof PlanFeaturesSchema>;
@@ -43,6 +45,8 @@ export const defaultPlanFeatures: PlanFeatures = {
maxWorkspaces: 1,
maxProjectsAllowedPerUser: 2,
maxAssetsPerProject: 50,
+ minSeats: 0,
+ maxSeatsPerWorkspace: 0,
};
/** All user purchases (subscriptions and LTDs). subscriptionId present only for recurring subscriptions */