The VS Code of video editing, built for agents.
TypeScript
Update dependencies and enhance dashboard components
konstantin-paulus8ff93b159bda
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 9c88f685..3042c542 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -4,3 +4,6 @@ VITE_SUPABASE_ANON_KEY=sb_publishable_V-K9coUWXVy8dsZPGKDw-g_d1JzJf8uVITE_UMAMI_WEBSITE_ID=e898e381-6ce3-4f5f-a485-8327ec9aa88bVITE_UMAMI_SCRIPT_URL=https://cloud.umami.is/script.jsVITE_UMAMI_DOMAINS=diffusion.studio,app.diffusion.studio++# The Diffusion Studio API; http://localhost:3000 for a local one+VITE_API_URL=https://api.diffusion.studiodiff --git a/apps/web/package.json b/apps/web/package.jsonindex 716b930a..3b0911d3 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -14,6 +14,7 @@},"dependencies": {"@diffusionstudio/agent-chat": "*",+ "@diffusionstudio/api-contract": "^0.2.0","@diffusionstudio/assets": "*","@diffusionstudio/dapi": "*","@diffusionstudio/encoder": "*",@@ -29,6 +30,8 @@"@solid-primitives/resize-observer": "^2.1.3","@solidjs/router": "^0.15.4","@supabase/supabase-js": "^2.99.2",+ "@trpc/client": "^11.19.0",+ "@trpc/server": "^11.19.0","animejs": "^4.4.1","cmdk-solid": "^1.1.2","colord": "^2.9.3",diff --git a/apps/web/src/components/dashboard/account-view.tsx b/apps/web/src/components/dashboard/account-view.tsxindex a389ee67..b552ba7e 100644--- a/apps/web/src/components/dashboard/account-view.tsx+++ b/apps/web/src/components/dashboard/account-view.tsx@@ -5,6 +5,7 @@import { useSearchParams } from "@solidjs/router";import { Show, createEffect, createSignal } from "solid-js";import { toast } from "somoto";+import type { EmailPreferences } from "@diffusionstudio/api-contract";import { useAvatar } from "@/hooks/use-avatar";import {@@ -27,14 +28,14 @@ import {import { TextField, TextFieldInput, TextFieldLabel } from "@/components/ui/text-field";import { useAuth } from "@/context/auth";import { supabase } from "@/lib/supabase";-import { backend } from "@/lib/backend";+import { api } from "@/lib/api";import {DashboardDividedStack,DashboardFormModal,DashboardFreePlanDetails,DashboardInfoActionRow,- DashboardProPlanDetails,+ DashboardPaidPlanDetails,DashboardPlanSummaryCard,DashboardScrollView,DashboardSurfaceSection,@@ -524,7 +525,7 @@ function DashboardAccountFreePlanCard() {<span class="grid h-7 w-6 place-items-center overflow-clip"><Icon name="upgrade" class="size-6" /></span>- Upgrade to Pro+ Upgrade</Button></DashboardSurfaceCard>);@@ -537,7 +538,7 @@ function DashboardAccountPlanSection() {return (<DashboardTitledSection title="Plan"><Show- when={auth.isPro()}+ when={auth.isSubscribed()}fallback={<DashboardAccountFreePlanCard />}><DashboardPlanSummaryCard@@ -550,53 +551,49 @@ function DashboardAccountPlanSection() {</Button>}>- <DashboardProPlanDetails />+ <DashboardPaidPlanDetails /></DashboardPlanSummaryCard></Show></DashboardTitledSection>);}-type EmailPreferenceColumn =- | "product_updates_enabled"- | "marketing_announcements_enabled";+type EmailPreference = keyof EmailPreferences;function DashboardAccountEmailPreferencesSection() {const auth = useAuth();const [optimistic, setOptimistic] =- createSignal<Partial<Record<EmailPreferenceColumn, boolean>>>({});+ createSignal<Partial<EmailPreferences>>({});- const serverValue = (column: EmailPreferenceColumn) =>- column === "product_updates_enabled"+ const serverValue = (preference: EmailPreference) =>+ preference === "productUpdates"? auth.productUpdatesEnabled(): auth.marketingAnnouncementsEnabled();- const value = (column: EmailPreferenceColumn) =>- optimistic()[column] ?? serverValue(column);+ const value = (preference: EmailPreference) =>+ optimistic()[preference] ?? serverValue(preference);- // Clear optimistic overrides once the server state catches up via realtime.+ // Clear optimistic overrides once the refetched account catches up.createEffect(() => {const current = optimistic();let next = current;- for (const column of [- "product_updates_enabled",- "marketing_announcements_enabled",- ] as const) {- if (column in current && current[column] === serverValue(column)) {+ for (const preference of ["productUpdates", "marketingAnnouncements"] as const) {+ if (preference in current && current[preference] === serverValue(preference)) {if (next === current) next = { ...current };- delete next[column];+ delete next[preference];}}if (next !== current) setOptimistic(next);});- const handleChange = (column: EmailPreferenceColumn) => async (v: boolean) => {- setOptimistic({ ...optimistic(), [column]: v });+ const handleChange = (preference: EmailPreference) => async (v: boolean) => {+ setOptimistic({ ...optimistic(), [preference]: v });try {- await backend.updateEmailPreference({ column, value: v });+ await api.account.updateEmailPreferences.mutate({ [preference]: v });+ auth.refreshAccount();} catch (err) {const next = { ...optimistic() };- delete next[column];+ delete next[preference];setOptimistic(next);const message = err instanceof Error ? err.message : "Failed to update preference";toast.error("Action failed", { description: message });@@ -609,14 +606,14 @@ function DashboardAccountEmailPreferencesSection() {<DashboardAccountPreferenceRowtitle="Product updates"description="Feature updates and important changes."- checked={value("product_updates_enabled")}- onChange={handleChange("product_updates_enabled")}+ checked={value("productUpdates")}+ onChange={handleChange("productUpdates")}/><DashboardAccountPreferenceRowtitle="Marketing & announcements"description="Product news and announcements."- checked={value("marketing_announcements_enabled")}- onChange={handleChange("marketing_announcements_enabled")}+ checked={value("marketingAnnouncements")}+ onChange={handleChange("marketingAnnouncements")}/></DashboardDividedStack></DashboardSurfaceSection>diff --git a/apps/web/src/components/dashboard/ai-credits-view.tsx b/apps/web/src/components/dashboard/ai-credits-view.tsxindex 5f9df3f7..5842352e 100644--- a/apps/web/src/components/dashboard/ai-credits-view.tsx+++ b/apps/web/src/components/dashboard/ai-credits-view.tsx@@ -12,7 +12,9 @@ import { useAuth } from "@/context/auth";import {TOPUP_CREDIT_TIERS,getTopupPrice,+ planName,startTopupCheckout,+ topupCredits,} from "@/lib/checkout";import {@@ -22,16 +24,12 @@ import {} from "./shared";import { DashboardProPlanFeatures } from "./plans-view";-import type { TopupCredits } from "@/lib/backend";+import type { TopupCredits } from "@diffusionstudio/api-contract";function formatCredits(value: number): string {return value.toLocaleString();}-function parseTierCredits(tier: TopupCredits): number {- return parseInt(tier.replace("_", ""), 10);-}-function formatPercent(used: number, total: number): string {if (total <= 0) return "0% used";const percent = Math.min(100, Math.max(0, (used / total) * 100));@@ -131,7 +129,7 @@ function DashboardAiCreditsTopUpSection() {)}><span class="text-xs text-foreground">- {formatCredits(parseTierCredits(tier))} credits+ {formatCredits(topupCredits(tier))} credits</span><span class="text-xs text-muted-foreground">${getTopupPrice(tier)}@@ -155,7 +153,7 @@ function DashboardAiCreditsNeedMoreSection() {<div class="flex flex-col gap-4 sm:flex-row sm:items-center"><DashboardLabelValuelabel="Keep creating without interruptions"- value="Flexible credit tiers, top ups on demand, and the full Pro experience."+ value="Monthly AI credits, top ups on demand, and the full Pro experience."/><Button class="gap-0 pl-0 pr-2" onClick={goToBilling}><span class="grid h-7 w-6 place-items-center overflow-clip">@@ -183,7 +181,7 @@ export function DashboardAiCreditsView() {const goToBilling = () =>setParams({ dashboard: "billing" }, { replace: true });- const isPro = () => auth.isPro();+ const isSubscribed = () => auth.isSubscribed();const total = () => auth.creditLimit();const remaining = () => auth.remainingCredits();const used = () => Math.max(0, total() - remaining());@@ -196,9 +194,9 @@ export function DashboardAiCreditsView() {return `Resets in ${days} ${days === 1 ? "day" : "days"} - ${date}`;};const creditLimitLabel = () =>- isPro()- ? `${formatCredits(total())} credits/mo`- : `${formatCredits(total())} trial credits`;+ isSubscribed()+ ? `${planName(auth.plan())} \u00B7 ${formatCredits(total())} credits/mo`+ : `Free \u00B7 ${formatCredits(total())} trial credits`;const creditUsageLabel = () =>`${formatCredits(used())} / ${formatCredits(total())}`;@@ -206,8 +204,8 @@ export function DashboardAiCreditsView() {<DashboardScrollView><DashboardSurfaceSection title="AI credits"><div class="flex flex-col gap-4 sm:flex-row sm:items-center">- <DashboardLabelValue label="Credit subscription" value={creditLimitLabel()} />- <Show when={!isPro()}>+ <DashboardLabelValue label="Plan" value={creditLimitLabel()} />+ <Show when={!isSubscribed()}><Button variant="secondary" onClick={goToBilling}>Upgrade plan</Button>@@ -221,14 +219,14 @@ export function DashboardAiCreditsView() {valueLabel={creditUsageLabel()}used={used()}total={total()}- footerLabel={isPro() ? resetLabel() : "One time only"}+ footerLabel={isSubscribed() ? resetLabel() : "One time only"}/></DashboardSurfaceSection>- <Show when={isPro()}>+ <Show when={isSubscribed()}><DashboardAiCreditsTopUpSection /></Show>- <Show when={!isPro()}>+ <Show when={!isSubscribed()}><DashboardAiCreditsNeedMoreSection /></Show></DashboardScrollView>diff --git a/apps/web/src/components/dashboard/billing-info-view.tsx b/apps/web/src/components/dashboard/billing-info-view.tsxindex 704fbc10..5f8f833e 100644--- a/apps/web/src/components/dashboard/billing-info-view.tsx+++ b/apps/web/src/components/dashboard/billing-info-view.tsx@@ -3,47 +3,25 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { For, Show, createResource, type Accessor, type JSX } from "solid-js";+import type { BillingInfo } from "@diffusionstudio/api-contract";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";import { openBillingPortal } from "@/lib/checkout";import { useAuth } from "@/context/auth";-import { backend } from "@/lib/backend";+import { api } from "@/lib/api";import {DashboardDividedStack,DashboardFreePlanDetails,DashboardInfoActionRow,- DashboardProPlanDetails,+ DashboardPaidPlanDetails,DashboardPlanSummaryCard,DashboardSurfaceCard,DashboardSurfaceSection,} from "./shared";-type BillingAddress = {- legalName: string;- line1: string;- line2: string;- city: string;- state: string;- postalCode: string;- country: string;-};--type PaymentMethod = {- brand: string;- last4: string;- expMonth: number;- expYear: number;-};--type BillingInfo = {- email: string;- address: BillingAddress | null;- taxId: string | null;- paymentMethod: PaymentMethod | null;- billingPeriod: "month" | "year" | null;-};+type BillingAddress = NonNullable<BillingInfo["address"]>;function capitalizeBrand(brand: string): string {if (!brand) return "Card";@@ -69,7 +47,7 @@ function DashboardBillingFreePlanCard(props: DashboardBillingFreePlanCardProps)<span class="grid h-7 w-6 place-items-center overflow-clip"><Icon name="upgrade" class="size-6" /></span>- Upgrade to Pro+ Upgrade</Button></DashboardSurfaceCard>);@@ -91,7 +69,7 @@ function DashboardBillingCurrentPlan(props: DashboardBillingCurrentPlanProps) {</div><Show- when={auth.isPro()}+ when={auth.isSubscribed()}fallback={<DashboardBillingFreePlanCard onUpgrade={props.onUpgrade} />}><DashboardPlanSummaryCard@@ -101,7 +79,7 @@ function DashboardBillingCurrentPlan(props: DashboardBillingCurrentPlanProps) {</Button>}>- <DashboardProPlanDetails />+ <DashboardPaidPlanDetails /></DashboardPlanSummaryCard></Show>@@ -217,17 +195,22 @@ export function DashboardBillingInfoView(props: DashboardBillingInfoViewProps) {const auth = useAuth();const [info] = createResource<BillingInfo | undefined, boolean>(- () => auth.isPro(),- async (isPro) => {- if (!isPro) return undefined;- return (await backend.getBillingInfo()) ?? undefined;+ () => auth.hasBillingAccount(),+ async (hasBillingAccount) => {+ if (!hasBillingAccount) return undefined;+ try {+ return await api.billing.info.query();+ } catch (err) {+ console.error("Failed to load billing information", err);+ return undefined;+ }},);return (<div class="flex flex-col gap-6"><DashboardBillingCurrentPlan onUpgrade={props.onUpgrade} />- <Show when={auth.isPro()}>+ <Show when={auth.hasBillingAccount()}><DashboardBillingInformation info={info} /></Show></div>diff --git a/apps/web/src/components/dashboard/billing-view.tsx b/apps/web/src/components/dashboard/billing-view.tsxindex 8bffb8ec..21f574a5 100644--- a/apps/web/src/components/dashboard/billing-view.tsx+++ b/apps/web/src/components/dashboard/billing-view.tsx@@ -37,7 +37,7 @@ function DashboardBillingTabButton(props: DashboardBillingTabButtonProps) {export function DashboardBillingView() {const auth = useAuth();const [tab, setTab] = createSignal<BillingTab>("plans");- const activeTab = (): BillingTab => (auth.hasStripeCustomer() ? tab() : "plans");+ const activeTab = (): BillingTab => (auth.hasBillingAccount() ? tab() : "plans");return (<div class="min-h-0 flex-1 overflow-y-auto">@@ -50,7 +50,7 @@ export function DashboardBillingView() {active={activeTab() === "plans"}onClick={() => setTab("plans")}/>- <Show when={auth.hasStripeCustomer()}>+ <Show when={auth.hasBillingAccount()}><DashboardBillingTabButtonlabel="Billing"active={activeTab() === "billing"}diff --git a/apps/web/src/components/dashboard/invoices-view.tsx b/apps/web/src/components/dashboard/invoices-view.tsxindex d3bc61f5..42bba2b9 100644--- a/apps/web/src/components/dashboard/invoices-view.tsx+++ b/apps/web/src/components/dashboard/invoices-view.tsx@@ -3,12 +3,13 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { For, Show, createResource } from "solid-js";+import type { Invoice } from "@diffusionstudio/api-contract";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { backend } from "@/lib/backend";+import { api } from "@/lib/api";import { DashboardDividedStack, DashboardSurfaceCard } from "./shared";@@ -23,15 +24,6 @@ export type InvoiceItem = {url: string | null;};-type RawInvoice = {- id: string;- status: string | null;- total: number;- currency: string;- dueDate: number;- hostedUrl: string | null;-};-function formatInvoiceDate(timestampMs: number): string {return new Date(timestampMs).toLocaleDateString("en-US", {year: "numeric",@@ -48,7 +40,7 @@ function formatInvoiceAmount(totalMinor: number, currency: string): string {}function mapInvoiceStatus(- status: string | null,+ status: Invoice["status"],dueDateMs: number,): InvoiceStatus {if (status === "paid") return "Paid";@@ -58,7 +50,7 @@ function mapInvoiceStatus(return "Open";}-function toInvoiceItem(invoice: RawInvoice): InvoiceItem {+function toInvoiceItem(invoice: Invoice): InvoiceItem {return {id: invoice.id,dueDate: formatInvoiceDate(invoice.dueDate),@@ -145,7 +137,7 @@ function DashboardInvoicesList(props: { invoices: InvoiceItem[] }) {export function DashboardInvoicesView() {const [invoices] = createResource<InvoiceItem[]>(async () => {try {- const raw = await backend.listInvoices();+ const raw = await api.billing.invoices.query();return raw.map(toInvoiceItem);} catch (err) {console.error("Failed to load invoices", err);diff --git a/apps/web/src/components/dashboard/plans-view.tsx b/apps/web/src/components/dashboard/plans-view.tsxindex 9b5c1507..5eb5c7f7 100644--- a/apps/web/src/components/dashboard/plans-view.tsx+++ b/apps/web/src/components/dashboard/plans-view.tsx@@ -2,18 +2,10 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Show, createSignal } from "solid-js";-import type { SubscriptionCredits } from "@/lib/backend";+import { For, Show, createSignal, type JSX } from "solid-js";+import type { BillingPeriod, PaidPlan } from "@diffusionstudio/api-contract";import { Button } from "@/components/ui/button";-import {- Select,- SelectContent,- SelectItem,- SelectPortal,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";import {SwitchControl,SwitchInput,@@ -21,25 +13,21 @@ import {Switch as Toggle,} from "@/components/ui/switch";import {- SUBSCRIPTION_CREDIT_TIERS,- SUBSCRIPTION_VOLUME_DISCOUNT,- getSubscriptionPrice,+ FREE_CREDITS,+ MAX_YEARLY_DISCOUNT,+ PAID_PLANS,+ PLANS,openBillingPortal,+ planName,startSubscriptionCheckout,+ yearlySavings,} from "@/lib/checkout";+import { track } from "@/lib/analytics";import { useAuth } from "@/context/auth";import { DashboardFeatureRow, DashboardSurfaceCard } from "./shared";-function formatCreditTierLabel(tier: SubscriptionCredits): string {- const credits = parseInt(tier.replace("_", ""), 10).toLocaleString();- const discount = SUBSCRIPTION_VOLUME_DISCOUNT[tier];- return discount > 0- ? `${credits} credits (${Math.round(discount * 100)}% off)`- : `${credits} credits`;-}--function DashboardBillingFreePlanFeatures() {+function DashboardFreePlanFeatures() {return (<><DashboardFeatureRow label="The full editor" />@@ -61,40 +49,114 @@ export function DashboardProPlanFeatures() {);}-function DashboardBillingEnterprisePlanFeatures() {- return (+const PLAN_FEATURES: Record<PaidPlan, () => JSX.Element> = {+ pro: () => (+ <>+ <DashboardFeatureRow label="Everything in Free" />+ <DashboardProPlanFeatures />+ </>+ ),+ plus: () => (+ <>+ <DashboardFeatureRow label="Everything in Pro" />+ <DashboardFeatureRow label="2× more AI credits" />+ <DashboardFeatureRow label="Priority support" />+ </>+ ),+ max: () => (<>- <DashboardFeatureRow label="Shared workspace and assets" />- <DashboardFeatureRow label="SSO and audit logs" />- <DashboardFeatureRow label="Pooled credits, invoiced" />+ <DashboardFeatureRow label="Everything in Pro" />+ <DashboardFeatureRow label="6× more AI credits" />+ <DashboardFeatureRow label="Priority support" /></>+ ),+};++type DashboardPlanCardProps = {+ name: string;+ price: number;+ /** Shown under the price, e.g. the yearly savings. */+ note?: string;+ credits: string;+ action: JSX.Element;+ children: JSX.Element;+};++function DashboardPlanCard(props: DashboardPlanCardProps) {+ return (+ <DashboardSurfaceCard class="flex flex-col gap-4">+ <div class="flex flex-col gap-1">+ <h2 class="text-sm leading-5 font-450 text-foreground">{props.name}</h2>+ <div class="flex items-center gap-1">+ <p class="text-lg leading-6 font-450 text-foreground">${props.price}</p>+ <Show when={props.price > 0}>+ <p class="text-muted-foreground text-xs translate-y-0.5 leading-none">/mo</p>+ </Show>+ </div>+ <p class="text-muted-foreground text-xs min-h-4">{props.note}</p>+ </div>++ <div class="flex flex-col gap-3">+ <p class="text-muted-foreground text-xs">{props.credits}</p>+ {props.action}+ </div>++ <div class="h-px w-full bg-border" />++ <div class="flex flex-col gap-2">{props.children}</div>+ </DashboardSurfaceCard>);}export function DashboardPlansView() {const auth = useAuth();const [annualBilling, setAnnualBilling] = createSignal(true);- const [creditTier, setCreditTier] = createSignal<SubscriptionCredits>("2_500");- const [checkoutLoading, setCheckoutLoading] = createSignal(false);+ const [checkoutPlan, setCheckoutPlan] = createSignal<PaidPlan | null>(null);++ const billingPeriod = (): BillingPeriod => (annualBilling() ? "year" : "month");- const billingPeriod = (): "month" | "year" => (annualBilling() ? "year" : "month");- const proPrice = () => getSubscriptionPrice(creditTier(), billingPeriod());+ const currentPlanLabel = () =>+ auth.plan() === "legacy" ? "a legacy Pro" : `the ${planName(auth.plan())}`;- const handleUpgrade = async () => {- if (checkoutLoading()) return;- setCheckoutLoading(true);+ const handleChoose = async (plan: PaidPlan) => {+ if (checkoutPlan()) return;+ setCheckoutPlan(plan);+ track("subscription_checkout_started", { plan, billing_period: billingPeriod() });try {- await startSubscriptionCheckout({- creditQuantity: creditTier(),- billingPeriod: billingPeriod(),- });+ await startSubscriptionCheckout({ plan, billingPeriod: billingPeriod() });} finally {- setCheckoutLoading(false);+ setCheckoutPlan(null);}};- const handleLearnMoreClick = (event: MouseEvent) => {- event.preventDefault();+ // A subscriber changes plans in the billing portal, which prorates+ // upgrades and moves downgrades to the end of the period.+ const planAction = (plan: PaidPlan) => {+ const name = PLANS[plan].name;+ if (auth.plan() === plan) {+ return (+ <Button variant="secondary" class="w-full" disabled>+ Current plan+ </Button>+ );+ }+ if (auth.isSubscribed()) {+ return (+ <Button variant="secondary" class="w-full" onClick={openBillingPortal}>+ Switch to {name}+ </Button>+ );+ }+ return (+ <Button+ variant={plan === "pro" ? "default" : "secondary"}+ class="w-full"+ disabled={checkoutPlan() !== null}+ onClick={() => handleChoose(plan)}+ >+ Choose {name}+ </Button>+ );};return (@@ -106,9 +168,9 @@ export function DashboardPlansView() {Plans</h2><div class="text-muted-foreground text-xs">- <p>You are currently on a {auth.isPro() ? "Pro" : "Free"} plan.</p>- <Show when={!auth.isPro()}>- <p>Select AI credits that fit your usage, then upgrade.</p>+ <p>You are currently on {currentPlanLabel()} plan.</p>+ <Show when={!auth.isSubscribed()}>+ <p>Start free. Let agents handle more with Pro.</p></Show></div></div>@@ -116,7 +178,7 @@ export function DashboardPlansView() {<div class="flex shrink-0 items-center gap-2 text-xs"><div class="flex flex-col text-right text-muted-foreground"><span>Yearly billing</span>- <span>Save up to 40%</span>+ <span>Save up to {MAX_YEARLY_DISCOUNT}%</span></div><Toggle checked={annualBilling()} onChange={setAnnualBilling} class="relative">@@ -128,141 +190,45 @@ export function DashboardPlansView() {</div></div>- <div class="grid gap-4 md:grid-cols-3">- <DashboardSurfaceCard class="flex min-h-99 flex-col gap-3">- <div class="flex flex-1 flex-col gap-4">- <div class="flex flex-col gap-1">- <h2 class="text-sm leading-5 font-450 text-foreground">- Free- </h2>- <p class="text-lg leading-6 font-450 text-foreground">- $0- </p>- <p class="text-muted-foreground text-xs min-h-8 line-clamp-2 -mb-2">- Everything you need to edit and export videos- </p>- </div>-- <div class="flex flex-col gap-3">- <div class="h-px w-full bg-border" />- <div class="flex h-7 items-center">- <p class="min-w-0 flex-1 truncate text-xs text-muted-foreground">- 50 free trial AI credits- </p>- </div>- <div class="h-px w-full bg-border" />- </div>-- <div class="flex flex-col gap-2">- <DashboardBillingFreePlanFeatures />- </div>- </div>-- <Button variant="secondary" class="w-full" disabled={!auth.isPro()} onClick={openBillingPortal}>- {auth.isPro() ? "Downgrade to Free" : "Current plan"}- </Button>- </DashboardSurfaceCard>-- <DashboardSurfaceCard class="flex min-h-99 flex-col gap-3">- <div class="flex flex-1 flex-col gap-4">- <div class="flex flex-col gap-1">- <h2 class="text-sm leading-5 font-450 text-foreground">- Pro- </h2>- <div class="flex items-center gap-1">- <p class="text-lg leading-6 font-450 text-foreground">- ${proPrice()}- </p>- <p class="text-muted-foreground text-xs translate-y-0.5 leading-none">- {annualBilling() ? "/month, billed annually" : "/month"}- </p>- </div>- <p class="text-muted-foreground text-xs min-h-8 line-clamp-2 -mb-2">- AI powered editing, analysis, and generation- </p>- </div>-- <div class="flex flex-col gap-3">- <div class="h-px w-full bg-border" />- <Select<SubscriptionCredits>- options={SUBSCRIPTION_CREDIT_TIERS}- value={creditTier()}- onChange={(value) => value && setCreditTier(value)}- itemComponent={(itemProps) => (- <SelectItem item={itemProps.item}>- {formatCreditTierLabel(itemProps.item.rawValue)}- </SelectItem>- )}- >- <SelectTrigger aria-label="Select AI credits per month">- <SelectValue<SubscriptionCredits>>- {formatCreditTierLabel(creditTier())}- <span class="text-muted-foreground text-xs">/mo*</span>- </SelectValue>- </SelectTrigger>- <SelectPortal>- <SelectContent />- </SelectPortal>- </Select>- <div class="h-px w-full bg-border" />- </div>-- <div class="flex flex-col gap-2">- <p class="text-muted-foreground text-xs">- Everything in Free, plus:- </p>- <DashboardProPlanFeatures />- </div>- </div>-- <Button class="w-full" disabled={auth.isPro() || checkoutLoading()} onClick={handleUpgrade}>- {auth.isPro() ? "Current plan" : "Continue with Pro"}- </Button>- </DashboardSurfaceCard>-- <DashboardSurfaceCard class="flex min-h-99 flex-col gap-3">- <div class="flex flex-1 flex-col gap-4">- <div class="flex flex-col gap-1">- <h2 class="text-sm leading-5 font-450 text-foreground">- Enterprise- </h2>- <p class="text-lg leading-6 font-450 text-foreground">- Custom- </p>- <p class="text-muted-foreground text-xs min-h-8 line-clamp-2 -mb-2">- For larger production operations- </p>- </div>-- <div class="flex flex-col gap-3">- <div class="h-px w-full bg-border" />- <div class="flex h-7 items-center">- <p class="min-w-0 flex-1 truncate text-xs text-muted-foreground">- Custom AI credit limits- </p>- </div>- <div class="h-px w-full bg-border" />- </div>-- <div class="flex flex-col gap-2">- <p class="text-muted-foreground text-xs">- Everything in Pro, plus:- </p>- <DashboardBillingEnterprisePlanFeatures />- </div>- </div>-- <Button as="a" class="w-full" href="https://cal.com/konstantinpaulus" target="_blank" variant="secondary">- Contact sales- </Button>- </DashboardSurfaceCard>+ <div class="grid auto-rows-fr gap-4 sm:grid-cols-2 lg:grid-cols-4">+ <DashboardPlanCard+ name="Free"+ price={0}+ credits={`${FREE_CREDITS} credits (one time)`}+ action={+ <Button+ variant="secondary"+ class="w-full"+ disabled={!auth.isSubscribed()}+ onClick={openBillingPortal}+ >+ {auth.isSubscribed() ? "Downgrade to Free" : "Current plan"}+ </Button>+ }+ >+ <DashboardFreePlanFeatures />+ </DashboardPlanCard>++ <For each={PAID_PLANS}>+ {(plan) => (+ <DashboardPlanCard+ name={PLANS[plan].name}+ price={PLANS[plan].monthlyPrice[billingPeriod()]}+ note={annualBilling() ? `Save $${yearlySavings(plan)}/year` : undefined}+ credits={`${PLANS[plan].monthlyCredits.toLocaleString()} credits /mo`}+ action={planAction(plan)}+ >+ {PLAN_FEATURES[plan]()}+ </DashboardPlanCard>+ )}+ </For></div></div>- <div class="px-2 pt-1 text-xs text-muted-foreground">- <span>*AI credits reset monthly. Volume discount applies for higher credits. </span>- <a href="#" class="text-primary hover:underline" onClick={handleLearnMoreClick}>- Learn more+ <div class="px-2 pt-1 text-xs text-muted-foreground">+ <span>AI credits reset monthly, on yearly plans too. Looking for enterprise features? </span>+ <a href="https://cal.com/konstantinpaulus" target="_blank" class="text-primary hover:underline">+ Contact sales</a></div></div>diff --git a/apps/web/src/components/dashboard/shared.tsx b/apps/web/src/components/dashboard/shared.tsxindex c0ee3401..e0e468c7 100644--- a/apps/web/src/components/dashboard/shared.tsx+++ b/apps/web/src/components/dashboard/shared.tsx@@ -7,7 +7,8 @@ import { Dialog, DialogContent, DialogPortal } from "@/components/ui/dialog";import { Icon } from "@/components/ui/icon";import { useAuth } from "@/context/auth";import { cx } from "@/lib/cva";-import { backend } from "@/lib/backend";+import { api } from "@/lib/api";+import { FREE_CREDITS, planName } from "@/lib/checkout";import {For,Show,@@ -228,7 +229,7 @@ export function DashboardFreePlanDetails() {<DashboardPlanDetailsdetails={[{ label: "Free", value: "$0.00" },- { label: "AI credits", value: "50 trial credits \u00B7 One time only" },+ { label: "AI credits", value: `${FREE_CREDITS} trial credits \u00B7 One time only` },]}/>);@@ -247,9 +248,16 @@ function formatCurrency(amountCents: number, currency: string) {}).format(amountCents / 100);}-export function DashboardProPlanDetails() {+export function DashboardPaidPlanDetails() {const auth = useAuth();- const [summary] = createResource(() => backend.getSubscriptionSummary());+ const [summary] = createResource(async () => {+ try {+ return await api.billing.subscription.query();+ } catch (err) {+ console.error("Failed to load the subscription", err);+ return null;+ }+ });const priceLabel = () => {const s = summary();@@ -270,7 +278,7 @@ export function DashboardProPlanDetails() {return (<DashboardPlanDetailsdetails={[- { label: "Pro", value: priceLabel() },+ { label: planName(auth.plan()), value: priceLabel() },{ label: "AI credits", value: creditsLabel() },{ label: "Renews", value: renewsLabel() },]}diff --git a/apps/web/src/components/dashboard/sidebar.tsx b/apps/web/src/components/dashboard/sidebar.tsxindex a48046b6..e2d58bea 100644--- a/apps/web/src/components/dashboard/sidebar.tsx+++ b/apps/web/src/components/dashboard/sidebar.tsx@@ -8,6 +8,7 @@ import { Icon } from "@/components/ui/icon";import { useAuth } from "@/context/auth";import { useAvatar } from "@/hooks/use-avatar";import { cx } from "@/lib/cva";+import { planName } from "@/lib/checkout";type DashboardSidebarItemProps = {icon: string;@@ -160,7 +161,7 @@ export function DashboardSidebarUser(props: DashboardSidebarUserProps) {return user?.user_metadata?.full_name || user?.email || "User";};- const planLabel = () => (auth.isPro() ? "Pro Plan" : "Free Plan");+ const planLabel = () => `${planName(auth.plan())} Plan`;const initial = () => displayName().charAt(0).toUpperCase();const avatarUrl = useAvatar();diff --git a/apps/web/src/components/purchase-success.tsx b/apps/web/src/components/purchase-success.tsxindex 6a54221f..1d6bb4da 100644--- a/apps/web/src/components/purchase-success.tsx+++ b/apps/web/src/components/purchase-success.tsx@@ -3,16 +3,26 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { useSearchParams } from "@solidjs/router";-import { Show, createSignal, onCleanup, onMount } from "solid-js";+import { Show, createEffect, createSignal, onCleanup, onMount } from "solid-js";import { Icon } from "@/components/ui/icon";+import { useAuth } from "@/context/auth";import { mainBridge } from "@/lib/ipc";import { MAIN_CHANNELS } from "@desktop/main-channels";export function PurchaseSuccess() {+ const auth = useAuth();const [params, setParams] = useSearchParams();const [deepLinkSuccess, setDeepLinkSuccess] = createSignal(false);+ const succeeded = () => params.checkout === "success" || deepLinkSuccess();++ createEffect(() => {+ if (succeeded()) {+ auth.refreshAccount();+ }+ });+onMount(() => {if (!window.desktop) return;@@ -48,7 +58,7 @@ export function PurchaseSuccess() {};return (- <Show when={params.checkout === "success" || deepLinkSuccess()}>+ <Show when={succeeded()}><divclass="pointer-events-auto fixed inset-0 z-[999] flex flex-col items-center justify-center gap-2 bg-overlay-strong"onClick={close}diff --git a/apps/web/src/components/sidebar-left/project-menu/ai-credits-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/ai-credits-menu.tsxindex 46d45c73..9f40c51b 100644--- a/apps/web/src/components/sidebar-left/project-menu/ai-credits-menu.tsx+++ b/apps/web/src/components/sidebar-left/project-menu/ai-credits-menu.tsx@@ -24,7 +24,7 @@ export function AiCreditsMenu() {const auth = useAuth();const navigate = useNavigate();- const isPro = () => auth.isPro();+ const isSubscribed = () => auth.isSubscribed();const total = () => auth.creditLimit();const remaining = () => auth.remainingCredits();const used = () => Math.max(0, total() - remaining());@@ -32,7 +32,7 @@ export function AiCreditsMenu() {const usageLabel = () => `${formatCredits(used())} / ${formatCredits(total())}`;const footerLabel = () => {- if (!isPro()) return "One time only";+ if (!isSubscribed()) return "One time only";const reset = auth.nextCreditReset();if (!reset) return "Resets monthly";const days = Math.max(0, Math.ceil((reset.getTime() - Date.now()) / 86_400_000));diff --git a/apps/web/src/components/upgrade-dialog.tsx b/apps/web/src/components/upgrade-dialog.tsxindex df329478..2d8b78f8 100644--- a/apps/web/src/components/upgrade-dialog.tsx+++ b/apps/web/src/components/upgrade-dialog.tsx@@ -3,19 +3,11 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { For, Show, createSignal, onMount } from "solid-js";-import type { SubscriptionCredits, TopupCredits } from "@/lib/backend";+import type { BillingPeriod, PaidPlan, TopupCredits } from "@diffusionstudio/api-contract";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogPortal } from "@/components/ui/dialog";import { Icon } from "@/components/ui/icon";-import {- Select,- SelectContent,- SelectItem,- SelectPortal,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";import {SwitchControl,SwitchInput,@@ -24,13 +16,14 @@ import {} from "@/components/ui/switch";import { useAuth } from "@/context/auth";import {- SUBSCRIPTION_CREDIT_TIERS,- SUBSCRIPTION_VOLUME_DISCOUNT,+ MAX_YEARLY_DISCOUNT,+ PAID_PLANS,+ PLANS,TOPUP_CREDIT_TIERS,- getSubscriptionPrice,getTopupPrice,startSubscriptionCheckout,startTopupCheckout,+ topupCredits,} from "@/lib/checkout";import { track } from "@/lib/analytics";import { mainBridge } from "@/lib/ipc";@@ -50,18 +43,6 @@ function formatCredits(value: number): string {return value.toLocaleString();}-function formatSubscriptionTier(tier: SubscriptionCredits): string {- const credits = parseInt(tier.replace("_", ""), 10).toLocaleString();- const discount = SUBSCRIPTION_VOLUME_DISCOUNT[tier];- return discount > 0- ? `${credits} credits (${Math.round(discount * 100)}% off)`- : `${credits} credits`;-}--function parseTopupCredits(tier: TopupCredits): number {- return parseInt(tier.replace("_", ""), 10);-}-function FeatureRow(props: { label: string }) {return (<div class="flex items-center gap-2">@@ -75,22 +56,21 @@ function FeatureRow(props: { label: string }) {function ProUpgradeContent() {const [annualBilling, setAnnualBilling] = createSignal(true);- const [creditTier, setCreditTier] = createSignal<SubscriptionCredits>("2_500");+ const [plan, setPlan] = createSignal<PaidPlan>("pro");const [loading, setLoading] = createSignal(false);- const billingPeriod = (): "month" | "year" => (annualBilling() ? "year" : "month");- const price = () => getSubscriptionPrice(creditTier(), billingPeriod());+ const billingPeriod = (): BillingPeriod => (annualBilling() ? "year" : "month");const handleUpgrade = async () => {if (loading()) return;setLoading(true);track('subscription_checkout_started', {- credit_tier: creditTier(),+ plan: plan(),billing_period: billingPeriod(),});try {await startSubscriptionCheckout({- creditQuantity: creditTier(),+ plan: plan(),billingPeriod: billingPeriod(),});} finally {@@ -107,14 +87,11 @@ function ProUpgradeContent() {<div class="flex flex-col gap-1"><img src="/mark-macos-small.png" alt="Diffusion Studio Logo Mark" class="size-12" /><h2 class="mt-2 text-sm leading-5 font-450 text-foreground">- Diffusion Studio Pro+ Upgrade Diffusion Studio</h2>- <div class="flex items-end gap-1 mt-2">- <p class="text-lg leading-6 font-450 text-foreground">${price()}</p>- <p class="text-xs leading-none text-muted-foreground translate-y-[-4px]">- {annualBilling() ? "/month, billed annually" : "/month"}- </p>- </div>+ <p class="text-xs text-muted-foreground">+ Pick a plan to keep creating with AI.+ </p></div><div class="flex items-center gap-2 text-xs">@@ -124,39 +101,45 @@ function ProUpgradeContent() {<SwitchThumb variant="compact" /></SwitchControl></Toggle>- <span class="text-muted-foreground">Yearly billing (save 24%)</span>+ <span class="text-muted-foreground">Yearly billing (save up to {MAX_YEARLY_DISCOUNT}%)</span></div>- <Select<SubscriptionCredits>- options={SUBSCRIPTION_CREDIT_TIERS}- value={creditTier()}- onChange={(value) => value && setCreditTier(value)}- itemComponent={(itemProps) => (- <SelectItem item={itemProps.item}>- {formatSubscriptionTier(itemProps.item.rawValue)}- </SelectItem>- )}- >- <SelectTrigger aria-label="Select AI credits per month">- <SelectValue<SubscriptionCredits>>- {formatSubscriptionTier(creditTier())}- <span class="text-xs text-muted-foreground">/mo</span>- </SelectValue>- </SelectTrigger>- <SelectPortal>- <SelectContent />- </SelectPortal>- </Select>+ <div role="radiogroup" aria-label="Plan" class="flex flex-col gap-2">+ <For each={PAID_PLANS}>+ {(option) => (+ <button+ role="radio"+ aria-checked={plan() === option}+ class="rounded-md border border-input p-3 flex items-center gap-2 font-normal transition-colors hover:bg-accent focus-ring"+ classList={{ "border-primary": plan() === option }}+ onClick={() => setPlan(option)}+ >+ <span class="flex min-w-0 flex-1 flex-col items-start gap-0.5">+ <span class="text-xs text-foreground">{PLANS[option].name}</span>+ <span class="text-xs text-muted-foreground">+ {formatCredits(PLANS[option].monthlyCredits)} credits/mo+ </span>+ </span>+ <span class="text-xs text-foreground">+ ${PLANS[option].monthlyPrice[billingPeriod()]}+ <span class="text-muted-foreground">/mo</span>+ </span>+ </button>+ )}+ </For>+ </div><div class="flex flex-col gap-2"><FeatureRow label="Monthly credit refill" /><FeatureRow label="Top up credits anytime" />- <FeatureRow label="Access to all pro models" />- <FeatureRow label="Priority feedback channel" />+ <FeatureRow label="Access to all AI models" />+ <Show when={plan() !== "pro"}>+ <FeatureRow label="Priority support" />+ </Show></div><Button class="w-full" disabled={loading()} onClick={handleUpgrade}>- Continue with Pro+ Continue with {PLANS[plan()].name}</Button></div>);@@ -202,7 +185,7 @@ function TopupContent() {onClick={() => setSelected(tier)}><span class="text-xs text-foreground">- {formatCredits(parseTopupCredits(tier))} credits+ {formatCredits(topupCredits(tier))} credits</span><span class="text-xs text-muted-foreground">${getTopupPrice(tier)}@@ -226,7 +209,7 @@ export function UpgradeDialog() {<Dialog open={open()} onOpenChange={setOpen}><DialogPortal><DialogContent class="sm:max-w-sm">- <Show when={auth.isPro()} fallback={<ProUpgradeContent />}>+ <Show when={auth.isSubscribed()} fallback={<ProUpgradeContent />}><TopupContent /></Show></DialogContent>diff --git a/apps/web/src/context/auth.tsx b/apps/web/src/context/auth.tsxindex daebf0e0..e4ec3e5a 100644--- a/apps/web/src/context/auth.tsx+++ b/apps/web/src/context/auth.tsx@@ -15,9 +15,11 @@ import {} from 'solid-js';import { toast } from 'somoto';import type { Session, User } from '@supabase/supabase-js';+import type { Account, Plan } from '@diffusionstudio/api-contract';import { supabase } from '@/lib/supabase';-import { backend, FREE_CREDITS_QUOTA, type UserData } from '@/lib/backend';+import { api } from '@/lib/api';+import { FREE_CREDITS } from '@/lib/checkout';import { identify, resetIdentity, track } from '@/lib/analytics';import { mainBridge } from '@/lib/ipc';import { MAIN_CHANNELS } from '@desktop/main-channels';@@ -30,37 +32,29 @@ type AuthContextValue = {user: Accessor<User | null>;isAuthenticated: Accessor<boolean>;isLoading: Accessor<boolean>;- accessLevel: Accessor<number>;+ plan: Accessor<Plan>;remainingCredits: Accessor<number>;creditLimit: Accessor<number>;nextCreditReset: Accessor<Date | null>;- isPro: Accessor<boolean>;- hasStripeCustomer: Accessor<boolean>;+ /** On any paid plan, legacy per-credit subscriptions included. */+ isSubscribed: Accessor<boolean>;+ /** Has billing details and invoices to show (a Stripe customer). */+ hasBillingAccount: Accessor<boolean>;productUpdatesEnabled: Accessor<boolean>;marketingAnnouncementsEnabled: Accessor<boolean>;signInWithOAuth: (provider: OAuthProvider) => Promise<void>;signInWithOtp: (email: string) => Promise<{ error: string | null }>;+ signInWithPassword: (email: string, password: string) => Promise<{ error: string | null }>;signOut: () => Promise<void>;deleteAccount: () => Promise<{ error: string | null }>;refreshSession: () => Promise<void>;+ /** Fetches the account again, after anything that changed it. */+ refreshAccount: () => void;};const AuthContext = createContext<AuthContextValue>();-type UserDataSubset = Pick<- UserData,- | 'lifetime_credit_balance'- | 'monthly_credit_balance'- | 'monthly_credit_quota'- | 'access_level'- | 'stripe_customer_id'- | 'last_credit_reset_at'- | 'product_updates_enabled'- | 'marketing_announcements_enabled'->;-const ELECTRON_AUTH_REDIRECT = 'https://app.diffusion.studio/auth/electron-callback.html';-const USER_DATA_QUERY = "lifetime_credit_balance,monthly_credit_balance,monthly_credit_quota,access_level,stripe_customer_id,last_credit_reset_at,product_updates_enabled,marketing_announcements_enabled" as const;export function AuthProvider(props: { children: JSX.Element }) {const [session, setSession] = createSignal<Session | null>(null);@@ -95,26 +89,26 @@ export function AuthProvider(props: { children: JSX.Element }) {- const [userData, { mutate: mutateUserData }] = createResource<UserDataSubset | null, string>(+ const [account, { refetch: refetchAccount }] = createResource<Account | null, string>(() => session()?.user.id,- async (userId) => {- if (!supabase) return null;-- const { data, error } = await supabase- .from('user_data')- .select(USER_DATA_QUERY)- .eq('id', userId)- .single();-- if (error) {- console.error('[auth] Failed to fetch user_data', error);+ async () => {+ try {+ return await api.account.get.query();+ } catch (err) {+ console.error('[auth] Failed to fetch the account', err);return null;}-- return data as UserDataSubset;},);+ const accountData = () => (session() ? account.latest ?? null : null)++ const refreshAccount = () => {+ if (session()) {+ refetchAccount();+ }+ }+onMount(() => {if (!window.desktop) return;// Must live in AuthProvider — ElectronProvider only mounts after sign-in,@@ -164,17 +158,19 @@ export function AuthProvider(props: { children: JSX.Element }) {table: 'user_data',filter: `id=eq.${userId}`,},- (payload) => mutateUserData(payload.new as UserDataSubset),+ refreshAccount,).subscribe();onCleanup(() => client.removeChannel(channel));});- const accessLevel = () => userData()?.access_level ?? 1;- const lifetimeCreditBalance = () => userData()?.lifetime_credit_balance ?? 0;- const monthlyCreditBalance = () => userData()?.monthly_credit_balance ?? 0;- const monthlyCreditQuota = () => userData()?.monthly_credit_quota ?? 0;+ onMount(() => {+ window.addEventListener('focus', refreshAccount);+ onCleanup(() => window.removeEventListener('focus', refreshAccount));+ });++ const plan = (): Plan => accountData()?.plan ?? 'free';const signInWithOAuth = async (provider: OAuthProvider) => {if (!supabase) return;@@ -231,6 +227,15 @@ export function AuthProvider(props: { children: JSX.Element }) {return { error: null };};+ const signInWithPassword = async (email: string, password: string): Promise<{ error: string | null }> => {+ if (!supabase) return { error: 'Auth is not configured' };++ track('sign_in_attempt', { method: 'password' });++ const { error } = await supabase.auth.signInWithPassword({ email, password });+ return { error: error?.message ?? null };+ };+const signOut = async () => {if (!supabase) return;@@ -247,7 +252,7 @@ export function AuthProvider(props: { children: JSX.Element }) {}try {- await backend.deleteAccount();+ await api.account.delete.mutate();track('account_deleted');// Sign out locally after successful server-side deletion@@ -269,28 +274,28 @@ export function AuthProvider(props: { children: JSX.Element }) {}};- const isPro = () => accessLevel() > 1;- const hasStripeCustomer = () => !!userData()?.stripe_customer_id;- const productUpdatesEnabled = () => userData()?.product_updates_enabled ?? true;- const marketingAnnouncementsEnabled = () => userData()?.marketing_announcements_enabled ?? true;- const remainingCredits = () => monthlyCreditBalance() + lifetimeCreditBalance();- const creditLimit = () => (isPro() ? monthlyCreditQuota() : FREE_CREDITS_QUOTA);+ const isSubscribed = () => plan() !== 'free';+ const hasBillingAccount = () => accountData()?.hasBillingAccount ?? false;+ const productUpdatesEnabled = () => accountData()?.emailPreferences.productUpdates ?? true;+ const marketingAnnouncementsEnabled = () => accountData()?.emailPreferences.marketingAnnouncements ?? true;+ const remainingCredits = () => {+ const credits = accountData()?.credits;+ return credits ? credits.monthly + credits.lifetime : 0;+ };+ const creditLimit = () => (isSubscribed() ? accountData()?.credits.quota ?? 0 : FREE_CREDITS);const nextCreditReset = (): Date | null => {- const last = userData()?.last_credit_reset_at;- if (!last) return null;- const next = new Date(last);- next.setMonth(next.getMonth() + 1);- return next;+ const next = accountData()?.nextResetAt;+ return next ? new Date(next) : null;};const ctx: AuthContextValue = {session,- isPro,- hasStripeCustomer,+ isSubscribed,+ hasBillingAccount,user: () => session()?.user ?? null,isAuthenticated: () => !!session(),isLoading,- accessLevel,+ plan,remainingCredits,creditLimit,nextCreditReset,@@ -298,9 +303,11 @@ export function AuthProvider(props: { children: JSX.Element }) {marketingAnnouncementsEnabled,signInWithOAuth,signInWithOtp,+ signInWithPassword,signOut,deleteAccount,refreshSession,+ refreshAccount,};return (diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsnew file mode 100644index 00000000..0423a789--- /dev/null+++ b/apps/web/src/lib/api.ts@@ -0,0 +1,41 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { createTRPCClient, httpBatchLink, TRPCClientError, type TRPCLink } from "@trpc/client";+import { observable } from "@trpc/server/observable";+import { supabase } from "./supabase";+import { showUpgradeDialog } from "@/components/upgrade-dialog";++import type { AppRouter } from "@diffusionstudio/api-contract";++/** Opens the upgrade dialog whenever a call fails for lack of credits. */+const paymentRequiredLink: TRPCLink<AppRouter> = () => ({ next, op }) =>+ observable((observer) => {+ const sub = next(op).subscribe({+ next: (value) => observer.next(value),+ error: (err) => {+ if (err instanceof TRPCClientError && err.data?.code === "PAYMENT_REQUIRED") {+ showUpgradeDialog();+ }+ observer.error(err);+ },+ complete: () => observer.complete(),+ });+ return () => sub.unsubscribe();+ });++/** The Diffusion Studio API (v2), authenticated with the Supabase session. */+export const api = createTRPCClient<AppRouter>({+ links: [+ paymentRequiredLink,+ httpBatchLink({+ url: `${import.meta.env.VITE_API_URL ?? ""}/api/v2/trpc`,+ async headers() {+ const session = await supabase?.auth.getSession();+ const token = session?.data.session?.access_token;+ return token ? { Authorization: `Bearer ${token}` } : {};+ },+ }),+ ],+});diff --git a/apps/web/src/lib/backend.ts b/apps/web/src/lib/backend.tsdeleted file mode 100644index 76512498..00000000--- a/apps/web/src/lib/backend.ts+++ /dev/null@@ -1,122 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--/**- * Stand-ins for the Diffusion Studio backend, which is being rebuilt. Every- * call the app used to make to it lands here: reads answer with empty mock- * data, and actions that need the server fail with `BackendUnavailableError`,- * so the screens that show them keep working until the new API is wired in.- * The Supabase database and auth are not part of this; they stay as they are.- */--export type BillingPeriod = "month" | "year";--export type SubscriptionCredits = "2_500" | "5_000" | "15_000" | "30_000" | "45_000";--export type TopupCredits = "1_000" | "2_000" | "5_000" | "10_000" | "25_000";--/** Credits a free account gets each month. */-export const FREE_CREDITS_QUOTA = 50;--/** Row shape of the Supabase `user_data` table. */-export type UserData = {- id: string;- lifetime_credit_balance: number;- monthly_credit_balance: number;- monthly_credit_quota: number;- access_level: number;- stripe_customer_id: string | null;- last_credit_reset_at: string | null;- product_updates_enabled: boolean;- marketing_announcements_enabled: boolean;-};--export type EmailPreferenceColumn = "product_updates_enabled" | "marketing_announcements_enabled";--export type SubscriptionSummary = {- amount: number;- currency: string;- billingPeriod: BillingPeriod;- currentPeriodEnd: number;-};--export type BillingInfo = {- email: string;- address: {- legalName: string;- line1: string;- line2: string;- city: string;- state: string;- postalCode: string;- country: string;- } | null;- taxId: string | null;- paymentMethod: {- brand: string;- last4: string;- expMonth: number;- expYear: number;- } | null;- billingPeriod: BillingPeriod | null;-};--export type Invoice = {- id: string;- status: "draft" | "open" | "paid" | "uncollectible" | "void" | null;- total: number;- currency: string;- dueDate: number;- hostedUrl: string | null;-};--export class BackendUnavailableError extends Error {- constructor(action: string) {- super(`${action} is not available yet.`);- this.name = "BackendUnavailableError";- }-}--export const backend = {- async getSubscriptionSummary(): Promise<SubscriptionSummary | null> {- return null;- },-- async getBillingInfo(): Promise<BillingInfo | null> {- return null;- },-- async listInvoices(): Promise<Invoice[]> {- return [];- },-- async createSubscription(_input: {- creditQuantity: SubscriptionCredits;- billingPeriod: BillingPeriod;- successUrl: string;- cancelUrl: string;- }): Promise<{ url: string }> {- throw new BackendUnavailableError("Checkout");- },-- async createTopup(_input: {- creditQuantity: TopupCredits;- successUrl: string;- cancelUrl: string;- }): Promise<{ url: string }> {- throw new BackendUnavailableError("Checkout");- },-- async createBillingPortal(): Promise<{ url: string }> {- throw new BackendUnavailableError("The billing portal");- },-- async updateEmailPreference(_input: { column: EmailPreferenceColumn; value: boolean }): Promise<{ success: boolean }> {- throw new BackendUnavailableError("Changing email preferences");- },-- async deleteAccount(): Promise<{ success: boolean }> {- throw new BackendUnavailableError("Deleting your account");- },-};diff --git a/apps/web/src/lib/checkout.ts b/apps/web/src/lib/checkout.tsindex 91d56285..9df05cd7 100644--- a/apps/web/src/lib/checkout.ts+++ b/apps/web/src/lib/checkout.ts@@ -4,28 +4,60 @@import { toast } from "somoto";-import { backend } from "./backend";+import { api } from "./api";import { mainBridge } from "./ipc";import { MAIN_CHANNELS } from "@desktop/main-channels";-import type { BillingPeriod, SubscriptionCredits, TopupCredits } from "./backend";+import type { BillingPeriod, PaidPlan, Plan, TopupCredits } from "@diffusionstudio/api-contract";function toastMessage(err: unknown, fallback: string): string {return err instanceof Error ? err.message : fallback;}-export const CREDIT_RATE = 0.01;-export const ANNUAL_DISCOUNT = 0.24;+/** Credits a new account gets once, at signup. */+export const FREE_CREDITS = 50;-export const SUBSCRIPTION_VOLUME_DISCOUNT: Record<SubscriptionCredits, number> = {- "2_500": 0,- "5_000": 0,- "15_000": 0.1,- "30_000": 0.15,- "45_000": 0.2,+type PlanOffer = {+ name: string;+ /** Credits granted every month, on monthly and yearly billing alike. */+ monthlyCredits: number;+ /** Display price per month (USD) for each billing period. */+ monthlyPrice: Record<BillingPeriod, number>;+};++/** The plans `billing.subscribe` sells. Prices mirror the Stripe prices the API looks up. */+export const PLANS: Record<PaidPlan, PlanOffer> = {+ pro: { name: "Pro", monthlyCredits: 2_500, monthlyPrice: { month: 25, year: 20 } },+ plus: { name: "Plus", monthlyCredits: 5_000, monthlyPrice: { month: 50, year: 35 } },+ max: { name: "Max", monthlyCredits: 15_000, monthlyPrice: { month: 150, year: 100 } },};-export const TOPUP_MARKUP: Record<TopupCredits, number> = {+export const PAID_PLANS = Object.keys(PLANS) as PaidPlan[];++/** USD a year of `plan` costs less when billed yearly. */+export function yearlySavings(plan: PaidPlan): number {+ const { month, year } = PLANS[plan].monthlyPrice;+ return (month - year) * 12;+}++/** The largest yearly discount across the plans, as a whole percentage. */+export const MAX_YEARLY_DISCOUNT = Math.max(+ ...PAID_PLANS.map((plan) => {+ const { month, year } = PLANS[plan].monthlyPrice;+ return Math.round((1 - year / month) * 100);+ }),+);++/** Display name of a plan. Legacy per-credit subscriptions were sold as Pro. */+export function planName(plan: Plan): string {+ if (plan === "free") return "Free";+ if (plan === "legacy") return "Pro";+ return PLANS[plan].name;+}++const CREDIT_RATE = 0.01;++const TOPUP_MARKUP: Record<TopupCredits, number> = {"1_000": 0.2,"2_000": 0.1,"5_000": 0,@@ -33,33 +65,15 @@ export const TOPUP_MARKUP: Record<TopupCredits, number> = {"25_000": 0,};-export const SUBSCRIPTION_CREDIT_TIERS = Object.keys(- SUBSCRIPTION_VOLUME_DISCOUNT,-) as SubscriptionCredits[];-export const TOPUP_CREDIT_TIERS = Object.keys(TOPUP_MARKUP) as TopupCredits[];-function parseCredits(tier: string): number {+export function topupCredits(tier: TopupCredits): number {return parseInt(tier.replace("_", ""), 10);}-/** Monthly display price (USD) for a subscription tier. */-export function getSubscriptionPrice(- tier: SubscriptionCredits,- billing: BillingPeriod,-): number {- const credits = parseCredits(tier);- const discount = SUBSCRIPTION_VOLUME_DISCOUNT[tier];- let price = credits * CREDIT_RATE * (1 - discount);- if (billing === "year") price *= 1 - ANNUAL_DISCOUNT;- return Math.round(price);-}-/** One-time topup price (USD) for a topup tier. */export function getTopupPrice(tier: TopupCredits): number {- const credits = parseCredits(tier);- const markup = TOPUP_MARKUP[tier];- return Math.round(credits * CREDIT_RATE * (1 + markup));+ return Math.round(topupCredits(tier) * CREDIT_RATE * (1 + TOPUP_MARKUP[tier]));}const ELECTRON_CHECKOUT_REDIRECT =@@ -90,11 +104,11 @@ async function openCheckoutUrl(url: string): Promise<void> {}export async function startSubscriptionCheckout(input: {- creditQuantity: SubscriptionCredits;+ plan: PaidPlan;billingPeriod: BillingPeriod;}): Promise<void> {try {- const { url } = await backend.createSubscription({+ const { url } = await api.billing.subscribe.mutate({...input,...successAndCancelUrls(),});@@ -108,7 +122,7 @@ export async function startTopupCheckout(creditQuantity: TopupCredits,): Promise<void> {try {- const { url } = await backend.createTopup({+ const { url } = await api.billing.topup.mutate({creditQuantity,...successAndCancelUrls(),});@@ -121,7 +135,7 @@ export async function startTopupCheckout(export async function openBillingPortal(): Promise<void> {if (window.desktop) {try {- const { url } = await backend.createBillingPortal();+ const { url } = await api.billing.portal.mutate();await mainBridge.call(MAIN_CHANNELS.APP_OPEN_EXTERNAL, { url });} catch (err) {toast.error(toastMessage(err, "Failed to open billing portal"));@@ -135,7 +149,7 @@ export async function openBillingPortal(): Promise<void> {if (!tab) return;try {- const { url } = await backend.createBillingPortal();+ const { url } = await api.billing.portal.mutate();tab.location.href = url;} catch (err) {tab.close();diff --git a/apps/web/src/pages/login.tsx b/apps/web/src/pages/login.tsxindex ecef0b50..7f86b2b2 100644--- a/apps/web/src/pages/login.tsx+++ b/apps/web/src/pages/login.tsx@@ -32,21 +32,45 @@ function OAuthButton(props: OAuthButtonProps) {);}+/**+ * Service and test accounts sign in with a password instead of a magic link:+ * plus-addressed mail on our own domain (`[email protected]`). Only we+ * can receive that mail, so nobody else can confirm an account that matches.+ * Password accounts are only ever created in the Supabase dashboard.+ */+const PASSWORD_ACCOUNT_EMAIL = /^[^@\s]+\+[^@\s]+@diffusion\.studio$/i;+export function LoginPage() {const auth = useAuth();const isFullscreen = useFullscreenState();const [email, setEmail] = createSignal('');- const [otpSending, setOtpSending] = createSignal(false);+ const [password, setPassword] = createSignal('');+ const [pending, setPending] = createSignal(false);++ const usesPassword = () => PASSWORD_ACCOUNT_EMAIL.test(email().trim());+ const canSubmit = () => !pending() && !!email().trim() && (!usesPassword() || !!password());++ const submitLabel = () => {+ if (usesPassword()) return pending() ? 'Signing in...' : 'Sign in';+ return pending() ? 'Sending...' : 'Send magic link';+ };- const handleOtpSubmit = async (e: SubmitEvent) => {+ const handleSubmit = async (e: SubmitEvent) => {e.preventDefault();+ if (!canSubmit()) return;const value = email().trim();- if (!value) return;+ setPending(true);++ if (usesPassword()) {+ const { error } = await auth.signInWithPassword(value, password());+ setPending(false);+ if (error) toast.error(error);+ return;+ }- setOtpSending(true);const { error } = await auth.signInWithOtp(value);- setOtpSending(false);+ setPending(false);if (error) {toast.error(error);@@ -55,6 +79,7 @@ export function LoginPage() {}};+return (<div class="flex flex-col bg-background fixed inset-0 z-999"><Show when={!!window.desktop && !isFullscreen()}>@@ -100,7 +125,7 @@ export function LoginPage() {</div></div>- <form class="flex flex-col gap-3" onSubmit={handleOtpSubmit}>+ <form class="flex flex-col gap-3" onSubmit={handleSubmit}><TextField><TextFieldLabeluiSize="compact"@@ -111,6 +136,7 @@ export function LoginPage() {<TextFieldInputuiSize="compact"type="email"+ autocomplete="username"placeholder="Enter your email"value={email()}onInput={(e) => setEmail(e.currentTarget.value)}@@ -119,12 +145,33 @@ export function LoginPage() {/></TextField>+ <Show when={usesPassword()}>+ <TextField>+ <TextFieldLabel+ uiSize="compact"+ class="text-xs text-muted-foreground"+ >+ Password+ </TextFieldLabel>+ <TextFieldInput+ uiSize="compact"+ type="password"+ autocomplete="current-password"+ placeholder="Enter your password"+ value={password()}+ onInput={(e) => setPassword(e.currentTarget.value)}+ onKeyDown={(e) => e.stopPropagation()}+ onKeyUp={(e) => e.stopPropagation()}+ />+ </TextField>+ </Show>+<Buttontype="submit"class="w-full"- disabled={otpSending() || !email().trim()}+ disabled={!canSubmit()}>- {otpSending() ? 'Sending...' : 'Send magic link'}+ {submitLabel()}</Button></form></div>diff --git a/package-lock.json b/package-lock.jsonindex 23229b13..fd64d47f 100644--- a/package-lock.json+++ b/package-lock.json@@ -107,6 +107,8 @@"@solid-primitives/resize-observer": "^2.1.3","@solidjs/router": "^0.15.4","@supabase/supabase-js": "^2.99.2",+ "@trpc/client": "^11.19.0",+ "@trpc/server": "^11.19.0","animejs": "^4.4.1","cmdk-solid": "^1.1.2","colord": "^2.9.3",@@ -4266,6 +4268,37 @@"node": ">= 10"}},+ "node_modules/@trpc/client": {+ "version": "11.19.0",+ "resolved": "https://registry.npmjs.org/@trpc/client/-/client-11.19.0.tgz",+ "integrity": "sha512-0MKkPq6MejsKB5Opca1Rl22KVIaqo2+A1EiXyZ8EGUsl9TLrPdpGn+Usux20TZKFwnSC2+wI/WilqNJaP4ODfw==",+ "funding": [+ "https://trpc.io/sponsor"+ ],+ "license": "MIT",+ "bin": {+ "intent": "bin/intent.js"+ },+ "peerDependencies": {+ "@trpc/server": "11.19.0",+ "typescript": ">=5.7.2"+ }+ },+ "node_modules/@trpc/server": {+ "version": "11.19.0",+ "resolved": "https://registry.npmjs.org/@trpc/server/-/server-11.19.0.tgz",+ "integrity": "sha512-7C1goiDurz82yFKtZUbEzjXd0Rg/jyisaIZQhdvus+1l7E6mwcEYZXjZ1US/HF8kOyz1LERL8UN3bcboJtjcyQ==",+ "funding": [+ "https://trpc.io/sponsor"+ ],+ "license": "MIT",+ "bin": {+ "intent": "bin/intent.js"+ },+ "peerDependencies": {+ "typescript": ">=5.7.2"+ }+ },"node_modules/@ts-morph/common": {"version": "0.29.0","resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.29.0.tgz",@@ -13128,7 +13161,6 @@"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz","integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "devOptional": true,"license": "Apache-2.0","bin": {"tsc": "bin/tsc",