Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Shareable link limits (#2138)
Richie McIlroyaa10436a3b44
diff --git a/apps/web/app/(org)/dashboard/Contexts.tsx b/apps/web/app/(org)/dashboard/Contexts.tsxindex 40f5ac3b0..fe9cfc25f 100644--- a/apps/web/app/(org)/dashboard/Contexts.tsx+++ b/apps/web/app/(org)/dashboard/Contexts.tsx@@ -34,6 +34,7 @@ export function DashboardContexts({initialTheme,initialSidebarCollapsed,referClicked,+ shareableLinkUsage,}: {children: React.ReactNode;organizationData: SharedContext["organizationData"];@@ -46,6 +47,7 @@ export function DashboardContexts({initialTheme: ITheme;initialSidebarCollapsed: boolean;referClicked: boolean;+ shareableLinkUsage: SharedContext["shareableLinkUsage"];}) {const user = useCurrentUser();if (!user) redirect("/login");@@ -164,6 +166,7 @@ export function DashboardContexts({isDeveloperSection,developerApps,setDeveloperApps,+ shareableLinkUsage,}}>{children}diff --git a/apps/web/app/(org)/dashboard/DashboardContext.ts b/apps/web/app/(org)/dashboard/DashboardContext.tsindex b4c0e6e7a..489f5938c 100644--- a/apps/web/app/(org)/dashboard/DashboardContext.ts+++ b/apps/web/app/(org)/dashboard/DashboardContext.ts@@ -40,6 +40,7 @@ export type SharedContext = {isDeveloperSection: boolean;developerApps: DeveloperApp[] | null;setDeveloperApps: (apps: DeveloperApp[] | null) => void;+ shareableLinkUsage: { used: number; limit: number } | null;};export type ITheme = "light" | "dark";diff --git a/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx b/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsxindex 5da3eb1e2..e702bb341 100644--- a/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx@@ -240,7 +240,7 @@ export function AnalyticsDashboard() {</h1></div><p className="mt-1 text-lg text-center text-gray-11">- You can cancel anytime. Early adopter pricing locked in.+ You can cancel anytime.</p><div className="flex flex-col items-center mt-3 mb-4 w-full">diff --git a/apps/web/app/(org)/dashboard/layout.tsx b/apps/web/app/(org)/dashboard/layout.tsxindex dde0a568b..bd9ceb665 100644--- a/apps/web/app/(org)/dashboard/layout.tsx+++ b/apps/web/app/(org)/dashboard/layout.tsx@@ -1,12 +1,14 @@import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";import { organizationInvites } from "@cap/database/schema";+import { userIsPro } from "@cap/utils";import { and, eq } from "drizzle-orm";import { cookies } from "next/headers";import { redirect } from "next/navigation";import { AuthContextProvider } from "@/app/Layout/AuthContext";import { resolveCurrentUser } from "@/app/Layout/current-user";import { runPromise } from "@/lib/server";+import { getShareableLinkUsage } from "@/lib/shareable-link-quota";import DashboardInner from "./_components/DashboardInner";import { DashboardPasteImport } from "./_components/DashboardPasteImport";import MobileTab from "./_components/MobileTab";@@ -78,6 +80,14 @@ export default async function DashboardLayout({userPreferences = null;}+ // Fail-open: the meter is informational and must never take the shell down.+ const shareableLinkUsage = userIsPro(user)+ ? null+ : await getShareableLinkUsage(user.id).catch((error) => {+ console.error("Failed to load shareable link usage", error);+ return null;+ });+let activeOrganization = organizationSelect.find((organization) =>organization.organization.id === user.activeOrganizationId,@@ -105,6 +115,7 @@ export default async function DashboardLayout({anyNewNotifications={anyNewNotifications}userPreferences={userPreferences}referClicked={referClicked === "true"}+ shareableLinkUsage={shareableLinkUsage}><DashboardPasteImport /><div className="bg-gray-2 dashboard-grid">diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomainDialog/CustomDomainDialog.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomainDialog/CustomDomainDialog.tsxindex 0bd00bb33..cc29a590e 100644--- a/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomainDialog/CustomDomainDialog.tsx+++ b/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomainDialog/CustomDomainDialog.tsx@@ -466,7 +466,7 @@ const CustomDomainDialog = ({handleClose();}}>- Upgrade To Cap Pro+ Upgrade to Cap Pro</Button>))}</DialogFooter>diff --git a/apps/web/app/api/settings/billing/usage/route.ts b/apps/web/app/api/settings/billing/usage/route.tsindex b402b4f03..3866373eb 100644--- a/apps/web/app/api/settings/billing/usage/route.ts+++ b/apps/web/app/api/settings/billing/usage/route.ts@@ -1,8 +1,6 @@-import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";-import { videos } from "@cap/database/schema";import { userIsPro } from "@cap/utils";-import { count, eq } from "drizzle-orm";+import { getShareableLinkUsage } from "@/lib/shareable-link-quota";export const dynamic = "force-dynamic";@@ -13,35 +11,25 @@ export async function GET() {return Response.json({ auth: false }, { status: 401 });}- const numberOfVideos = await db()- .select({ count: count() })- .from(videos)- .where(eq(videos.ownerId, user.id));-- if (!numberOfVideos[0]) {- return Response.json(- { error: "Could not fetch video count" },- { status: 500 },- );- }+ const usage = await getShareableLinkUsage(user.id);if (userIsPro(user)) {return Response.json({subscription: true,videoLimit: 0,- videoCount: numberOfVideos[0].count,- },- { status: 200 },- );- } else {- return Response.json(- {- subscription: false,- videoLimit: 25,- videoCount: numberOfVideos[0].count,+ videoCount: usage.used,},{ status: 200 },);}++ return Response.json(+ {+ subscription: false,+ videoLimit: usage.limit,+ videoCount: usage.used,+ },+ { status: 200 },+ );}diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsxindex 28eb58172..39370252f 100644--- a/apps/web/app/embed/[videoId]/page.tsx+++ b/apps/web/app/embed/[videoId]/page.tsx@@ -12,13 +12,15 @@ import {} from "@cap/database/schema";import type { VideoMetadata } from "@cap/database/types";import { buildEnv } from "@cap/env";+import { Logo } from "@cap/ui";+import { userIsPro } from "@cap/utils";import {provideOptionalAuth,resolveEffectiveVideoRules,Videos,VideosPolicy,} from "@cap/web-backend";-import { type Organisation, Policy, type Video } from "@cap/web-domain";+import { type Organisation, Policy, Video } from "@cap/web-domain";import { and, eq, isNull, sql } from "drizzle-orm";import { Effect, Option } from "effect";import type { Metadata } from "next";@@ -26,6 +28,7 @@ import Link from "next/link";import { notFound } from "next/navigation";import * as EffectRuntime from "@/lib/server";import { buildShareVideoMetadata } from "@/lib/share-video-metadata";+import { isVideoOverShareableLinkLimit } from "@/lib/shareable-link-quota";import { transcribeVideo } from "@/lib/transcribe";import { isAiGenerationEnabled } from "@/utils/flags";import { EmbedVideo } from "./_components/EmbedVideo";@@ -225,6 +228,7 @@ async function EmbedContent({});let aiGenerationEnabled = false;+ let ownerIsProUser = false;const videoOwnerQuery = await db().select({email: users.email,@@ -238,6 +242,7 @@ async function EmbedContent({if (videoOwnerQuery.length > 0 && videoOwnerQuery[0]) {const videoOwner = videoOwnerQuery[0];aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);+ ownerIsProUser = userIsPro(videoOwner);}if (@@ -275,6 +280,45 @@ async function EmbedContent({);}+ // Same quota gate as the share page, so embeds are not a loophole around+ // it. Fail-open: a broken count must never take the embed down.+ const overShareLimit =+ !ownerIsProUser &&+ (await isVideoOverShareableLinkLimit({+ id: video.id,+ ownerId: video.ownerId,+ createdAt: video.createdAt,+ isScreenshot: video.isScreenshot,+ }).catch((error) => {+ console.error(+ `[EmbedVideoPage] Shareable link quota check failed for ${video.id}:`,+ error,+ );+ return false;+ }));++ if (overShareLimit) {+ return (+ <div className="flex flex-col gap-3 justify-center items-center px-6 min-h-screen text-center bg-black">+ <Logo className="w-auto h-7" white />+ <h1 className="text-lg font-semibold text-white">+ This video is over its free limit+ </h1>+ <p className="max-w-sm text-sm leading-relaxed text-white/60">+ {`The owner of this video has used all ${Video.FREE_PLAN_SHAREABLE_LINKS_PER_MONTH} shareable links included with Cap's free plan this month. As soon as they upgrade to Cap Pro, this video will be instantly viewable.`}+ </p>+ <a+ href={`${buildEnv.NEXT_PUBLIC_WEB_URL}/s/${video.id}`}+ target="_blank"+ rel="noreferrer"+ className="mt-2 rounded-full border border-gray-5 bg-gray-3 px-5 py-2 text-sm font-medium text-gray-12 transition-colors hover:bg-gray-6"+ >+ Open on Cap+ </a>+ </div>+ );+ }+const commentsQuery = await db().select({id: comments.id,diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex 639eb159b..eeca8be43 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -598,8 +598,12 @@ export const Share = ({const [selectedView, setSelectedView] = useState<ShareView>(initialView);// Screenshots have no timeline to show, and a comments-disabled video has// nothing to branch — both stay on the classic layout even if someone- // hand-writes `?view=timeline`.- const timelineAvailable = !isScreenshot && !areCommentStampsDisabled;+ // hand-writes `?view=timeline`. Over-quota videos stay classic too: the+ // timeline deck's filmstrip would leak frames below the upgrade gate.+ const timelineAvailable =+ !isScreenshot &&+ !areCommentStampsDisabled &&+ data.ownerIsOverShareLimit !== true;// Where the timeline's filmstrip frames come from. Mirrors the source split// in `ShareVideo`: instant recordings have a result.mp4 a bare <video> can@@ -988,6 +992,7 @@ export const Share = ({isEditProcessing={isEditProcessing}recordingStopped={recordingStopped}defaultPlaybackSpeed={defaultPlaybackSpeed}+ viewerIsOwner={viewerId === data.owner.id}ref={playerRef}/>)}diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsxindex ab783c082..897c79f0b 100644--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx@@ -735,7 +735,7 @@ export const ShareHeader = ({size="sm"variant="blue">- Upgrade To Cap Pro+ Upgrade to Cap Pro</Button></div>)}diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsxindex cc20e2264..745ce641e 100644--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx@@ -28,6 +28,7 @@ import {PreparingVideoOverlay,RecordingInProgressOverlay,} from "./RecordingInProgress";+import { ShareableLinkLimitOverlay } from "./ShareableLinkLimitOverlay";import {shouldDeferPlaybackSource,shouldReloadPlaybackAfterUploadCompletes,@@ -96,6 +97,7 @@ export const ShareVideo = forwardRef<isEditProcessing: boolean;recordingStopped?: boolean;defaultPlaybackSpeed?: number;+ viewerIsOwner?: boolean;}>((@@ -115,6 +117,7 @@ export const ShareVideo = forwardRef<isEditProcessing,recordingStopped = false,defaultPlaybackSpeed,+ viewerIsOwner = false,},ref,) => {@@ -324,6 +327,7 @@ export const ShareVideo = forwardRef<const isMp4Source =data.source.type === "desktopMP4" || data.source.type === "webMP4";const isSegmentsSource = data.source.type === "desktopSegments";+ const isOverShareLimit = data.ownerIsOverShareLimit === true;const previousSegmentUploadProgressRef = useRef(segmentUploadProgress);const isActivelyRecording =isSegmentsSource &&@@ -541,6 +545,19 @@ export const ShareVideo = forwardRef<</div>) : isProcessingInProgress ? (<PreparingVideoOverlay className="h-full" />+ ) : isOverShareLimit ? (+ // Quota gate: the player is never mounted, so the video is not+ // fetched or playable until the owner upgrades (server recomputes+ // the flag on the next load). Recording/processing branches above+ // keep priority so in-flight uploads always finalize.+ <ShareableLinkLimitOverlay+ isOwner={viewerIsOwner}+ onUpgrade={openUpgradeModal}+ onUpgradeHover={() => {+ void importUpgradeModal();+ }}+ className="h-full"+ />) : isMp4Source ? (<CapVideoPlayervideoId={data.id}@@ -654,7 +671,7 @@ export const ShareVideo = forwardRef<)}</div>- {!data.owner.isPro && (+ {!data.owner.isPro && !isOverShareLimit && (<div className="absolute top-4 left-4 z-30"><buttontype="button"diff --git a/apps/web/app/s/[videoId]/_components/ShareableLinkLimitOverlay.tsx b/apps/web/app/s/[videoId]/_components/ShareableLinkLimitOverlay.tsxnew file mode 100644index 000000000..f8b44e27a--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/ShareableLinkLimitOverlay.tsx@@ -0,0 +1,84 @@+"use client";++import { buildEnv } from "@cap/env";+import { Button, Logo } from "@cap/ui";+import { Video } from "@cap/web-domain";+import clsx from "clsx";+import { BarChart3, Infinity as InfinityIcon, Share2 } from "lucide-react";++const LIMIT = Video.FREE_PLAN_SHAREABLE_LINKS_PER_MONTH;++const PRO_BENEFITS = [+ { icon: Share2, label: "Unlimited shareable links" },+ { icon: InfinityIcon, label: "No recording length limits" },+ { icon: BarChart3, label: "Analytics, Cap AI and password protection" },+];++export function ShareableLinkLimitOverlay({+ isOwner,+ onUpgrade,+ onUpgradeHover,+ className,+}: {+ isOwner: boolean;+ onUpgrade: () => void;+ onUpgradeHover?: () => void;+ className?: string;+}) {+ return (+ <div+ className={clsx(+ "flex overflow-y-auto flex-col justify-center items-center rounded-xl bg-black px-4 py-6",+ className,+ )}+ >+ <div className="flex flex-col items-center max-w-md text-center">+ <Logo className="w-auto h-6 sm:h-8" white />+ <h3 className="mt-4 text-lg font-semibold text-white sm:text-xl">+ {isOwner+ ? "You've run out of shareable links"+ : "This video is over its free limit"}+ </h3>+ <p className="mt-2 max-w-sm text-xs leading-relaxed sm:text-sm text-white/60">+ {isOwner+ ? `You've used all ${LIMIT} shareable links included with Cap's free plan this month. Upgrade to Cap Pro and this video becomes instantly viewable, along with everything else you record.`+ : `The owner of this video has used all ${LIMIT} shareable links included with Cap's free plan this month. As soon as they upgrade to Cap Pro, this video will be instantly viewable.`}+ </p>+ <div className="hidden flex-col gap-2 items-start mt-5 sm:flex">+ {PRO_BENEFITS.map(({ icon: Icon, label }) => (+ <div key={label} className="flex gap-2.5 items-center">+ <Icon className="size-4 shrink-0 text-blue-400" />+ <span className="text-sm text-white/80">{label}</span>+ </div>+ ))}+ </div>+ {isOwner ? (+ <Button+ variant="blue"+ size="sm"+ className="mt-6"+ onClick={onUpgrade}+ onPointerEnter={onUpgradeHover}+ >+ Upgrade to Cap Pro+ </Button>+ ) : (+ <Button+ variant="white"+ size="sm"+ className="mt-6"+ href={buildEnv.NEXT_PUBLIC_WEB_URL}+ target="_blank"+ >+ Record with Cap for free+ </Button>+ )}+ <p className="mt-3 text-xs text-white/40">+ {isOwner+ ? "Videos recorded in Studio mode are saved to your device, free and unlimited."+ : `Cap's free plan includes ${LIMIT} shareable links per month.`}+ </p>+ </div>+ </div>+ );+}diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex f021913bb..6bf3f6982 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -57,6 +57,7 @@ import { runPromise } from "@/lib/server";import { getSharePageBranding } from "@/lib/share-branding";import { buildShareVideoMetadata } from "@/lib/share-video-metadata";import { resolveShareWebUrl } from "@/lib/share-web-url";+import { isVideoOverShareableLinkLimit } from "@/lib/shareable-link-quota";import {isIframelyCrawlerUserAgent,isSocialCrawlerUserAgent,@@ -494,6 +495,24 @@ async function AuthorizedContent({const sharedSpacesPromise = getSharedSpacesForVideo(videoId);+ const ownerIsPro = userIsPro(video.owner);++ // Fail-open: a broken count must never take the share page down.+ const overShareLimitPromise = ownerIsPro+ ? Promise.resolve(false)+ : isVideoOverShareableLinkLimit({+ id: videoId,+ ownerId: video.owner.id,+ createdAt: video.createdAt,+ isScreenshot: video.isScreenshot,+ }).catch((error) => {+ console.error(+ `[ShareVideoPage] Shareable link quota check failed for ${videoId}:`,+ error,+ );+ return false;+ });+const aiGenerationEnabledPromise = db().select({email: users.email,@@ -737,6 +756,7 @@ async function AuthorizedContent({canManageSharePageBranding,canDownloadVideo,videoHasEdits,+ ownerIsOverShareLimit,] = await Promise.all([spacesDataPromise,sharedSpacesPromise,@@ -749,6 +769,7 @@ async function AuthorizedContent({canManageSharePageBrandingPromise,canDownloadVideoPromise,videoHasEditsPromise,+ overShareLimitPromise,]);const rules = resolveEffectiveVideoRules({@@ -799,10 +820,11 @@ async function AuthorizedContent({return {...video,hasActiveUpload,+ ownerIsOverShareLimit,owner: {id: video.owner.id,name: video.owner.name,- isPro: userIsPro(video.owner),+ isPro: ownerIsPro,image: video.owner.image? yield* imageUploads.resolveImageUrl(video.owner.image): null,diff --git a/apps/web/app/s/[videoId]/types.ts b/apps/web/app/s/[videoId]/types.tsindex e41583fb3..f013595ba 100644--- a/apps/web/app/s/[videoId]/types.ts+++ b/apps/web/app/s/[videoId]/types.ts@@ -19,6 +19,7 @@ export type VideoData = Omit<typeof videos.$inferSelect, "ownerId"> & {shareableLinkIconUrl?: ImageUpload.ImageUrl | null;hasActiveUpload?: boolean;activeUploadRawFileKey?: string | null;+ ownerIsOverShareLimit?: boolean;};export type VideoOwner = {diff --git a/apps/web/components/UpgradeModal.tsx b/apps/web/components/UpgradeModal.tsxindex 8fc24a248..ee2bd9801 100644--- a/apps/web/components/UpgradeModal.tsx+++ b/apps/web/components/UpgradeModal.tsx@@ -7,14 +7,17 @@ import { useMutation } from "@tanstack/react-query";import { useCurrency } from "hooks/useCurrency";import {BarChart3,+ Clock,+ Cloud,Database,Globe,Headphones,- Infinity,+ Infinity as InfinityIcon,+ Link2,Lock,+ Mic,Minus,Plus,- Share2,Shield,ShieldCheck,Sparkles,@@ -22,7 +25,7 @@ import {} from "lucide-react";import { AnimatePresence, motion } from "motion/react";import { useRouter } from "next/navigation";-import { memo, useState } from "react";+import { memo, useRef, useState } from "react";import { toast } from "sonner";import { useStripeContext } from "@/app/Layout/StripeContext";import { PRICING } from "@/data/pricing";@@ -63,6 +66,85 @@ const modalVariants = {},};+const ANNUAL_SAVINGS_PERCENT = Math.round(+ (1 - PRICING.pro.annualPerMonth / PRICING.pro.monthly) * 100,+);++const iconStyling = "text-blue-500 size-4";++const PRO_FEATURES = [+ {+ icon: <Link2 className={iconStyling} />,+ title: "Unlimited shareable links",+ description: "No monthly limit, every video is instantly shareable",+ },+ {+ icon: <Clock className={iconStyling} />,+ title: "Unlimited recording length",+ description: "The 5 minute free recording cap is removed",+ },+ {+ icon: <Cloud className={iconStyling} />,+ title: "Unlimited cloud storage",+ description: "Keep every recording, forever",+ },+ {+ icon: <Sparkles className={iconStyling} />,+ title: "Cap AI",+ description: "Automatic titles, summaries, chapters & more",+ },+ {+ icon: <Globe className={iconStyling} />,+ title: "Custom domain",+ description: "Share videos from your own domain",+ },+ {+ icon: <Lock className={iconStyling} />,+ title: "Password protected videos",+ description: "Control exactly who can watch",+ },+ {+ icon: <BarChart3 className={iconStyling} />,+ title: "Analytics",+ description: "Views, engagement and viewer insights",+ },+ {+ icon: <Video className={iconStyling} />,+ title: "Upload & import videos",+ description: "Upload existing files or import straight from Loom",+ },+ {+ icon: <Mic className={iconStyling} />,+ title: "Audio & video comments",+ description: "Viewers reply on the timeline with voice or camera",+ },+ {+ icon: <Database className={iconStyling} />,+ title: "Custom storage",+ description: "Connect your own Google Drive or S3 bucket",+ },+ {+ icon: <InfinityIcon className={iconStyling} />,+ title: "Unlimited views",+ description: "No limits on video views",+ },+ {+ icon: <Shield className={iconStyling} />,+ title: "Commercial license",+ description: "Desktop app commercial license included",+ },+ {+ icon: <ShieldCheck className={iconStyling} />,+ title: "SOC 2, ISO 27001 & HIPAA",+ description: "Independently audited security & compliance",+ },+ {+ icon: <Headphones className={iconStyling} />,+ title: "Priority support",+ description: "Get help when you need it",+ },+];+const UpgradeModalImpl = ({open,onOpenChange,@@ -72,85 +154,15 @@ const UpgradeModalImpl = ({}: UpgradeModalProps) => {const stripeCtx = useStripeContext();const { currency } = useCurrency();- const [isAnnual, setIsAnnual] = useState(true);+ const [isAnnual, setIsAnnual] = useState(false);const [proQuantity, setProQuantity] = useState(1);+ const upgradeButtonRef = useRef<HTMLButtonElement>(null);const { push } = useRouter();- const pricePerUser = isAnnual- ? PRICING.pro.annualPerMonth- : PRICING.pro.monthly;+ const pricePerUser = isAnnual ? PRICING.pro.yearlyTotal : PRICING.pro.monthly;const totalPrice = pricePerUser * proQuantity;const billingText = isAnnual ? "billed annually" : "billed monthly";- useRive({- src: "/rive/main.riv",- artboard: "cap-pro-modal",- animations: ["animation"],- layout: new Layout({- fit: Fit.Cover,- }),- autoplay: true,- });-- const iconStyling = "text-blue-500 size-[18px]";- const proFeatures = [- {- icon: <Globe className={iconStyling} />,- title: "Custom domain",- description: "Connect your own domain to Cap",- },- {- icon: <Share2 className={iconStyling} />,- title: "Unlimited sharing",- description: "Cloud storage & shareable links",- },- {- icon: <Sparkles className={iconStyling} />,- title: "Cap AI",- description: "Automatic video chapters, summaries & more",- },- {- icon: <Lock className={iconStyling} />,- title: "Password protected videos",- description: "Enhanced security for your content",- },- {- icon: <Database className={iconStyling} />,- title: "Custom storage",- description: "Connect your own Google Drive or S3 bucket",- },- {- icon: <Shield className={iconStyling} />,- title: "Commercial license",- description: "Commercial license for desktop app automatically included",- },- {- icon: <Video className={iconStyling} />,- title: "Upload videos",- description: "Upload custom videos directly to Cap",- },- {- icon: <Infinity className={iconStyling} />,- title: "Unlimited views",- description: "No limits on video views",- },- {- icon: <BarChart3 className={iconStyling} />,- title: "Analytics",- description: "Video viewing insights",- },- {- icon: <Headphones className={iconStyling} />,- title: "Priority support",- description: "Get help when you need it",- },- {- icon: <ShieldCheck className={iconStyling} />,- title: "SOC 2, ISO 27001 & HIPAA",- description: "Independently audited security & compliance",- },- ];-const proCheckoutMutation = useMutation({mutationFn: async () => {const planId = stripeCtx.plans[isAnnual ? "yearly" : "monthly"];@@ -180,11 +192,6 @@ const UpgradeModalImpl = ({onOpenChange(false);}- if (data.subscription === true) {- toast.success("You are already on the Cap Pro plan");- onOpenChange(false);- }-await onCheckout?.();if (data.url) {@@ -208,8 +215,30 @@ const UpgradeModalImpl = ({onInteractOutside={(event) => {if (!dismissible) event.preventDefault();}}+ // Land focus on the upgrade CTA so Space/Enter proceed natively+ // (Radix would otherwise focus the close button, where Space would+ // dismiss the dialog we just advertised a Space shortcut in).+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ upgradeButtonRef.current?.focus();+ }}+ onKeyDown={(event) => {+ if (event.code !== "Space") return;+ // Focused controls keep their native Space behavior (switch+ // toggle, stepper, close); the shortcut only fires from inert+ // targets so it never double-activates.+ const target = event.target as HTMLElement | null;+ if (+ target?.closest(+ "button, a, input, textarea, select, [role='switch'], [contenteditable]",+ )+ )+ return;+ event.preventDefault();+ if (!proCheckoutMutation.isPending) proCheckoutMutation.mutate();+ }}className={[- "sm:max-w-[1100px] w-[calc(100%-20px)] custom-scroll bg-gray-2 border border-gray-4 overflow-y-auto md:overflow-hidden max-h-[90vh] p-0",+ "sm:max-w-[1100px] w-[calc(100%-20px)] custom-scroll bg-gray-2 border border-gray-4 overflow-y-auto max-h-[90vh] p-0",dismissible ? "" : "[&>button:last-child]:hidden",].join(" ")}>@@ -223,17 +252,17 @@ const UpgradeModalImpl = ({exit="exit"><div className="flex relative flex-col flex-1 justify-between items-end self-stretch border-r-0 border-b md:border-b-0 md:border-r border-gray-4">- <div className="h-[275px] border-b border-gray-4 w-full overflow-hidden">+ <div className="h-36 md:h-[275px] border-b border-gray-4 w-full overflow-hidden"><ProRiveArt /></div>- <div className="flex relative flex-col flex-1 justify-center items-center py-6 w-full">+ <div className="flex relative flex-col flex-1 justify-center items-center px-4 py-6 w-full"><div className="flex flex-col items-center">- <h1 className="text-3xl font-medium text-gray-12">+ <h1 className="text-2xl font-medium sm:text-3xl text-gray-12">Upgrade to Cap Pro</h1></div>- <p className="mt-1 text-lg text-center text-gray-11">- You can cancel anytime. Early adopter pricing locked in.+ <p className="mt-1 text-base text-center sm:text-lg text-gray-11">+ You can cancel anytime.</p><div className="flex flex-col items-center mt-3 mb-4 w-full">@@ -262,13 +291,23 @@ const UpgradeModalImpl = ({</span></div>- <div className="flex flex-col gap-6 justify-evenly items-center mt-8 w-full max-w-md sm:gap-10 sm:flex-row">+ <div className="flex flex-col gap-6 justify-evenly items-center mt-6 w-full max-w-md sm:gap-8 sm:flex-row"><div className="flex gap-3 items-center"><span className="text-gray-12">Annual billing</span><Switchchecked={isAnnual}onCheckedChange={() => setIsAnnual(!isAnnual)}/>+ <span+ className={[+ "rounded-full px-2 py-0.5 text-[11px] font-semibold transition-colors",+ isAnnual+ ? "bg-blue-500/10 text-blue-500"+ : "bg-gray-4 text-gray-10",+ ].join(" ")}+ >+ Save {ANNUAL_SAVINGS_PERCENT}%+ </span></div><div className="flex items-center">@@ -301,23 +340,35 @@ const UpgradeModalImpl = ({</div><Button+ ref={upgradeButtonRef}variant="blue"type="button"+ aria-keyshortcuts="Space"onClick={(e) => {e.preventDefault();proCheckoutMutation.mutate();}}- className="mt-5 w-full max-w-sm h-14 text-lg"+ className="flex-col gap-1.5 mt-5 w-full max-w-sm h-16 text-base"disabled={proCheckoutMutation.isPending}>- {proCheckoutMutation.isPending- ? "Loading..."- : "Upgrade to Cap Pro"}+ {proCheckoutMutation.isPending ? (+ "Loading..."+ ) : (+ <>+ <span className="leading-none">Upgrade to Cap Pro</span>+ <span className="hidden gap-1 items-center sm:flex text-[10px] font-normal text-white/70">+ or,+ <kbd className="flex justify-center items-center px-1 rounded border bg-white/15 border-white/25 h-[14px] text-[9px] font-medium text-white/80">+ spacebar+ </kbd>+ </span>+ </>+ )}</Button>{dismissible && (<buttontype="button"- className="mt-2 w-full max-w-sm h-14 text-base rounded-xl hover:underline text-gray-11 hover:text-gray-12"+ className="mt-2 w-full max-w-sm h-10 text-base rounded-xl hover:underline text-gray-11 hover:text-gray-12"onClick={() => onOpenChange(false)}>Skip@@ -326,22 +377,21 @@ const UpgradeModalImpl = ({</div></div>- <div className="flex flex-1 justify-center items-center self-stretch p-8 bg-transparent md:bg-gray-3">- <div className="grid grid-cols-1 gap-8 md:grid-cols-2">- {proFeatures.map((feature, index) => (- <div- key={index.toString()}- className="flex flex-col justify-center items-center"- >- <div className="mb-3.5 bg-gray-5 rounded-full size-10 flex items-center justify-center">+ <div className="flex flex-1 justify-center items-center self-stretch p-5 bg-transparent sm:p-6 md:p-8 md:bg-gray-3">+ <div className="grid grid-cols-1 gap-x-8 gap-y-4 w-full sm:grid-cols-2 md:gap-y-5">+ {PRO_FEATURES.map((feature) => (+ <div key={feature.title} className="flex gap-3 items-start">+ <div className="flex justify-center items-center rounded-lg bg-gray-5 shrink-0 size-8">{feature.icon}</div>- <h3 className="text-base font-medium text-center text-gray-12">- {feature.title}- </h3>- <p className="text-sm text-center text-gray-11">- {feature.description}- </p>+ <div className="min-w-0">+ <h3 className="text-sm font-medium text-gray-12">+ {feature.title}+ </h3>+ <p className="mt-0.5 text-xs leading-relaxed text-gray-11">+ {feature.description}+ </p>+ </div></div>))}</div>diff --git a/apps/web/components/UsageButton.tsx b/apps/web/components/UsageButton.tsxindex 3cfc3436b..c2ea482f4 100644--- a/apps/web/components/UsageButton.tsx+++ b/apps/web/components/UsageButton.tsx@@ -1,12 +1,13 @@-import { Button } from "@cap/ui";-import { faCheck } from "@fortawesome/free-solid-svg-icons";+import { Button, Popover, PopoverContent, PopoverTrigger } from "@cap/ui";+import { faCheck, faCircleInfo } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import clsx from "clsx";+import { HardDrive, Link2, Sparkles } from "lucide-react";+import { motion } from "motion/react";import Link from "next/link";-import { memo } from "react";+import { memo, useEffect, useRef, useState } from "react";import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";import { Tooltip } from "@/components/Tooltip";-import { Fit, Layout, useRive } from "@/lib/rive";export const UsageButton = memo(({@@ -16,104 +17,272 @@ export const UsageButton = memo(subscribed: boolean;toggleMobileNav?: () => void;}) => {- const { sidebarCollapsed } = useDashboardContext();+ const { sidebarCollapsed, shareableLinkUsage, setUpgradeModalOpen } =+ useDashboardContext();+if (subscribed) {- return (- <Tooltip position="right" content="Cap Pro">- <Link- className="flex justify-center mx-auto w-full"- href="/dashboard/settings/workspace"+ if (sidebarCollapsed) {+ return (+ <Tooltip+ position="right"+ content="Cap Pro. Unlimited shareable links.">- <Button- size="lg"- className={clsx(- "overflow-hidden truncate",- sidebarCollapsed- ? "p-0 w-10 h-10 rounded-full min-w-[unset] max-w-10"- : "w-full",- )}- variant="blue"+ <Link+ className="flex justify-center mx-auto w-full"+ href="/dashboard/settings/workspace">+ <Button+ size="lg"+ className="overflow-hidden p-0 w-10 h-10 rounded-full truncate min-w-[unset] max-w-10"+ variant="blue"+ >+ <FontAwesomeIcon className="text-white size-4" icon={faCheck} />+ </Button>+ </Link>+ </Tooltip>+ );+ }++ return (+ <div className="p-3 w-full rounded-xl bg-gray-3">+ <div className="flex justify-between items-center">+ <span className="text-xs font-medium text-gray-11">+ Shareable links+ </span>+ <span className="text-xs font-semibold text-gray-12">+ Unlimited+ </span>+ </div>+ <Link className="block mt-3" href="/dashboard/settings/workspace">+ <Button size="sm" variant="blue" className="w-full"><FontAwesomeIcon- className={clsx(- "text-white size-4",- sidebarCollapsed ? "mr-0" : "mr-1",- )}+ className="mr-1 text-white size-4"icon={faCheck}/>- {sidebarCollapsed ? null : <p className="text-white">Cap Pro</p>}+ <p className="text-white">Cap Pro</p></Button></Link>+ </div>+ );+ }++ const openUpgrade = () => {+ setUpgradeModalOpen(true);+ toggleMobileNav?.();+ };++ if (sidebarCollapsed) {+ return (+ <Tooltip+ position="right"+ content={+ shareableLinkUsage+ ? `Upgrade to Pro. ${shareableLinkUsage.used}/${shareableLinkUsage.limit} shareable links used this month.`+ : "Upgrade to Pro"+ }+ >+ <Button+ variant="blue"+ onClick={openUpgrade}+ aria-label="Upgrade to Pro"+ className="p-0 mx-auto w-10 h-10 rounded-full min-w-[unset] max-w-10"+ >+ <Sparkles className="text-white size-4" />+ </Button></Tooltip>);}+ if (!shareableLinkUsage) {+ return (+ <Button variant="blue" onClick={openUpgrade} className="w-full">+ Upgrade to Pro+ </Button>+ );+ }+return (- <Tooltip- disable={!sidebarCollapsed}- position="right"- content="Upgrade to Pro"- >- <ProRiveButton toggleMobileNav={toggleMobileNav} />- </Tooltip>+ <div className="p-3 w-full rounded-xl bg-gray-3">+ <ShareableLinksMeter+ used={shareableLinkUsage.used}+ limit={shareableLinkUsage.limit}+ onShowBenefits={openUpgrade}+ />+ <Button+ variant="blue"+ size="sm"+ onClick={openUpgrade}+ className="mt-3 w-full"+ >+ Upgrade to Pro+ </Button>+ <button+ type="button"+ onClick={openUpgrade}+ className="mt-2 w-full text-[11px] text-center text-gray-10 transition-colors hover:text-gray-12"+ >+ What's included in Pro?+ </button>+ </div>);},);-const ProRiveButton = memo(- ({ toggleMobileNav }: { toggleMobileNav?: () => void }) => {- const { setUpgradeModalOpen, sidebarCollapsed } = useDashboardContext();+const ShareableLinksMeter = ({+ used,+ limit,+ onShowBenefits,+}: {+ used: number;+ limit: number;+ onShowBenefits?: () => void;+}) => {+ const atLimit = used >= limit;+ const [infoOpen, setInfoOpen] = useState(false);+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);- const { rive, RiveComponent: ProRive } = useRive({- src: "/rive/pricing.riv",- artboard: "pro",- animations: "idle",- autoplay: false,- layout: new Layout({- fit: Fit.Cover,- }),- });+ const openInfo = () => {+ if (closeTimer.current) clearTimeout(closeTimer.current);+ setInfoOpen(true);+ };+ // Grace delay so the pointer can cross the gap between the trigger and+ // the panel without the panel closing underneath it.+ const scheduleInfoClose = () => {+ if (closeTimer.current) clearTimeout(closeTimer.current);+ closeTimer.current = setTimeout(() => setInfoOpen(false), 150);+ };+ useEffect(+ () => () => {+ if (closeTimer.current) clearTimeout(closeTimer.current);+ },+ [],+ );- return (- <Button- variant="blue"- size="lg"- onMouseEnter={() => {- if (rive) {- rive.stop();- rive.play("items-coming-out");- }- }}- onMouseLeave={() => {- if (rive) {- rive.stop();- rive.play("items-coming-in");- }- }}- className={clsx(- "flex overflow-visible relative gap-3 justify-evenly items-center cursor-pointer",- "mx-auto",- sidebarCollapsed ? "py-0 h-10 min-w-[unset]" : "py-3 w-full h-fit",- )}- onClick={() => {- setUpgradeModalOpen(true);- toggleMobileNav?.();- }}- >- <ProRive+ return (+ <div>+ <div className="flex justify-between items-center">+ <div className="flex gap-1.5 items-center">+ <span className="text-xs font-medium text-gray-11">+ Shareable links+ </span>+ <Popover open={infoOpen} onOpenChange={setInfoOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label="About video limits"+ onMouseEnter={openInfo}+ onMouseLeave={scheduleInfoClose}+ onFocus={openInfo}+ onBlur={scheduleInfoClose}+ // preventDefault stops Radix's toggle-on-click, so a tap+ // (which fires mouseenter then click) opens instead of+ // opening and immediately closing again.+ onClick={(event) => {+ event.preventDefault();+ openInfo();+ }}+ className="flex items-center text-gray-9 transition-colors hover:text-gray-11 data-[state=open]:text-gray-11"+ >+ <FontAwesomeIcon icon={faCircleInfo} className="size-3" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ side="top"+ align="start"+ sideOffset={8}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onMouseEnter={openInfo}+ onMouseLeave={scheduleInfoClose}+ className="z-[60] p-0 w-72 border shadow-lg bg-gray-1 border-gray-4"+ >+ <div className="px-4 py-3 border-b border-gray-4">+ <p className="text-[13px] font-medium text-gray-12">+ Video limits+ </p>+ <p className="mt-0.5 text-xs text-gray-10">+ What counts toward your free plan+ </p>+ </div>+ <div className="flex flex-col gap-3.5 px-4 py-3.5">+ <div className="flex gap-3 items-start">+ <div className="flex justify-center items-center mt-0.5 rounded-md bg-gray-3 shrink-0 size-7">+ <Link2 className="size-3.5 text-gray-11" />+ </div>+ <div>+ <p className="text-xs font-medium text-gray-12">+ Shareable links+ </p>+ <p className="mt-0.5 text-xs leading-relaxed text-gray-10">+ {limit} per month on the free plan. Resets on the 1st of+ each month.+ </p>+ </div>+ </div>+ <div className="flex gap-3 items-start">+ <div className="flex justify-center items-center mt-0.5 rounded-md bg-gray-3 shrink-0 size-7">+ <HardDrive className="size-3.5 text-gray-11" />+ </div>+ <div>+ <p className="text-xs font-medium text-gray-12">+ Unlimited Studio mode videos+ </p>+ <p className="mt-0.5 text-xs leading-relaxed text-gray-10">+ Saved to your device. Always free.+ </p>+ </div>+ </div>+ </div>+ {onShowBenefits && (+ <button+ type="button"+ onClick={() => {+ setInfoOpen(false);+ onShowBenefits();+ }}+ className="flex justify-between items-center px-4 py-2.5 w-full text-xs font-medium border-t transition-colors border-gray-4 text-gray-11 hover:text-gray-12 hover:bg-gray-2"+ >+ What are the benefits of Pro?+ <span aria-hidden className="text-gray-9">+ →+ </span>+ </button>+ )}+ </PopoverContent>+ </Popover>+ </div>+ <span+ className={clsx(+ "text-xs font-semibold tabular-nums",+ atLimit ? "text-red-500" : "text-gray-12",+ )}+ >+ {used}/{limit}+ </span>+ </div>+ <div className="overflow-hidden mt-2.5 w-full h-1.5 rounded-full bg-gray-5">+ <motion.div+ initial={{ width: 0 }}+ animate={{+ width: `${Math.min(100, Math.round((used / limit) * 100))}%`,+ }}+ transition={{+ type: "spring",+ stiffness: 110,+ damping: 20,+ delay: 0.15,+ }}className={clsx(- sidebarCollapsed- ? "bottom-[4px] h-10 absolute w-[68px]"- : "absolute w-[90px] h-[66px] bottom-[-3px] left-[-20px]",- "scale-[0.8]",+ "h-full rounded-full",+ atLimit ? "bg-red-500" : "bg-blue-500",)}/>- {!sidebarCollapsed ? (- <p className="relative left-8 text-center text-white truncate">- Upgrade to Pro- </p>- ) : null}- </Button>- );- },-);+ </div>+ {atLimit && (+ <p className="mt-2 text-[11px] leading-snug text-gray-10">+ Links over the limit stay locked unless you upgrade. You get {limit}{" "}+ new links on the 1st.+ </p>+ )}+ </div>+ );+};diff --git a/apps/web/components/pages/_components/UpgradeToPro.tsx b/apps/web/components/pages/_components/UpgradeToPro.tsxindex aeab3cb2d..3796675bf 100644--- a/apps/web/components/pages/_components/UpgradeToPro.tsx+++ b/apps/web/components/pages/_components/UpgradeToPro.tsx@@ -31,7 +31,7 @@ const ProRiveArt = ({ onReady }: { onReady: (rive: Rive | null) => void }) => {};const UpgradeToPro = ({- text = "Upgrade To Cap Pro",+ text = "Upgrade to Cap Pro",onClick,}: {text?: string;diff --git a/apps/web/lib/shareable-link-quota.ts b/apps/web/lib/shareable-link-quota.tsnew file mode 100644index 000000000..2b87dd48f--- /dev/null+++ b/apps/web/lib/shareable-link-quota.ts@@ -0,0 +1,71 @@+import "server-only";++import { db } from "@cap/database";+import { videos } from "@cap/database/schema";+import { type User, Video } from "@cap/web-domain";+import { and, count, eq, gte, lt, or } from "drizzle-orm";++const monthStartUtc = (reference: Date) =>+ new Date(Date.UTC(reference.getUTCFullYear(), reference.getUTCMonth(), 1));++const quotaWindowStart = (reference: Date) => {+ const start = monthStartUtc(reference);+ return start > Video.SHAREABLE_LINK_LIMIT_ENFORCED_FROM+ ? start+ : Video.SHAREABLE_LINK_LIMIT_ENFORCED_FROM;+};++/**+ * A video is over quota when 25 or more of the owner's videos were created+ * earlier in the same calendar month (UTC). The flag is derived from creation+ * order, so it sticks to the video across month boundaries, disappears the+ * moment the owner upgrades (callers skip the check for Pro owners), and+ * frees up if earlier videos from that month are deleted.+ */+export async function isVideoOverShareableLinkLimit(video: {+ id: Video.VideoId;+ ownerId: User.UserId;+ createdAt: Date;+ isScreenshot: boolean;+}): Promise<boolean> {+ if (video.isScreenshot) return false;+ if (video.createdAt < Video.SHAREABLE_LINK_LIMIT_ENFORCED_FROM) return false;++ const [row] = await db()+ .select({ earlier: count() })+ .from(videos)+ .where(+ and(+ eq(videos.ownerId, video.ownerId),+ eq(videos.isScreenshot, false),+ gte(videos.createdAt, quotaWindowStart(video.createdAt)),+ or(+ lt(videos.createdAt, video.createdAt),+ and(eq(videos.createdAt, video.createdAt), lt(videos.id, video.id)),+ ),+ ),+ );++ return (row?.earlier ?? 0) >= Video.FREE_PLAN_SHAREABLE_LINKS_PER_MONTH;+}++export async function getShareableLinkUsage(userId: User.UserId): Promise<{+ used: number;+ limit: number;+}> {+ const [row] = await db()+ .select({ used: count() })+ .from(videos)+ .where(+ and(+ eq(videos.ownerId, userId),+ eq(videos.isScreenshot, false),+ gte(videos.createdAt, quotaWindowStart(new Date())),+ ),+ );++ return {+ used: row?.used ?? 0,+ limit: Video.FREE_PLAN_SHAREABLE_LINKS_PER_MONTH,+ };+}diff --git a/packages/web-domain/src/Video.ts b/packages/web-domain/src/Video.tsindex c4a9949bc..82cc67242 100644--- a/packages/web-domain/src/Video.ts+++ b/packages/web-domain/src/Video.ts@@ -15,6 +15,14 @@ export type VideoId = typeof VideoId.Type;export const FREE_PLAN_MAX_RECORDING_SECONDS = 5 * 60;+export const FREE_PLAN_SHAREABLE_LINKS_PER_MONTH = 25;++// Quota is not retroactive: videos created before this date never count+// toward, nor get gated by, the monthly shareable-link limit.+export const SHAREABLE_LINK_LIMIT_ENFORCED_FROM = new Date(+ "2026-08-19T00:00:00.000Z",+);+// Purposefully doesn't include password as this is a public classexport class Video extends Schema.Class<Video>("Video")({id: VideoId,