Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(billing): show the no-card Business trial in the app (MUL-9485) (#10956)

Multica Evee16c89b6141b
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
index 251860df13..e651b5331b 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
@@ -87,6 +87,7 @@ vi.mock("@multica/views/search", () => ({
vi.mock("@multica/views/chat", () => ({ FloatingChat: () => null }));
vi.mock("@multica/views/star-prompt", () => ({ StarPrompt: () => null }));
vi.mock("@multica/views/whats-new", () => ({ WhatsNewDeck: () => null }));
+vi.mock("@multica/views/billing", () => ({ WorkspaceTrialNotices: () => null }));
vi.mock("./tab-bar", () => ({ TabBar: () => null }));
vi.mock("./window-overlay", () => ({ WindowOverlay: () => null }));
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 911a7c14f3..13f1926974 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -24,6 +24,7 @@ import {
import { SearchCommand } from "@multica/views/search";
import { FloatingChat } from "@multica/views/chat";
import { StarPrompt } from "@multica/views/star-prompt";
+import { WorkspaceTrialNotices } from "@multica/views/billing";
import { WhatsNewDeck } from "@multica/views/whats-new";
import { WorkspaceSlugProvider, useCurrentWorkspace } from "@multica/core/paths";
import { workspaceListOptions } from "@multica/core/workspace";
@@ -286,6 +287,7 @@ export function DesktopShell() {
click just froze until the destination committed
(MUL-6404). */}
<NavigationProgress />
+ {slug && <WorkspaceTrialNotices />}
<TabContent />
{slug && <FloatingChat />}
{slug && <StarPrompt />}
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
index f0d3884cf6..26e8c305c7 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
@@ -118,6 +118,7 @@ vi.mock("@multica/views/star-prompt", () => ({
StarPrompt: () => <div data-testid="star-prompt" />,
}));
vi.mock("@multica/views/whats-new", () => ({ WhatsNewDeck: () => null }));
+vi.mock("@multica/views/billing", () => ({ WorkspaceTrialNotices: () => null }));
vi.mock("./tab-bar", () => ({ TabBar: () => null }));
vi.mock("./window-overlay", () => ({ WindowOverlay: () => null }));
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index cf10aa2ea6..27c1c894b1 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -1632,6 +1632,7 @@ describe("workspace subscription contract", () => {
checkPlanChange: false,
});
expect(summary?.planChange).toBeNull();
+ expect(summary?.trial).toBeNull();
});
it("reads a plan change that still holds the subscription", async () => {
@@ -1689,6 +1690,64 @@ describe("workspace subscription contract", () => {
expect(summary?.planChange?.state ?? null).toBe(expected);
});
+ it("reads a no-card trial", async () => {
+ stubFetchJson({
+ entitlement: {
+ ...entitlement,
+ plan: "business",
+ status: "trialing",
+ current_period_end: "2026-12-19T08:00:00Z",
+ },
+ billing_interval: null,
+ human_members: 7,
+ seat_capacity: null,
+ cancel_at_period_end: false,
+ grace_until: null,
+ has_stripe_customer: false,
+ available_actions: { checkout: true, portal: false, purchase_seats: false },
+ trial: {
+ plan: "business",
+ state: "active",
+ started_at: "2026-12-05T08:00:00Z",
+ ends_at: "2026-12-19T08:00:00Z",
+ },
+ });
+ const client = new ApiClient("https://api.example.test");
+ const summary = await client.getWorkspaceSubscriptionSummary();
+
+ expect(summary?.entitlement.status).toBe("trialing");
+ expect(summary?.trial).toEqual({
+ plan: "business",
+ state: "active",
+ startedAt: "2026-12-05T08:00:00Z",
+ endsAt: "2026-12-19T08:00:00Z",
+ });
+ });
+
+ it.each([
+ ["absent (an older cloud)", undefined],
+ ["an unknown state", { plan: "business", state: "paused", started_at: "2026-12-05T08:00:00Z", ends_at: "2026-12-19T08:00:00Z" }],
+ ["an unparseable end", { plan: "business", state: "active", started_at: "2026-12-05T08:00:00Z", ends_at: "soon" }],
+ ["a missing plan", { state: "active", started_at: "2026-12-05T08:00:00Z", ends_at: "2026-12-19T08:00:00Z" }],
+ ])("reads %s trial as no trial without failing the summary", async (_name, trial) => {
+ stubFetchJson({
+ entitlement,
+ billing_interval: "month",
+ human_members: 3,
+ seat_capacity: null,
+ cancel_at_period_end: false,
+ grace_until: null,
+ has_stripe_customer: true,
+ available_actions: { checkout: false, portal: true, purchase_seats: false },
+ ...(trial === undefined ? {} : { trial }),
+ });
+ const client = new ApiClient("https://api.example.test");
+ const summary = await client.getWorkspaceSubscriptionSummary();
+
+ expect(summary).not.toBeNull();
+ expect(summary?.trial).toBeNull();
+ });
+
it("offers no plan switch when cloud does not report change_plan", async () => {
stubFetchJson({
entitlement,
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index f05ab6b81d..ee65c86aa3 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -3689,6 +3689,24 @@ export const WorkspaceSubscriptionSummarySchema = z
.nullable()
.optional()
.catch(null),
+ // Absent on a cloud that predates trials. A malformed value reads as no
+ // trial: the entitlement still carries the plan the workspace has.
+ trial: z
+ .object({
+ plan: z.string().min(1),
+ state: z.enum(["active", "expired", "converted"]),
+ started_at: z.string().min(1),
+ ends_at: z.string().min(1),
+ })
+ .loose()
+ .refine(
+ (value) =>
+ !Number.isNaN(Date.parse(value.started_at)) &&
+ !Number.isNaN(Date.parse(value.ends_at)),
+ )
+ .nullable()
+ .optional()
+ .catch(null),
})
.loose()
.transform(
@@ -3735,6 +3753,14 @@ export const WorkspaceSubscriptionSummarySchema = z
since: value.plan_change.since,
}
: null,
+ trial: value.trial
+ ? {
+ plan: value.trial.plan,
+ state: value.trial.state,
+ startedAt: value.trial.started_at,
+ endsAt: value.trial.ends_at,
+ }
+ : null,
}),
);
diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.ts
index 0dfbaf2b92..b7bd0218e8 100644
--- a/packages/core/billing/index.ts
+++ b/packages/core/billing/index.ts
@@ -4,3 +4,5 @@ export * from "./workspace-subscription-queries";
export * from "./workspace-subscription-mutations";
export * from "./recovery";
export * from "./paid-features";
+export * from "./trial";
+export * from "./trial-notice-store";
diff --git a/packages/core/billing/trial-clock.test.tsx b/packages/core/billing/trial-clock.test.tsx
new file mode 100644
index 0000000000..cd951299a2
--- /dev/null
+++ b/packages/core/billing/trial-clock.test.tsx
@@ -0,0 +1,45 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import { useWorkspaceTrial } from "./trial";
+import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+// This clock runs ahead of Cloud's, so both refetches around the end still read
+// the trial as active; the hook keeps asking until Cloud confirms.
+it("confirms expiry in an open tab when the browser clock is two minutes ahead", async () => {
+ vi.useFakeTimers();
+ const endsAt = Date.parse("2030-01-15T00:00:00Z");
+ vi.setSystemTime(endsAt - 1000);
+ const trial = { plan: "business", startedAt: "2030-01-01T00:00:00Z", endsAt: new Date(endsAt).toISOString() };
+ const active = { entitlement: { plan: "business", status: "trialing" }, trial: { ...trial, state: "active" } };
+ const expired = { entitlement: { plan: "free", status: "inactive" }, trial: { ...trial, state: "expired" } };
+ const clockOffset = 120_000;
+ const getWorkspaceSubscriptionSummary = vi.fn(async () =>
+ Date.now() - clockOffset < endsAt ? active : expired,
+ );
+ setApiInstance({ getWorkspaceSubscriptionSummary } as unknown as ApiClient);
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(workspaceSubscriptionKeys.summary("ws-clock"), active);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => useWorkspaceTrial("ws-clock", true), { wrapper });
+ try {
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(70_000); });
+ expect(result.current).toMatchObject({ kind: "ended", confirmed: false });
+ await act(async () => { await vi.advanceTimersByTimeAsync(60 * 60 * 1000); });
+ expect(result.current).toMatchObject({ kind: "ended", confirmed: true });
+ } finally {
+ qc.clear();
+ }
+});
diff --git a/packages/core/billing/trial-hook.test.tsx b/packages/core/billing/trial-hook.test.tsx
new file mode 100644
index 0000000000..db177817cf
--- /dev/null
+++ b/packages/core/billing/trial-hook.test.tsx
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import type { WorkspaceSubscriptionSummary } from "../types";
+import { useWorkspaceTrial } from "./trial";
+import { usePaidFeatureAccess, workspaceFeatureKeys } from "./paid-features";
+import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+// The server may cache the trial's Business policy for up to a minute past the
+// end; the hook refetches again once that window has passed.
+it("refreshes feature access after the last Business policy expires on the server", async () => {
+ vi.useFakeTimers();
+ const endsAt = Date.parse("2030-01-15T00:00:00Z");
+ vi.setSystemTime(endsAt - 1000);
+ const active = {
+ entitlement: { plan: "business", status: "trialing" },
+ trial: {
+ plan: "business", state: "active",
+ startedAt: "2030-01-01T00:00:00Z", endsAt: new Date(endsAt).toISOString(),
+ },
+ } as WorkspaceSubscriptionSummary;
+ // A policy read just before trial expiry is fresh for another minute.
+ const serverPolicyFreshUntil = endsAt + 59_000;
+ const getWorkspaceFeatures = vi.fn(async () => ({
+ features: { private_projects: Date.now() < serverPolicyFreshUntil ? "available" : "locked" },
+ }));
+ const getWorkspaceSubscriptionSummary = vi.fn(async () => Date.now() < endsAt ? active : ({
+ ...active, entitlement: { plan: "free", status: "inactive" },
+ trial: { ...active.trial, state: "expired" },
+ }));
+ setApiInstance({ getWorkspaceFeatures, getWorkspaceSubscriptionSummary } as unknown as ApiClient);
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(workspaceSubscriptionKeys.summary("ws-trial"), active);
+ qc.setQueryData(workspaceFeatureKeys.all("ws-trial"), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => ({
+ trial: useWorkspaceTrial("ws-trial", true),
+ access: usePaidFeatureAccess("ws-trial", "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(100); });
+ expect(result.current.trial.kind).toBe("ended");
+ expect(getWorkspaceFeatures).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(5 * 60 * 1000); });
+ expect(result.current.access.state).toBe("read_only");
+ qc.clear();
+});
+
+function trialSummary(state: "active" | "expired", endsAt: number): WorkspaceSubscriptionSummary {
+ return {
+ entitlement: state === "active"
+ ? { plan: "business", status: "trialing" }
+ : { plan: "free", status: "inactive" },
+ trial: {
+ plan: "business",
+ state,
+ startedAt: new Date(endsAt - 14 * 24 * 60 * 60 * 1000).toISOString(),
+ endsAt: new Date(endsAt).toISOString(),
+ },
+ } as WorkspaceSubscriptionSummary;
+}
+
+// A desktop window switches workspaces without remounting the shell. The
+// workspace switched to has to be read at the current time, and an end that
+// passed while it was not showing has to be caught up.
+it("reads a workspace switched to at the current time and catches up its missed end", async () => {
+ vi.useFakeTimers();
+ const start = Date.parse("2030-01-01T00:00:00Z");
+ vi.setSystemTime(start);
+ const otherEndsAt = start + 10 * 24 * 60 * 60 * 1000;
+ const endedAt = start + 10 * 60 * 1000;
+ const getWorkspaceSubscriptionSummary = vi.fn(async () => trialSummary("expired", endedAt));
+ const getWorkspaceFeatures = vi.fn(async () => ({ features: { private_projects: "locked" } }));
+ setApiInstance({ getWorkspaceFeatures, getWorkspaceSubscriptionSummary } as unknown as ApiClient);
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(workspaceSubscriptionKeys.summary("ws-a"), trialSummary("active", otherEndsAt));
+ // Read while ws-b's trial was still running.
+ qc.setQueryData(workspaceSubscriptionKeys.summary("ws-b"), trialSummary("active", endedAt));
+ qc.setQueryData(workspaceFeatureKeys.all("ws-b"), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, rerender } = renderHook(
+ ({ wsId }) => ({
+ trial: useWorkspaceTrial(wsId, true),
+ access: usePaidFeatureAccess(wsId, "private_projects", { hasExistingConfig: true }),
+ }),
+ { wrapper, initialProps: { wsId: "ws-a" } },
+ );
+ expect(result.current.trial.kind).toBe("active");
+
+ // Half an hour later, short of the hourly tick: ws-b ended 20 minutes ago.
+ vi.setSystemTime(start + 30 * 60 * 1000);
+ rerender({ wsId: "ws-b" });
+ await act(async () => { await vi.advanceTimersByTimeAsync(100); });
+ expect(result.current.trial).toMatchObject({ kind: "ended", confirmed: true, settled: false });
+ // Paid-feature reads settle a moment after Cloud's confirmation arrives.
+ await act(async () => { await vi.advanceTimersByTimeAsync(6_000); });
+
+ expect(result.current.trial).toMatchObject({ kind: "ended", settled: true });
+ expect(getWorkspaceSubscriptionSummary).toHaveBeenCalled();
+ expect(getWorkspaceFeatures).toHaveBeenCalled();
+ expect(result.current.access.state).toBe("read_only");
+ qc.clear();
+});
+
+it("does not refetch reads made after the end when a settled workspace shows again", async () => {
+ vi.useFakeTimers();
+ const endedAt = Date.parse("2030-01-01T00:00:00Z");
+ vi.setSystemTime(endedAt + 60 * 60 * 1000);
+ const getWorkspaceSubscriptionSummary = vi.fn(async () => trialSummary("expired", endedAt));
+ setApiInstance({ getWorkspaceSubscriptionSummary } as unknown as ApiClient);
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(workspaceSubscriptionKeys.summary("ws-c"), trialSummary("expired", endedAt));
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => useWorkspaceTrial("ws-c", true), { wrapper });
+ await act(async () => { await vi.advanceTimersByTimeAsync(6_000); });
+
+ expect(result.current).toMatchObject({ kind: "ended", settled: true });
+ expect(getWorkspaceSubscriptionSummary).not.toHaveBeenCalled();
+ qc.clear();
+});
diff --git a/packages/core/billing/trial-notice-store.ts b/packages/core/billing/trial-notice-store.ts
new file mode 100644
index 0000000000..f5a3503b21
--- /dev/null
+++ b/packages/core/billing/trial-notice-store.ts
@@ -0,0 +1,60 @@
+"use client";
+
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { defaultStorage } from "../platform/storage";
+import type { TrialReminderMilestone } from "./trial";
+
+/**
+ * The trial's one-time notices: the welcome card, each reminder, and the
+ * "trial ended" message. Each shows once per device.
+ */
+export type TrialNotice =
+ | "welcome"
+ | `reminder:${TrialReminderMilestone}`
+ | "ended";
+
+/** Keeps the persisted record small; old trials age out first. */
+const MAX_SEEN = 200;
+
+/**
+ * Keyed by workspace and the trial's end, so a later trial of the same
+ * workspace starts with nothing seen.
+ */
+export function trialNoticeKey(wsId: string, endsAt: number, notice: TrialNotice): string {
+ return `${wsId}:${endsAt}:${notice}`;
+}
+
+interface TrialNoticeState {
+ /** Seen notice keys, oldest first. */
+ seen: string[];
+ markSeen: (key: string) => void;
+}
+
+export const useTrialNoticeStore = create<TrialNoticeState>()(
+ persist(
+ (set) => ({
+ seen: [],
+ markSeen: (key) =>
+ set((state) =>
+ state.seen.includes(key)
+ ? state
+ : { seen: [...state.seen, key].slice(-MAX_SEEN) },
+ ),
+ }),
+ {
+ name: "multica_trial_notices",
+ storage: createJSONStorage(() => defaultStorage),
+ partialize: (state) => ({ seen: state.seen }),
+ merge: (persisted, current) => {
+ const saved = (persisted as { seen?: unknown } | undefined)?.seen;
+ return {
+ ...current,
+ seen: Array.isArray(saved)
+ ? saved.filter((key): key is string => typeof key === "string").slice(-MAX_SEEN)
+ : [],
+ };
+ },
+ },
+ ),
+);
diff --git a/packages/core/billing/trial-recovery.test.tsx b/packages/core/billing/trial-recovery.test.tsx
new file mode 100644
index 0000000000..b3259be94d
--- /dev/null
+++ b/packages/core/billing/trial-recovery.test.tsx
@@ -0,0 +1,384 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { focusManager, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import { createQueryClient } from "../query-client";
+import { usePaidFeatureAccess, workspaceFeatureKeys } from "./paid-features";
+import { useWorkspaceTrial } from "./trial";
+import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";
+
+afterEach(() => {
+ cleanup();
+ focusManager.setFocused(undefined);
+ vi.useRealTimers();
+});
+
+const endsAt = Date.parse("2030-01-15T00:00:00Z");
+const trial = {
+ plan: "business",
+ startedAt: "2030-01-01T00:00:00Z",
+ endsAt: new Date(endsAt).toISOString(),
+};
+const active = { entitlement: { plan: "business", status: "trialing" }, trial: { ...trial, state: "active" } };
+const expired = { entitlement: { plan: "free", status: "inactive" }, trial: { ...trial, state: "expired" } };
+const paid = { entitlement: { plan: "pro", status: "active" }, trial: null };
+const ws = "ws-trial-recovery";
+
+async function advance(ms: number) {
+ await act(async () => { await vi.advanceTimersByTimeAsync(ms); });
+}
+
+it("updates an open project's access when a refocus discovers a mid-trial Pro conversion", async () => {
+ vi.useFakeTimers();
+ const daySeven = endsAt - 7 * 24 * 60 * 60 * 1000;
+ const returnAt = daySeven + 6 * 60 * 1000;
+ vi.setSystemTime(daySeven);
+ const getWorkspaceFeatures = vi.fn(async () => ({
+ features: { private_projects: Date.now() < returnAt + 30_000 ? "available" : "locked" },
+ }));
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => paid,
+ getWorkspaceFeatures,
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ qc.setQueryData(workspaceSubscriptionKeys.summary(ws), active);
+ qc.setQueryData(workspaceFeatureKeys.all(ws), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => ({
+ trial: useWorkspaceTrial(ws, true),
+ access: usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ try {
+ expect(result.current.trial.kind).toBe("active");
+ // While this tab is in the background, an admin subscribes to Pro.
+ // On return both reads refresh. The product policy cache still has 30s left.
+ focusManager.setFocused(false);
+ await advance(returnAt - daySeven);
+ await act(async () => { focusManager.setFocused(true); });
+ await advance(10);
+ expect(result.current.trial.kind).toBe("none");
+ expect(getWorkspaceFeatures).toHaveBeenCalled();
+ await advance(60 * 60 * 1000);
+ expect(result.current.access.state).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// The backoff recheck keeps going through failed attempts, not only through
+// answers that are still active.
+it("recovers the expiry summary after the server briefly fails the scheduled recheck", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(endsAt - 1_000);
+ const attempts: number[] = [];
+ const getWorkspaceSubscriptionSummary = async () => {
+ const elapsed = Date.now() - endsAt;
+ attempts.push(elapsed);
+ // The browser is two minutes ahead. Both the first backoff request and
+ // React Query's normal retry hit a temporary service error.
+ if (elapsed >= 95_000 && elapsed < 110_000) throw new Error("HTTP 503");
+ return elapsed < 120_000 ? active : expired;
+ };
+ setApiInstance({ getWorkspaceSubscriptionSummary } as unknown as ApiClient);
+ const qc = createQueryClient();
+ qc.setQueryData(workspaceSubscriptionKeys.summary(ws), active);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => useWorkspaceTrial(ws, true), { wrapper });
+ try {
+ for (const ms of [1_000, 5, 69_995, 5, 30_000, 2_000, 60_000, 300_000, 3_600_000]) await advance(ms);
+ expect(attempts.some((time) => time >= 95_000 && time < 110_000)).toBe(true);
+ expect(result.current, JSON.stringify(attempts)).toMatchObject({ kind: "ended", confirmed: true });
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// A trial that converts at its end still gets the end's follow-up refetch: reads
+// made just before the end may hold the trial's Business features.
+it("refreshes Business-only feature access after a trial converts to Pro on another device", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(endsAt - 1_000);
+ // The Pro summary is already committed. A previously cached Business
+ // policy has half a second left when the local expiry timer fires.
+ const featureReads: number[] = [];
+ const getWorkspaceFeatures = async () => {
+ featureReads.push(Date.now() - endsAt);
+ return { features: { private_projects: Date.now() < endsAt + 500 ? "available" : "locked" } };
+ };
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => paid,
+ getWorkspaceFeatures,
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ qc.setQueryData(workspaceSubscriptionKeys.summary(ws), active);
+ qc.setQueryData(workspaceFeatureKeys.all(ws), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => ({
+ trial: useWorkspaceTrial(ws, true),
+ access: usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ try {
+ for (const ms of [1_000, 5, 70_000, 3_600_000]) await advance(ms);
+ expect(result.current.trial.kind).toBe("none");
+ expect(result.current.access.state, JSON.stringify(featureReads)).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// A desktop window switches workspaces without remounting. Switching to
+// another workspace's trial and back must not drop the refresh a mid-trial
+// conversion scheduled for this one.
+it("keeps a converted workspace's feature refresh across a workspace switch", async () => {
+ vi.useFakeTimers();
+ const t0 = endsAt - 7 * 24 * 60 * 60 * 1000;
+ vi.setSystemTime(t0);
+ const other = "ws-trial-other";
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => paid,
+ getWorkspaceFeatures: async () => ({
+ features: { private_projects: Date.now() < t0 + 60_000 ? "available" : "locked" },
+ }),
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ qc.setQueryData(workspaceSubscriptionKeys.summary(ws), active);
+ qc.setQueryData(workspaceSubscriptionKeys.summary(other), active);
+ qc.setQueryData(workspaceFeatureKeys.all(ws), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, rerender, unmount } = renderHook(
+ ({ wsId }) => ({
+ trial: useWorkspaceTrial(wsId, true),
+ access: usePaidFeatureAccess(wsId, "private_projects", { hasExistingConfig: true }),
+ }),
+ { wrapper, initialProps: { wsId: ws } },
+ );
+ try {
+ // This workspace's summary now reports Pro; the server still serves the
+ // trial's Business policy for another minute.
+ await act(async () => {
+ await qc.invalidateQueries({ queryKey: workspaceSubscriptionKeys.all(ws) });
+ });
+ await advance(10);
+ expect(result.current.trial.kind).toBe("none");
+
+ rerender({ wsId: other });
+ await advance(1_000);
+ rerender({ wsId: ws });
+ await advance(10_000);
+ expect(result.current.access.state).toBe("available");
+
+ await advance(80_000);
+ expect(result.current.access.state).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// Subscribed on another device while this tab was in the background: coming
+// back re-reads the plan (the summary is stale after 30 seconds), and the
+// paid-feature read made alongside it is refreshed once the server's cached
+// trial policy has expired.
+it("converges an open tab to Pro's access after a refocus shortly after conversion", async () => {
+ vi.useFakeTimers();
+ const t0 = endsAt - 7 * 24 * 60 * 60 * 1000;
+ vi.setSystemTime(t0);
+ const convertedAt = t0 + 30_000;
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => (Date.now() < convertedAt ? active : paid),
+ getWorkspaceFeatures: async () => ({
+ features: { private_projects: Date.now() < convertedAt + 60_000 ? "available" : "locked" },
+ }),
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ qc.setQueryData(workspaceSubscriptionKeys.summary(ws), active);
+ qc.setQueryData(workspaceFeatureKeys.all(ws), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => ({
+ trial: useWorkspaceTrial(ws, true),
+ access: usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ try {
+ focusManager.setFocused(false);
+ await advance(60_000);
+ await act(async () => { focusManager.setFocused(true); });
+ await advance(10);
+ expect(result.current.trial.kind).toBe("none");
+ await advance(10 * 60 * 1000);
+ expect(result.current.access.state).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// Opening the app just after the workspace converted: the summary already
+// says Pro, but the first paid-feature read may come from the server's cached
+// trial policy. The first read of the plan schedules one refresh too.
+it("converges a freshly opened app to Pro's access", async () => {
+ vi.useFakeTimers();
+ const t0 = endsAt - 7 * 24 * 60 * 60 * 1000;
+ vi.setSystemTime(t0);
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => paid,
+ getWorkspaceFeatures: async () => ({
+ features: { private_projects: Date.now() < t0 + 50_000 ? "available" : "locked" },
+ }),
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => ({
+ trial: useWorkspaceTrial(ws, true),
+ access: usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ try {
+ await advance(10);
+ expect(result.current.access.state).toBe("available");
+ await advance(10 * 60 * 1000);
+ expect(result.current.access.state).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// Coming back within the summary's stale time during a trial still re-reads
+// the plan: it may have been bought on another device a moment ago.
+it("re-reads the plan on refocus during a trial even while the summary is fresh", async () => {
+ vi.useFakeTimers();
+ const t0 = endsAt - 7 * 24 * 60 * 60 * 1000;
+ vi.setSystemTime(t0);
+ const convertedAt = t0 + 15_000;
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => (Date.now() < convertedAt ? active : paid),
+ getWorkspaceFeatures: async () => ({
+ features: { private_projects: Date.now() < convertedAt + 60_000 ? "available" : "locked" },
+ }),
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ qc.setQueryData(workspaceSubscriptionKeys.summary(ws), active);
+ qc.setQueryData(workspaceFeatureKeys.all(ws), { features: { private_projects: "available" } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => ({
+ trial: useWorkspaceTrial(ws, true),
+ access: usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ try {
+ focusManager.setFocused(false);
+ await advance(20_000);
+ await act(async () => { focusManager.setFocused(true); });
+ await advance(10);
+ expect(result.current.trial.kind).toBe("none");
+ await advance(10 * 60 * 1000);
+ expect(result.current.access.state).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// A paid-feature read that failed (first read, or the refresh after a plan
+// change) is asked again with backoff once the service recovers.
+it.each([
+ ["the first read", 0, 10_000],
+ ["the refresh after the plan change", 65_000, 80_000],
+] as const)("recovers paid-feature access when %s fails", async (_name, failFrom, failUntil) => {
+ vi.useFakeTimers();
+ const t0 = endsAt - 7 * 24 * 60 * 60 * 1000;
+ vi.setSystemTime(t0);
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => paid,
+ getWorkspaceFeatures: async () => {
+ const elapsed = Date.now() - t0;
+ if (elapsed >= failFrom && elapsed < failUntil) throw new Error("HTTP 503");
+ return { features: { private_projects: elapsed < 50_000 ? "available" : "locked" } };
+ },
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => ({
+ trial: useWorkspaceTrial(ws, true),
+ access: usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ }), { wrapper });
+ try {
+ // Step through ten minutes so renders between timers run, as in a page.
+ for (let i = 0; i < 60; i++) await advance(10_000);
+ expect(result.current.access.state).toBe("read_only");
+ } finally {
+ unmount();
+ qc.clear();
+ }
+});
+
+// A paid-feature read already in flight when the refresh runs (a project
+// opened a moment before), which then fails: the refresh waits for it and
+// retries with backoff instead of skipping it.
+it.each([
+ ["with an earlier answer cached", true],
+ ["with nothing cached", false],
+] as const)("retries a paid-feature read that was in flight at the refresh and then failed (%s)", async (_name, cached) => {
+ vi.useFakeTimers();
+ const t0 = endsAt - 7 * 24 * 60 * 60 * 1000;
+ vi.setSystemTime(t0);
+ setApiInstance({
+ getWorkspaceSubscriptionSummary: async () => paid,
+ getWorkspaceFeatures: async () => {
+ const startedAt = Date.now() - t0;
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ if (startedAt >= 69_000 && startedAt < 80_000) throw new Error("HTTP 503");
+ return { features: { private_projects: startedAt < 50_000 ? "available" : "locked" } };
+ },
+ } as unknown as ApiClient);
+ const qc = createQueryClient();
+ if (cached) {
+ qc.setQueryData(workspaceFeatureKeys.all(ws), { features: { private_projects: "available" } });
+ }
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ const shell = renderHook(() => useWorkspaceTrial(ws, true), { wrapper });
+ let unmountPage: (() => void) | null = null;
+ try {
+ await advance(10);
+ // The project opens at 69 s; its read is still in flight at the 70 s refresh.
+ await advance(69_000);
+ if (cached) {
+ await act(async () => {
+ await qc.invalidateQueries({ queryKey: workspaceFeatureKeys.all(ws) });
+ });
+ }
+ const page = renderHook(
+ () => usePaidFeatureAccess(ws, "private_projects", { hasExistingConfig: true }),
+ { wrapper },
+ );
+ unmountPage = page.unmount;
+ for (let i = 0; i < 60; i++) await advance(10_000);
+ expect(page.result.current.state).toBe("read_only");
+ } finally {
+ unmountPage?.();
+ shell.unmount();
+ qc.clear();
+ }
+});
diff --git a/packages/core/billing/trial.test.ts b/packages/core/billing/trial.test.ts
new file mode 100644
index 0000000000..e288e674c4
--- /dev/null
+++ b/packages/core/billing/trial.test.ts
@@ -0,0 +1,165 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { WorkspaceSubscriptionSummary, WorkspaceTrial } from "../types";
+import {
+ DAY_MS,
+ TRIAL_CONFIRM_SETTLE_MS,
+ TRIAL_END_SETTLE_MS,
+ resolveWorkspaceTrial,
+} from "./trial";
+
+const startedAt = Date.parse("2026-12-05T08:00:00Z");
+const endsAt = startedAt + 14 * DAY_MS;
+
+function summary(
+ trial: Partial<WorkspaceTrial> | null,
+ plan = trial?.state === "active" ? "business" : "free",
+): WorkspaceSubscriptionSummary {
+ return {
+ entitlement: {
+ workspaceId: "ws-1",
+ plan,
+ status: plan === "business" ? "trialing" : "inactive",
+ seats: 7,
+ limits: { autopilotRuns: { mode: "unlimited", limit: null } },
+ currentPeriodEnd: null,
+ snapshotExpiresAt: null,
+ version: 0,
+ },
+ billingInterval: null,
+ humanMembers: 7,
+ seatCapacity: null,
+ cancelAtPeriodEnd: false,
+ graceUntil: null,
+ hasStripeCustomer: false,
+ availableActions: {
+ checkout: true,
+ portal: false,
+ purchaseSeats: false,
+ changePlan: false,
+ checkPlanChange: false,
+ },
+ planChange: null,
+ trial: trial
+ ? {
+ plan: "business",
+ state: "active",
+ startedAt: new Date(startedAt).toISOString(),
+ endsAt: new Date(endsAt).toISOString(),
+ ...trial,
+ }
+ : null,
+ };
+}
+
+describe("resolveWorkspaceTrial", () => {
+ it("has nothing to show without a trial or after converting", () => {
+ expect(resolveWorkspaceTrial(null, startedAt)).toEqual({ kind: "none" });
+ expect(resolveWorkspaceTrial(summary(null), startedAt)).toEqual({ kind: "none" });
+ expect(
+ resolveWorkspaceTrial(summary({ state: "converted" }, "pro"), startedAt),
+ ).toEqual({ kind: "none" });
+ });
+
+ it.each([
+ // [elapsed, daysLeft, day, warning, reminder]
+ [0, 14, 1, false, null],
+ [6.5 * DAY_MS, 8, 7, false, null],
+ [7 * DAY_MS, 7, 8, false, 7],
+ [10.5 * DAY_MS, 4, 11, false, 7],
+ [11 * DAY_MS, 3, 12, true, 3],
+ [13 * DAY_MS + 1, 1, 14, true, 1],
+ [14 * DAY_MS - 1, 1, 14, true, 1],
+ ] as const)(
+ "counts whole days left from the end (%d ms in)",
+ (elapsed, daysLeft, day, warning, reminder) => {
+ const view = resolveWorkspaceTrial(summary({}), startedAt + elapsed);
+ expect(view).toMatchObject({
+ kind: "active",
+ daysLeft,
+ day,
+ totalDays: 14,
+ warning,
+ reminder,
+ });
+ },
+ );
+
+ it("reads a stale active summary as ended once the end has passed", () => {
+ expect(resolveWorkspaceTrial(summary({}), endsAt)).toEqual({
+ kind: "ended",
+ plan: "business",
+ endsAt,
+ recent: true,
+ // Only this clock says so; Cloud has not confirmed the downgrade.
+ confirmed: false,
+ settledAt: null,
+ settled: false,
+ });
+ expect(
+ resolveWorkspaceTrial(summary({ state: "expired" }), endsAt),
+ ).toMatchObject({ kind: "ended", confirmed: true });
+ });
+
+ it("offers the upgrade for a week after the end, then only on Billing", () => {
+ const expired = summary({ state: "expired" });
+ expect(resolveWorkspaceTrial(expired, endsAt + 7 * DAY_MS - 1)).toMatchObject({
+ kind: "ended",
+ recent: true,
+ });
+ expect(resolveWorkspaceTrial(expired, endsAt + 7 * DAY_MS)).toMatchObject({
+ kind: "ended",
+ recent: false,
+ });
+ });
+
+ it("settles after Cloud's confirmation, never before the end's own settle point", () => {
+ const expired = summary({ state: "expired" });
+ // Confirmed late (this clock behind Cloud's): settles shortly after.
+ const late = endsAt + 10 * 60 * 1000;
+ expect(resolveWorkspaceTrial(expired, late, late)).toMatchObject({
+ settledAt: late + TRIAL_CONFIRM_SETTLE_MS,
+ settled: false,
+ });
+ expect(
+ resolveWorkspaceTrial(expired, late + TRIAL_CONFIRM_SETTLE_MS, late),
+ ).toMatchObject({ settled: true });
+ // Confirmed right at the end: the end's settle point still applies.
+ expect(resolveWorkspaceTrial(expired, endsAt, endsAt)).toMatchObject({
+ settledAt: endsAt + TRIAL_END_SETTLE_MS,
+ });
+ });
+
+ it("settles once the server can no longer hold the trial's policy", () => {
+ const expired = summary({ state: "expired" });
+ expect(
+ resolveWorkspaceTrial(expired, endsAt + TRIAL_END_SETTLE_MS - 1),
+ ).toMatchObject({ kind: "ended", settled: false });
+ expect(
+ resolveWorkspaceTrial(expired, endsAt + TRIAL_END_SETTLE_MS),
+ ).toMatchObject({ kind: "ended", settled: true });
+ });
+
+ it("skips reminders a short trial never reaches", () => {
+ const short = summary({
+ endsAt: new Date(startedAt + 5 * DAY_MS).toISOString(),
+ });
+ expect(resolveWorkspaceTrial(short, startedAt)).toMatchObject({
+ kind: "active",
+ daysLeft: 5,
+ reminder: null,
+ });
+ });
+
+ it("ignores timestamps it cannot use", () => {
+ expect(
+ resolveWorkspaceTrial(summary({ endsAt: "not a date" }), startedAt),
+ ).toEqual({ kind: "none" });
+ expect(
+ resolveWorkspaceTrial(
+ summary({ endsAt: new Date(startedAt).toISOString() }),
+ startedAt,
+ ),
+ ).toEqual({ kind: "none" });
+ });
+});
diff --git a/packages/core/billing/trial.ts b/packages/core/billing/trial.ts
new file mode 100644
index 0000000000..f7b0ad7c84
--- /dev/null
+++ b/packages/core/billing/trial.ts
@@ -0,0 +1,416 @@
+import { useEffect, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import type { WorkspaceSubscriptionSummary } from "../types";
+import { autopilotKeys } from "../autopilots/queries";
+import { workspaceFeatureKeys } from "./paid-features";
+import {
+ workspaceSubscriptionKeys,
+ workspaceSubscriptionSummaryOptions,
+} from "./workspace-subscription-queries";
+
+/**
+ * The no-card Business trial (MUL-9485), as the app shell shows it.
+ *
+ * Cloud decides what the workspace is entitled to; this module only turns the
+ * trial's timestamps into what to show today. Days are counted from `endsAt`
+ * in whole 24-hour steps, so "3 days left" means less than 72 hours remain,
+ * whatever the viewer's timezone.
+ */
+
+export const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** The status bar turns to a warning for the last three days. */
+export const TRIAL_WARNING_DAYS = 3;
+
+/** After the trial ends, the status bar offers an upgrade for a week. */
+export const TRIAL_ENDED_VISIBLE_DAYS = 7;
+
+/**
+ * How long after the end the app refetches once more. The server may cache
+ * Cloud's enforcement policy for up to a minute, so a refetch exactly at the
+ * end can still read the trial's Business policy.
+ */
+export const TRIAL_END_SETTLE_MS = 70 * 1000;
+
+/**
+ * How long after Cloud first confirms the end paid-feature states are read
+ * again. Cloud stops serving the trial's policy at the end, give or take a
+ * second; this covers that and the viewer's clock being behind Cloud's.
+ */
+export const TRIAL_CONFIRM_SETTLE_MS = 5 * 1000;
+
+/**
+ * While this clock says the trial has ended but Cloud still reports it
+ * active (this clock runs ahead), the summary is asked again after these
+ * delays, the last one repeating.
+ */
+export const TRIAL_END_RECHECK_MS = [30_000, 60_000, 120_000, 300_000] as const;
+
+/**
+ * Owners and admins get one dismissible reminder at each of these points:
+ * halfway, three days left, and the last day.
+ */
+export const TRIAL_REMINDER_MILESTONES = [7, 3, 1] as const;
+export type TrialReminderMilestone = (typeof TRIAL_REMINDER_MILESTONES)[number];
+
+export type WorkspaceTrialView =
+ | { kind: "none" }
+ | {
+ kind: "active";
+ plan: string;
+ startedAt: number;
+ endsAt: number;
+ /** Whole days left, rounded up: 1 on the last day. */
+ daysLeft: number;
+ /** The current day of the trial, 1-based. */
+ day: number;
+ totalDays: number;
+ warning: boolean;
+ /** The reminder due now, if any; the caller tracks which were seen. */
+ reminder: TrialReminderMilestone | null;
+ }
+ | {
+ kind: "ended";
+ plan: string;
+ endsAt: number;
+ /** Within the week after the end, while the status bar still shows it. */
+ recent: boolean;
+ /**
+ * Cloud has said the trial expired and the workspace is on Free. Until
+ * then the end is only this clock's: the workspace may have subscribed
+ * elsewhere, so nothing may announce a downgrade yet.
+ */
+ confirmed: boolean;
+ /**
+ * From when paid-feature states and limits read are Free's: the later of
+ * TRIAL_END_SETTLE_MS after the end and TRIAL_CONFIRM_SETTLE_MS after
+ * Cloud's confirmation was received. Null until confirmed.
+ */
+ settledAt: number | null;
+ /** Confirmed, and past `settledAt`. */
+ settled: boolean;
+ };
+
+/**
+ * What to show for the workspace's trial at `now`. A summary that still says
+ * `active` after `endsAt` is stale: it reads as ended so the shell flips at
+ * the boundary while the refetch catches up.
+ */
+export function resolveWorkspaceTrial(
+ summary: WorkspaceSubscriptionSummary | null | undefined,
+ now: number,
+ /** When this client received Cloud's confirmation of the end, if known. */
+ confirmedAt?: number,
+): WorkspaceTrialView {
+ const trial = summary?.trial;
+ if (!trial || trial.state === "converted") return { kind: "none" };
+ const startedAt = Date.parse(trial.startedAt);
+ const endsAt = Date.parse(trial.endsAt);
+ if (Number.isNaN(startedAt) || Number.isNaN(endsAt) || endsAt <= startedAt) {
+ return { kind: "none" };
+ }
+ if (trial.state === "active" && now < endsAt) {
+ const totalDays = Math.max(1, Math.round((endsAt - startedAt) / DAY_MS));
+ const daysLeft = Math.max(1, Math.ceil((endsAt - now) / DAY_MS));
+ const day = Math.min(
+ totalDays,
+ Math.max(1, Math.floor((now - startedAt) / DAY_MS) + 1),
+ );
+ const reminder =
+ [...TRIAL_REMINDER_MILESTONES]
+ .reverse()
+ .find((milestone) => daysLeft <= milestone && milestone < totalDays) ??
+ null;
+ return {
+ kind: "active",
+ plan: trial.plan,
+ startedAt,
+ endsAt,
+ daysLeft,
+ day,
+ totalDays,
+ warning: daysLeft <= TRIAL_WARNING_DAYS,
+ reminder,
+ };
+ }
+ // A paid plan in effect means the trial no longer matters to the shell.
+ if (summary.entitlement.plan !== "free" && trial.state !== "active") {
+ return { kind: "none" };
+ }
+ const confirmed = trial.state === "expired" && summary.entitlement.plan === "free";
+ const settledAt = confirmed
+ ? Math.max(
+ endsAt + TRIAL_END_SETTLE_MS,
+ (confirmedAt ?? endsAt) + TRIAL_CONFIRM_SETTLE_MS,
+ )
+ : null;
+ return {
+ kind: "ended",
+ plan: trial.plan,
+ endsAt,
+ recent: now - endsAt < TRIAL_ENDED_VISIBLE_DAYS * DAY_MS,
+ confirmed,
+ settledAt,
+ settled: settledAt !== null && now >= settledAt,
+ };
+}
+
+/**
+ * After refetching paid-feature reads made before a plan change settled, a
+ * read that is still failing and on screen is asked again after these
+ * delays; then it is left to the next focus or mount.
+ */
+export const PAID_READ_RETRY_MS = [30_000, 60_000, 120_000, 300_000] as const;
+
+type QueryClientLike = ReturnType<typeof useQueryClient>;
+
+/**
+ * Refetch the workspace's paid-feature reads (feature states, autopilot
+ * usage) that were last answered before `boundary`, including ones that never
+ * answered at all, and keep retrying with backoff while one shown on screen
+ * still fails. Reads answered after `boundary` are current and left alone.
+ */
+async function refreshPaidReadsBefore(
+ qc: QueryClientLike,
+ wsId: string,
+ boundary: number,
+ wait: (ms: number) => Promise<void>,
+ isCancelled: () => boolean,
+): Promise<void> {
+ const keys = [workspaceFeatureKeys.all(wsId), autopilotKeys.usage(wsId)];
+ const outdated = (query: { state: { dataUpdatedAt: number } }) =>
+ query.state.dataUpdatedAt < boundary;
+ for (let attempt = 0; ; attempt++) {
+ // A read already in flight is awaited rather than restarted, so one that
+ // goes on to fail is still caught by the check below.
+ await Promise.all(
+ keys.map((queryKey) =>
+ qc.invalidateQueries({ queryKey, predicate: outdated }, { cancelRefetch: false }),
+ ),
+ );
+ if (isCancelled()) return;
+ const failing = keys.some((queryKey) =>
+ qc
+ .getQueryCache()
+ .findAll({ queryKey })
+ .some(
+ (query) =>
+ query.state.status === "error" &&
+ query.getObserversCount() > 0 &&
+ query.state.dataUpdatedAt < boundary,
+ ),
+ );
+ if (!failing || attempt >= PAID_READ_RETRY_MS.length) return;
+ await wait(PAID_READ_RETRY_MS[attempt]!);
+ if (isCancelled()) return;
+ }
+}
+
+/**
+ * Re-render often enough for day counts, and exactly when the trial ends.
+ */
+const TRIAL_CLOCK_TICK_MS = 60 * 60 * 1000;
+
+/**
+ * The trial view for a workspace, kept current. It re-renders hourly for the
+ * day count and, around the end, refetches everything the end changes (plan,
+ * paid-feature states, autopilot limit) instead of waiting for their stale
+ * times:
+ *
+ * - at the end on this clock, and TRIAL_END_SETTLE_MS later;
+ * - while Cloud still reports the trial active past that point (this clock
+ * runs ahead of Cloud's), the summary again with backoff until Cloud
+ * answers;
+ * - once Cloud confirms the end, at the view's `settledAt`.
+ *
+ * A boundary that passed while the workspace was not showing (another desktop
+ * tab's workspace, a closed window) is caught up when it shows again.
+ *
+ * `enabled` is the caller's billing gate; a self-hosted deployment never
+ * requests the summary.
+ */
+export function useWorkspaceTrial(
+ wsId: string,
+ enabled: boolean,
+): WorkspaceTrialView {
+ const qc = useQueryClient();
+ const summaryQuery = useQuery({
+ ...workspaceSubscriptionSummaryOptions(wsId),
+ enabled: enabled && wsId.length > 0,
+ // During a trial, coming back to the tab always re-reads the plan, even
+ // inside the stale time: it may have been bought on another device.
+ refetchOnWindowFocus: (query) =>
+ query.state.data?.trial?.state === "active" ? "always" : true,
+ });
+ const [now, setNow] = useState(() => Date.now());
+ const summary = enabled ? summaryQuery.data : null;
+ // Keyed on the end, not on the state, so the follow-up refetch survives the
+ // summary turning from active to expired at the first one.
+ const endsAtRaw =
+ summary?.trial && summary.trial.state !== "converted"
+ ? summary.trial.endsAt
+ : null;
+ const trialKey = endsAtRaw ? `${wsId}:${endsAtRaw}` : null;
+ // The last trial end this workspace showed. The end's refetches keep running
+ // when the summary stops carrying the trial (it converted to a paid plan on
+ // another device): reads made just before the end may still hold the
+ // trial's Business features.
+ //
+ // This and the records below are kept per workspace: a desktop window
+ // switches workspaces without remounting, and switching back must pick up
+ // the refetches the other workspace's trial would otherwise have replaced.
+ const [lastEnds, setLastEnds] = useState<Record<string, string>>({});
+ useEffect(() => {
+ if (!endsAtRaw || !wsId) return;
+ setLastEnds((current) =>
+ current[wsId] === endsAtRaw ? current : { ...current, [wsId]: endsAtRaw },
+ );
+ }, [endsAtRaw, wsId]);
+ const lastEnd = lastEnds[wsId] ?? null;
+ const boundaryEndRaw = endsAtRaw ?? lastEnd;
+
+ // When this client first saw the workspace's current plan, per workspace.
+ // Any plan change (subscribing mid-trial, possibly on another device) and a
+ // first read of the plan (opening the app just after one) may be followed
+ // by paid-feature reads the server answered from its cached previous policy
+ // for up to a minute, so those reads are refreshed once that has passed.
+ const planKey = summary
+ ? `${summary.entitlement.plan}|${summary.entitlement.status}|${summary.trial?.state ?? "-"}`
+ : null;
+ const [planSeen, setPlanSeen] = useState<Record<string, { plan: string; at: number }>>({});
+ const planSeenAt = planKey && planSeen[wsId]?.plan === planKey ? planSeen[wsId].at : undefined;
+ useEffect(() => {
+ if (!planKey || !wsId) return;
+ setPlanSeen((current) =>
+ current[wsId]?.plan === planKey
+ ? current
+ : { ...current, [wsId]: { plan: planKey, at: summaryQuery.dataUpdatedAt || Date.now() } },
+ );
+ }, [planKey, summaryQuery.dataUpdatedAt, wsId]);
+ useEffect(() => {
+ if (planSeenAt === undefined || !wsId) return;
+ const boundary = planSeenAt + TRIAL_END_SETTLE_MS;
+ let cancelled = false;
+ let timer: number | undefined;
+ const wait = (ms: number) =>
+ new Promise<void>((resolve) => {
+ timer = window.setTimeout(resolve, ms);
+ });
+ const run = async () => {
+ const delay = boundary - Date.now();
+ // A boundary that passed while this workspace was not showing is caught
+ // up now.
+ if (delay > 0) await wait(delay);
+ if (!cancelled) {
+ await refreshPaidReadsBefore(qc, wsId, boundary, wait, () => cancelled);
+ }
+ };
+ void run();
+ return () => {
+ cancelled = true;
+ if (timer !== undefined) window.clearTimeout(timer);
+ };
+ }, [planSeenAt, qc, wsId]);
+ const cloudSaysActive = summary?.trial?.state === "active";
+ const cloudConfirmsEnd =
+ summary?.trial?.state === "expired" && summary.entitlement.plan === "free";
+
+ // When this client first received Cloud's confirmation, per trial.
+ const [confirmations, setConfirmations] = useState<Record<string, number>>({});
+ const confirmedAt = trialKey ? confirmations[trialKey] : undefined;
+ useEffect(() => {
+ if (!cloudConfirmsEnd || !trialKey) return;
+ setConfirmations((current) =>
+ trialKey in current
+ ? current
+ : { ...current, [trialKey]: summaryQuery.dataUpdatedAt || Date.now() },
+ );
+ }, [cloudConfirmsEnd, summaryQuery.dataUpdatedAt, trialKey]);
+
+ useEffect(() => {
+ const id = window.setInterval(() => setNow(Date.now()), TRIAL_CLOCK_TICK_MS);
+ return () => window.clearInterval(id);
+ }, []);
+
+ useEffect(() => {
+ // A workspace switch reuses this hook: count from now, not from the
+ // previous workspace's last tick.
+ setNow(Date.now());
+ if (!boundaryEndRaw || !wsId) return;
+ const endsAt = Date.parse(boundaryEndRaw);
+ if (Number.isNaN(endsAt)) return;
+ const keys = [
+ workspaceSubscriptionKeys.all(wsId),
+ workspaceFeatureKeys.all(wsId),
+ autopilotKeys.usage(wsId),
+ ];
+ // Refetch what was read before `boundary`; reads made after it are current.
+ const refreshReadsBefore = (boundary: number, queryKeys = keys) => {
+ setNow(Date.now());
+ for (const queryKey of queryKeys) {
+ void qc.invalidateQueries({
+ queryKey,
+ predicate: (query) =>
+ query.state.dataUpdatedAt > 0 && query.state.dataUpdatedAt < boundary,
+ });
+ }
+ };
+ const boundaries: Array<{ at: number; keys: typeof keys }> = [
+ { at: endsAt, keys },
+ { at: endsAt + TRIAL_END_SETTLE_MS, keys },
+ ];
+ if (confirmedAt !== undefined) {
+ // The summary is already Cloud's answer; only policy-backed reads lag.
+ boundaries.push({ at: confirmedAt + TRIAL_CONFIRM_SETTLE_MS, keys: keys.slice(1) });
+ }
+ const timers: number[] = [];
+ for (const boundary of boundaries) {
+ const delay = boundary.at - Date.now();
+ if (delay <= 0) {
+ // Passed while this workspace was not showing: catch up now.
+ refreshReadsBefore(boundary.at, boundary.keys);
+ } else if (delay <= 2 ** 31 - 1) {
+ // setTimeout overflows past ~24.8 days, far beyond a trial.
+ timers.push(
+ window.setTimeout(() => refreshReadsBefore(boundary.at, boundary.keys), delay),
+ );
+ }
+ }
+ return () => timers.forEach((id) => window.clearTimeout(id));
+ }, [boundaryEndRaw, confirmedAt, qc, wsId]);
+
+ // This clock is past the end and its follow-up, yet Cloud still says
+ // active: ask again with backoff until Cloud answers otherwise.
+ const recheckAttempt = useRef<{ key: string; attempt: number } | null>(null);
+ useEffect(() => {
+ if (!cloudSaysActive || !endsAtRaw || !trialKey) {
+ recheckAttempt.current = null;
+ return;
+ }
+ const endsAt = Date.parse(endsAtRaw);
+ if (Number.isNaN(endsAt)) return;
+ const recheckFrom = endsAt + TRIAL_END_SETTLE_MS;
+ if (Date.now() < recheckFrom) return;
+ const attempt =
+ recheckAttempt.current?.key === trialKey ? recheckAttempt.current.attempt : 0;
+ recheckAttempt.current = { key: trialKey, attempt: attempt + 1 };
+ const delay =
+ TRIAL_END_RECHECK_MS[Math.min(attempt, TRIAL_END_RECHECK_MS.length - 1)]!;
+ const id = window.setTimeout(() => {
+ void qc.invalidateQueries({ queryKey: workspaceSubscriptionKeys.all(wsId) });
+ }, delay);
+ return () => window.clearTimeout(id);
+ // Each answer that is still active (a new dataUpdatedAt) and each failed
+ // attempt (a new errorUpdatedAt; the last answer stays cached) re-arm it.
+ }, [
+ cloudSaysActive,
+ endsAtRaw,
+ qc,
+ summaryQuery.dataUpdatedAt,
+ summaryQuery.errorUpdatedAt,
+ trialKey,
+ wsId,
+ ]);
+
+ return resolveWorkspaceTrial(summary, now, confirmedAt);
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 1a150ddee1..5162cde9a6 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -151,6 +151,7 @@
"./issue-views/edit-store": "./issue-views/edit-store.ts",
"./billing": "./billing/index.ts",
"./billing/recovery": "./billing/recovery.ts",
+ "./billing/trial": "./billing/trial.ts",
"./billing/queries": "./billing/queries.ts",
"./billing/mutations": "./billing/mutations.ts",
"./github": "./github/index.ts",
diff --git a/packages/core/session-prompt/index.ts b/packages/core/session-prompt/index.ts
index 03e6145401..c448f1200d 100644
--- a/packages/core/session-prompt/index.ts
+++ b/packages/core/session-prompt/index.ts
@@ -3,7 +3,7 @@
import { create } from "zustand";
/** Cards that slide into the bottom-right corner, which holds one at a time. */
-export type CornerCard = "whats-new" | "star";
+export type CornerCard = "whats-new" | "star" | "trial";
interface SessionPromptStore {
/**
diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.ts
index 33e6d8b9b0..a8a11d6c24 100644
--- a/packages/core/types/billing.ts
+++ b/packages/core/types/billing.ts
@@ -254,8 +254,28 @@ export interface WorkspaceSubscriptionSummary {
* purchases and other plan changes are unavailable.
*/
planChange: WorkspacePlanChangeHold | null;
+ /**
+ * The workspace's no-card trial. Null when it never had one, while a paid
+ * subscription is in effect, and on a cloud that predates trials.
+ */
+ trial: WorkspaceTrial | null;
+}
+
+/**
+ * A no-card trial of a paid plan. Only `active` grants the plan; the
+ * entitlement, not this object, decides access. Clients count days from
+ * `endsAt` and refresh when it passes.
+ */
+export interface WorkspaceTrial {
+ plan: string;
+ state: WorkspaceTrialState;
+ startedAt: string;
+ endsAt: string;
}
+/** `converted`: the trial ended because the workspace subscribed. */
+export type WorkspaceTrialState = "active" | "expired" | "converted";
+
export interface WorkspacePlanChangeHold {
targetPlan: string;
/**
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index c8b66740c7..14d03e418a 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -417,6 +417,8 @@ export type {
WorkspaceSubscriptionPlanPrices,
WorkspaceSubscriptionPrices,
WorkspacePlanChangeHold,
+ WorkspaceTrial,
+ WorkspaceTrialState,
CreateWorkspaceSubscriptionCheckoutRequest,
CreateWorkspaceSubscriptionCheckoutResponse,
PreviewWorkspaceSeatPurchaseRequest,
diff --git a/packages/views/billing/index.ts b/packages/views/billing/index.ts
index 17ae245206..3608bf2715 100644
--- a/packages/views/billing/index.ts
+++ b/packages/views/billing/index.ts
@@ -1,2 +1,4 @@
export { BillingReturnPage } from "./billing-return-page";
export { PaidFeatureNotice, usePaidFeatureErrorMessage } from "./paid-feature-notice";
+export { TrialStatus } from "./trial-status";
+export { WorkspaceTrialNotices } from "./trial-notices";
diff --git a/packages/views/billing/trial-notices-cloud.test.tsx b/packages/views/billing/trial-notices-cloud.test.tsx
new file mode 100644
index 0000000000..818183d658
--- /dev/null
+++ b/packages/views/billing/trial-notices-cloud.test.tsx
@@ -0,0 +1,48 @@
+import { act, cleanup } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, expect, it, vi } from "vitest";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { workspaceSubscriptionKeys, useTrialNoticeStore } from "@multica/core/billing";
+import { renderWithI18n } from "../test/i18n";
+import { WorkspaceTrialNotices } from "./trial-notices";
+
+const h = vi.hoisted(() => ({ toast: vi.fn() }));
+vi.mock("sonner", () => ({ toast: h.toast }));
+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => true }));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-member", name: "Test" }),
+}));
+vi.mock("@multica/core/permissions", () => ({
+ useCurrentMember: () => ({ role: "member", isLoading: false }),
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+// The real trial hook and query client, with Cloud's summary answering late:
+// the end on this clock is not a downgrade until Cloud says so.
+it("does not tell a member the workspace is Free if an admin subscribed on another device", async () => {
+ vi.useFakeTimers();
+ const endsAt = Date.parse("2030-01-15T00:00:00Z");
+ vi.setSystemTime(endsAt - 1000);
+ useTrialNoticeStore.setState({ seen: [] });
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const key = workspaceSubscriptionKeys.summary("ws-member");
+ qc.setQueryData(key, {
+ entitlement: { plan: "business", status: "trialing" },
+ trial: { plan: "business", state: "active", startedAt: "2030-01-01T00:00:00Z", endsAt: new Date(endsAt).toISOString() },
+ });
+ const paid = { entitlement: { plan: "pro", status: "active" }, trial: null };
+ const getWorkspaceSubscriptionSummary = vi.fn(() =>
+ new Promise(resolve => setTimeout(() => resolve(paid), 100)),
+ );
+ setApiInstance({ getWorkspaceSubscriptionSummary } as unknown as ApiClient);
+ renderWithI18n(<QueryClientProvider client={qc}><WorkspaceTrialNotices /></QueryClientProvider>);
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(200); });
+ expect(qc.getQueryData(key)).toEqual(paid);
+ expect(h.toast).not.toHaveBeenCalled();
+});
diff --git a/packages/views/billing/trial-notices.test.tsx b/packages/views/billing/trial-notices.test.tsx
new file mode 100644
index 0000000000..b21abea06c
--- /dev/null
+++ b/packages/views/billing/trial-notices.test.tsx
@@ -0,0 +1,352 @@
+import { act, fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WorkspaceTrialView } from "@multica/core/billing";
+import { useTrialNoticeStore } from "@multica/core/billing";
+import { useSessionPromptStore } from "@multica/core/session-prompt";
+import type { AutopilotQuotaUsage } from "@multica/core/types";
+import { renderWithI18n } from "../test/i18n";
+import { WorkspaceTrialNotices } from "./trial-notices";
+
+const DAY = 24 * 60 * 60 * 1000;
+// Ended trials in these tests ended two days ago, so they have settled.
+const ENDS_AT = Date.now() - 2 * DAY;
+
+const h = vi.hoisted(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { create } = require("zustand") as typeof import("zustand");
+ return {
+ trial: { kind: "none" } as WorkspaceTrialView,
+ workspace: { id: "ws-1", name: "Acme Labs" },
+ role: "owner" as "owner" | "admin" | "member" | null,
+ features: { private_projects: "available" } as Record<string, string>,
+ usage: null as AutopilotQuotaUsage | null,
+ /** The feature read failed after its retries. */
+ featuresFailed: false,
+ /** A failed feature read is being retried. */
+ featuresRetrying: false,
+ /** When the mocked feature and usage answers were received. */
+ dataUpdatedAt: Date.now(),
+ push: vi.fn(),
+ toast: vi.fn(),
+ chat: create<{ isOpen: boolean; floatingChatEnabled: boolean }>(() => ({
+ isOpen: false,
+ floatingChatEnabled: true,
+ })),
+ };
+});
+
+vi.mock("@multica/core/billing", async () => {
+ const actual = await vi.importActual<typeof import("@multica/core/billing")>("@multica/core/billing");
+ return { ...actual, useWorkspaceTrial: () => h.trial };
+});
+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => true }));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => h.workspace,
+ useWorkspacePaths: () => ({ settings: () => "/acme/settings", chat: () => "/acme/chat" }),
+}));
+vi.mock("@multica/core/permissions", () => ({
+ useCurrentMember: () => ({ userId: "u1", role: h.role, member: null, isLoading: false }),
+}));
+vi.mock("@multica/core/chat", () => ({ useChatStore: h.chat }));
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
+ return {
+ ...actual,
+ useQuery: (options: { queryKey: readonly unknown[] }) => {
+ const key = options.queryKey;
+ if (key[0] === "workspace-features") {
+ if (h.featuresFailed) {
+ return { data: undefined, isPending: false, isError: true, isFetching: h.featuresRetrying, dataUpdatedAt: 0 };
+ }
+ return { data: { features: h.features }, isPending: false, dataUpdatedAt: h.dataUpdatedAt };
+ }
+ if (key[key.length - 1] === "usage") {
+ return { data: h.usage, isPending: false, dataUpdatedAt: h.dataUpdatedAt };
+ }
+ return { data: undefined, isPending: true };
+ },
+ };
+});
+vi.mock("sonner", () => ({ toast: h.toast }));
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ pathname: "/acme/issues", push: h.push }),
+}));
+
+function active(overrides: Partial<Extract<WorkspaceTrialView, { kind: "active" }>> = {}): WorkspaceTrialView {
+ return {
+ kind: "active",
+ plan: "business",
+ startedAt: ENDS_AT - 14 * DAY,
+ endsAt: ENDS_AT,
+ daysLeft: 9,
+ day: 6,
+ totalDays: 14,
+ warning: false,
+ reminder: null,
+ ...overrides,
+ };
+}
+
+const ended: WorkspaceTrialView = {
+ kind: "ended",
+ plan: "business",
+ endsAt: ENDS_AT,
+ recent: true,
+ confirmed: true,
+ settledAt: ENDS_AT + 70_000,
+ settled: true,
+};
+
+beforeEach(() => {
+ h.trial = { kind: "none" };
+ h.workspace = { id: "ws-1", name: "Acme Labs" };
+ h.role = "owner";
+ h.features = { private_projects: "available" };
+ h.usage = null;
+ h.dataUpdatedAt = Date.now();
+ h.featuresFailed = false;
+ h.featuresRetrying = false;
+ h.push.mockReset();
+ h.toast.mockReset();
+ h.chat.setState({ isOpen: false, floatingChatEnabled: true });
+ useTrialNoticeStore.setState({ seen: [] });
+ useSessionPromptStore.setState({ corner: null });
+});
+
+describe("WorkspaceTrialNotices", () => {
+ it("preserves the owner's end notice until membership is known", () => {
+ h.role = null;
+ h.trial = ended;
+ const { rerender } = renderWithI18n(<WorkspaceTrialNotices />);
+ h.role = "owner";
+ rerender(<WorkspaceTrialNotices />);
+ expect.soft(h.toast).not.toHaveBeenCalled();
+ expect(screen.queryByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("shows nothing outside a trial or between reminders", () => {
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+
+ h.trial = active();
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ });
+
+ it("reminds owners and admins once per milestone", () => {
+ h.trial = active({ daysLeft: 3, warning: true, reminder: 3 });
+ const { unmount } = renderWithI18n(<WorkspaceTrialNotices />);
+
+ expect(screen.getByRole("status")).toHaveTextContent("3 days left in your Business trial.");
+ fireEvent.click(screen.getByRole("button", { name: "Later" }));
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ unmount();
+
+ // Seen on this device: a remount stays quiet until the next milestone.
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ });
+
+ it("opens Billing from the reminder", () => {
+ h.trial = active({ daysLeft: 7, reminder: 7 });
+ renderWithI18n(<WorkspaceTrialNotices />);
+
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "Your Business trial is halfway through: 7 days left.",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Choose a plan" }));
+ expect(h.push).toHaveBeenCalledWith("/acme/settings?tab=billing");
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ });
+
+ it("does not remind members", () => {
+ h.role = "member";
+ h.trial = active({ daysLeft: 1, warning: true, reminder: 1 });
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ });
+
+ it("welcomes everyone on the first day, once", () => {
+ h.role = "member";
+ h.trial = active({ daysLeft: 14, day: 1 });
+ const { unmount } = renderWithI18n(<WorkspaceTrialNotices />);
+
+ expect(
+ screen.getByRole("heading", { name: "Welcome! This workspace has a free 14-day Business trial" }),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
+ expect(screen.queryByRole("heading")).not.toBeInTheDocument();
+ expect(useSessionPromptStore.getState().corner).toBeNull();
+ unmount();
+
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("heading")).not.toBeInTheDocument();
+ });
+
+ it("leaves the corner to a card already showing there", () => {
+ useSessionPromptStore.setState({ corner: "whats-new" });
+ h.trial = active({ daysLeft: 14, day: 1 });
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("heading")).not.toBeInTheDocument();
+ });
+
+ it("shows the welcome once another corner card closes", () => {
+ useSessionPromptStore.setState({ corner: "whats-new" });
+ h.trial = active({ daysLeft: 14, day: 1 });
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("heading")).not.toBeInTheDocument();
+
+ act(() => useSessionPromptStore.getState().releaseCorner("whats-new"));
+ expect(
+ screen.getByRole("heading", { name: "Welcome! This workspace has a free 14-day Business trial" }),
+ ).toBeInTheDocument();
+ expect(useSessionPromptStore.getState().corner).toBe("trial");
+ });
+
+ it("waits for the end to settle before telling a manager what changed", () => {
+ h.trial = { ...ended, settled: false } as WorkspaceTrialView;
+ h.features = { private_projects: "locked" };
+ const { unmount } = renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ unmount();
+
+ // Settled, but the cached answers predate it: wait for fresh ones.
+ h.trial = ended;
+ h.dataUpdatedAt = ENDS_AT;
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(useTrialNoticeStore.getState().seen).toEqual([]);
+ });
+
+ it("tells a manager what changed, listing only restrictions in force", () => {
+ h.trial = ended;
+ h.features = { private_projects: "locked" };
+ h.usage = {
+ action: "enforce",
+ used: 1284,
+ reserved: 0,
+ total: 1284,
+ limit: 200,
+ reached: false,
+ period_start: null,
+ period_end: null,
+ reset_at: null,
+ blocked_counts: null,
+ };
+ renderWithI18n(<WorkspaceTrialNotices />);
+
+ const dialog = screen.getByRole("dialog", { name: "Your Business trial has ended" });
+ expect(dialog).toHaveTextContent("Acme Labs is now on Free. Nothing was deleted.");
+ expect(dialog).toHaveTextContent("Members, projects, and settings you already have stay as they are.");
+ expect(dialog).toHaveTextContent("Private projects stay private.");
+ expect(dialog).toHaveTextContent("Automations get 200 runs a month; 1,284 used this month.");
+
+ fireEvent.click(screen.getByRole("button", { name: "Continue on Free" }));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("opens on Cloud's confirmation even when a detail read failed", () => {
+ h.trial = ended;
+ h.featuresFailed = true;
+ h.usage = {
+ action: "enforce",
+ used: 12,
+ reserved: 0,
+ total: 12,
+ limit: 200,
+ reached: false,
+ period_start: null,
+ period_end: null,
+ reset_at: null,
+ blocked_counts: null,
+ };
+ renderWithI18n(<WorkspaceTrialNotices />);
+
+ const dialog = screen.getByRole("dialog", { name: "Your Business trial has ended" });
+ expect(dialog).toHaveTextContent("Automations get 200 runs a month; 12 used this month.");
+ expect(dialog).not.toHaveTextContent("Private projects");
+ });
+
+ it("stays open while a failed detail read is retried", () => {
+ h.trial = ended;
+ h.featuresFailed = true;
+ const { rerender } = renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+
+ h.featuresRetrying = true;
+ rerender(<WorkspaceTrialNotices />);
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+
+ h.featuresFailed = false;
+ h.features = { private_projects: "locked" };
+ rerender(<WorkspaceTrialNotices />);
+ expect(screen.getByRole("dialog")).toHaveTextContent("Private projects stay private.");
+ });
+
+ it("claims no restriction while limits are only observed", () => {
+ h.trial = ended;
+ h.usage = {
+ action: "observe",
+ used: 10,
+ reserved: 0,
+ total: 10,
+ limit: 200,
+ reached: false,
+ period_start: null,
+ period_end: null,
+ reset_at: null,
+ blocked_counts: null,
+ };
+ renderWithI18n(<WorkspaceTrialNotices />);
+
+ const dialog = screen.getByRole("dialog");
+ expect(dialog).not.toHaveTextContent("Private projects");
+ expect(dialog).not.toHaveTextContent("Automations");
+ });
+
+ it("tells members once with a toast", () => {
+ h.role = "member";
+ h.trial = ended;
+ const { unmount } = renderWithI18n(<WorkspaceTrialNotices />);
+ expect(h.toast).toHaveBeenCalledTimes(1);
+ expect(h.toast).toHaveBeenCalledWith("This workspace is now on Free", {
+ description: "Existing settings keep working. Ask a workspace admin if you need more.",
+ });
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ unmount();
+
+ act(() => {
+ renderWithI18n(<WorkspaceTrialNotices />);
+ });
+ expect(h.toast).toHaveBeenCalledTimes(1);
+ });
+
+ it("tells a member about each workspace that ended, across a workspace switch", () => {
+ h.role = "member";
+ h.trial = ended;
+ const { rerender } = renderWithI18n(<WorkspaceTrialNotices />);
+ expect(h.toast).toHaveBeenCalledTimes(1);
+
+ h.workspace = { id: "ws-2", name: "Pixel Forge" };
+ rerender(<WorkspaceTrialNotices />);
+ expect(h.toast).toHaveBeenCalledTimes(2);
+ });
+
+ it("announces nothing while only this clock says the trial ended", () => {
+ h.trial = { ...ended, confirmed: false } as WorkspaceTrialView;
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+
+ h.role = "member";
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(h.toast).not.toHaveBeenCalled();
+ expect(useTrialNoticeStore.getState().seen).toEqual([]);
+ });
+
+ it("stays quiet once the week after the end has passed", () => {
+ h.trial = { ...ended, recent: false } as WorkspaceTrialView;
+ renderWithI18n(<WorkspaceTrialNotices />);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(h.toast).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/billing/trial-notices.tsx b/packages/views/billing/trial-notices.tsx
new file mode 100644
index 0000000000..519b3129e1
--- /dev/null
+++ b/packages/views/billing/trial-notices.tsx
@@ -0,0 +1,341 @@
+"use client";
+
+import { useCallback, useEffect, useId, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { Bot, Hourglass, Lock, Sparkles, Users, X } from "@multica/ui/icons";
+import { autopilotQuotaUsageOptions } from "@multica/core/autopilots";
+import {
+ trialNoticeKey,
+ useTrialNoticeStore,
+ useWorkspaceTrial,
+ workspaceFeaturesOptions,
+ type TrialNotice,
+ type WorkspaceTrialView,
+} from "@multica/core/billing";
+import { useChatStore } from "@multica/core/chat";
+import { useFeatureEnabled } from "@multica/core/config";
+import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { useCurrentMember } from "@multica/core/permissions";
+import { useSessionPromptStore } from "@multica/core/session-prompt";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { isFloatingChatRouteSuppressed } from "../chat/floating-chat-visibility";
+import { useLocale, useT } from "../i18n";
+import { useNavigation } from "../navigation";
+
+type ActiveTrial = Extract<WorkspaceTrialView, { kind: "active" }>;
+type EndedTrial = Extract<WorkspaceTrialView, { kind: "ended" }>;
+
+function useNoticeSeen(wsId: string, endsAt: number, notice: TrialNotice) {
+ const key = trialNoticeKey(wsId, endsAt, notice);
+ const seen = useTrialNoticeStore((s) => s.seen.includes(key));
+ const markSeenKey = useTrialNoticeStore((s) => s.markSeen);
+ const markSeen = useCallback(() => markSeenKey(key), [key, markSeenKey]);
+ return [seen, markSeen] as const;
+}
+
+function formatDate(value: number, locale: string): string {
+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(value));
+}
+
+/**
+ * The trial's one-time notices (MUL-9485), mounted at the top of the content
+ * column so the reminder banner pushes the page down instead of covering it:
+ *
+ * - day 1: a welcome card in the corner, for everyone;
+ * - halfway, three days left and the last day: a dismissible banner for
+ * owners and admins;
+ * - after Cloud confirms the end: a dialog for owners and admins, a toast for
+ * members.
+ *
+ * Each shows once per device. Nothing here decides access; the server does.
+ */
+export function WorkspaceTrialNotices() {
+ const wsId = useCurrentWorkspace()?.id ?? "";
+ const enabled = useFeatureEnabled(BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG, false);
+ const trial = useWorkspaceTrial(wsId, enabled);
+ const { role, isLoading } = useCurrentMember(wsId);
+ // Who sees what depends on the role, and the notices are recorded as seen
+ // per device: wait until the role is known rather than guess "member".
+ if (!wsId || isLoading || role === null || trial.kind === "none") return null;
+ const isManager = role === "owner" || role === "admin";
+
+ if (trial.kind === "active") {
+ return (
+ <>
+ {isManager && trial.reminder !== null ? (
+ <TrialReminderBanner key={trial.reminder} wsId={wsId} trial={trial} />
+ ) : null}
+ {trial.day === 1 ? <TrialWelcomeCard wsId={wsId} trial={trial} /> : null}
+ </>
+ );
+ }
+ // Announce the downgrade only once Cloud confirms it: when this clock
+ // passes the end, the workspace may already have subscribed elsewhere.
+ if (!trial.recent || !trial.confirmed) return null;
+ if (!isManager) return <TrialEndedToast wsId={wsId} trial={trial} />;
+ // The dialog lists what is restricted now; until the end has settled, the
+ // server may still answer with the trial's Business policy.
+ return trial.settled ? <TrialEndedDialog wsId={wsId} trial={trial} /> : null;
+}
+
+function useOpenBilling() {
+ const navigation = useNavigation();
+ const paths = useWorkspacePaths();
+ return () => navigation.push(`${paths.settings()}?tab=billing`);
+}
+
+function TrialReminderBanner({ wsId, trial }: { wsId: string; trial: ActiveTrial }) {
+ const { t } = useT("billing");
+ const locale = useLocale();
+ const reminder = trial.reminder ?? 7;
+ const [seen, markSeen] = useNoticeSeen(wsId, trial.endsAt, `reminder:${reminder}`);
+ const openBilling = useOpenBilling();
+ if (seen) return null;
+
+ const title =
+ reminder === 7
+ ? t(($) => $.trial.reminder.halfway_title, { count: trial.daysLeft })
+ : reminder === 3
+ ? t(($) => $.trial.reminder.days_left_title, { count: trial.daysLeft })
+ : t(($) => $.trial.reminder.last_day_title);
+
+ return (
+ <section
+ role="status"
+ data-slot="trial-reminder"
+ className="mx-3 mt-3 flex shrink-0 flex-wrap items-center gap-x-3 gap-y-2 rounded-lg bg-warning/10 px-4 py-2.5 ring-1 ring-warning/30"
+ >
+ <Hourglass aria-hidden="true" className="size-4 shrink-0 text-warning" />
+ <p className="min-w-0 flex-1 text-body">
+ <span className="font-semibold">{title}</span>{" "}
+ <span className="text-muted-foreground">
+ {t(($) => $.trial.reminder.body, { date: formatDate(trial.endsAt, locale) })}
+ </span>
+ </p>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button variant="ghost" size="sm" onClick={markSeen}>
+ {t(($) => $.trial.reminder.later)}
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => {
+ markSeen();
+ openBilling();
+ }}
+ >
+ {t(($) => $.trial.reminder.choose_plan)}
+ </Button>
+ </div>
+ </section>
+ );
+}
+
+function TrialWelcomeCard({ wsId, trial }: { wsId: string; trial: ActiveTrial }) {
+ const { t } = useT("billing");
+ const titleId = useId();
+ const [seen, markSeen] = useNoticeSeen(wsId, trial.endsAt, "welcome");
+ const openBilling = useOpenBilling();
+ const chatOpen = useChatStore((s) => s.isOpen);
+ const floatingChatEnabled = useChatStore((s) => s.floatingChatEnabled);
+ const { pathname } = useNavigation();
+ const chatPath = useWorkspacePaths().chat();
+ const corner = useSessionPromptStore((s) => s.corner);
+ const launcherVisible =
+ floatingChatEnabled && !chatOpen && !isFloatingChatRouteSuppressed(pathname, chatPath);
+
+ // Claim the corner whenever it is free, including after another card that
+ // held it closes; give it back once seen or unmounted.
+ useEffect(() => {
+ const store = useSessionPromptStore.getState();
+ if (seen) store.releaseCorner("trial");
+ else if (corner === null) store.claimCorner("trial");
+ }, [corner, seen]);
+ useEffect(() => () => useSessionPromptStore.getState().releaseCorner("trial"), []);
+
+ // Another card holds the corner, or the chat window covers it.
+ if (seen || corner !== "trial" || chatOpen) return null;
+
+ return (
+ <section
+ aria-labelledby={titleId}
+ aria-live="polite"
+ data-slot="trial-welcome"
+ className={cn(
+ "absolute right-[var(--chat-launcher-inset)] z-50 w-[min(23.75rem,calc(100%-2*var(--chat-launcher-inset)))] rounded-xl bg-surface-raised p-4 pb-3 text-popover-foreground shadow-[var(--floating-shadow)] ring-1 ring-floating-border",
+ "animate-in fade-in-0 slide-in-from-bottom-2 duration-200 motion-reduce:animate-none",
+ launcherVisible ? "above-chat-launcher" : "bottom-[var(--chat-launcher-inset)]",
+ )}
+ >
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t(($) => $.trial.welcome.close)}
+ onClick={markSeen}
+ className="absolute top-2 right-2 text-muted-foreground"
+ >
+ <X />
+ </Button>
+ <div className="flex items-start gap-2 pr-6">
+ <Sparkles aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-brand" />
+ <div className="min-w-0">
+ <h2 id={titleId} className="text-body font-semibold">
+ {t(($) => $.trial.welcome.title, { count: trial.totalDays })}
+ </h2>
+ <p className="mt-1 text-label text-muted-foreground">{t(($) => $.trial.welcome.body)}</p>
+ </div>
+ </div>
+ <div className="mt-3 flex justify-end">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ markSeen();
+ openBilling();
+ }}
+ >
+ {t(($) => $.trial.welcome.action)}
+ </Button>
+ </div>
+ </section>
+ );
+}
+
+/**
+ * Lists only what is restricted right now. While limits are still observed
+ * rather than enforced, the end of the trial blocks nothing, and the dialog
+ * must not say otherwise.
+ */
+function TrialEndedDialog({ wsId, trial }: { wsId: string; trial: EndedTrial }) {
+ const { t } = useT("billing");
+ const locale = useLocale();
+ const workspaceName = useCurrentWorkspace()?.name ?? "";
+ const [seen, markSeen] = useNoticeSeen(wsId, trial.endsAt, "ended");
+ const openBilling = useOpenBilling();
+ // Read both again on mount and use only answers received after the end
+ // settled, so a cached Business answer never leaves a restriction out. The
+ // host renders this only once settled, so settledAt is set.
+ const settledAt = trial.settledAt ?? Number.POSITIVE_INFINITY;
+ const featuresQuery = useQuery({
+ ...workspaceFeaturesOptions(wsId),
+ enabled: !seen,
+ refetchOnMount: "always",
+ });
+ const usageQuery = useQuery({
+ ...autopilotQuotaUsageOptions(wsId),
+ enabled: !seen,
+ refetchOnMount: "always",
+ });
+ const current = (query: { isPending: boolean; dataUpdatedAt: number }) =>
+ !query.isPending && query.dataUpdatedAt >= settledAt;
+ // Cloud has confirmed the downgrade; the details only add to it. A detail
+ // read that failed does not hold the dialog back: it opens without that
+ // line, which appears if a later read succeeds while it is open.
+ const answered = (query: {
+ isPending: boolean;
+ isError: boolean;
+ isFetching: boolean;
+ dataUpdatedAt: number;
+ }) => current(query) || (query.isError && !query.isFetching);
+ const ready = answered(featuresQuery) && answered(usageQuery);
+ // Once open, it stays open while a detail read retries (on refocus, say);
+ // the retry only fills in its line.
+ const [opened, setOpened] = useState(false);
+ useEffect(() => {
+ if (ready) setOpened(true);
+ }, [ready]);
+ if (seen || !(opened || ready)) return null;
+
+ const count = new Intl.NumberFormat(locale);
+ const privateProjectsLocked =
+ current(featuresQuery) && featuresQuery.data?.features?.private_projects === "locked";
+ const usage = current(usageQuery) ? usageQuery.data : undefined;
+ const autopilotEnforced =
+ usage?.action === "enforce" && usage.limit !== null && usage.used !== null;
+
+ return (
+ <Dialog open onOpenChange={(open) => (open ? undefined : markSeen())}>
+ <DialogContent data-slot="trial-ended">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.trial.ended.title)}</DialogTitle>
+ <DialogDescription>
+ {workspaceName
+ ? t(($) => $.trial.ended.description, { workspace: workspaceName })
+ : t(($) => $.trial.ended.description_without_name)}
+ </DialogDescription>
+ </DialogHeader>
+ <ul className="space-y-2.5 text-body">
+ <li className="flex items-start gap-2.5">
+ <Users aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <span>{t(($) => $.trial.ended.kept)}</span>
+ </li>
+ {privateProjectsLocked ? (
+ <li className="flex items-start gap-2.5">
+ <Lock aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <span>{t(($) => $.trial.ended.private_projects)}</span>
+ </li>
+ ) : null}
+ {autopilotEnforced && usage ? (
+ <li className="flex items-start gap-2.5">
+ <Bot aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <span>
+ {usage.reached && usage.reset_at
+ ? t(($) => $.trial.ended.autopilot_paused, {
+ limit: count.format(usage.limit ?? 0),
+ used: count.format(usage.used ?? 0),
+ date: formatDate(Date.parse(usage.reset_at ?? ""), locale),
+ })
+ : t(($) => $.trial.ended.autopilot, {
+ limit: count.format(usage.limit ?? 0),
+ used: count.format(usage.used ?? 0),
+ })}
+ </span>
+ </li>
+ ) : null}
+ </ul>
+ <DialogFooter>
+ <Button variant="outline" onClick={markSeen}>
+ {t(($) => $.trial.ended.keep_free)}
+ </Button>
+ <Button
+ onClick={() => {
+ markSeen();
+ openBilling();
+ }}
+ >
+ {t(($) => $.trial.ended.upgrade)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function TrialEndedToast({ wsId, trial }: { wsId: string; trial: EndedTrial }) {
+ const { t } = useT("billing");
+ const [seen, markSeen] = useNoticeSeen(wsId, trial.endsAt, "ended");
+ // Per trial, not per mount: switching workspaces keeps this mounted.
+ const key = trialNoticeKey(wsId, trial.endsAt, "ended");
+ const shownFor = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (seen || shownFor.current === key) return;
+ shownFor.current = key;
+ markSeen();
+ toast(t(($) => $.trial.ended.member_title), {
+ description: t(($) => $.trial.ended.member_description),
+ });
+ }, [key, markSeen, seen, t]);
+
+ return null;
+}
diff --git a/packages/views/billing/trial-status.test.tsx b/packages/views/billing/trial-status.test.tsx
new file mode 100644
index 0000000000..8f1b799fdc
--- /dev/null
+++ b/packages/views/billing/trial-status.test.tsx
@@ -0,0 +1,115 @@
+import { screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WorkspaceTrialView } from "@multica/core/billing";
+import { NavigationProvider, type NavigationAdapter } from "../navigation";
+import { renderWithI18n } from "../test/i18n";
+import { TrialStatus } from "./trial-status";
+
+const h = vi.hoisted(() => ({
+ enabled: true,
+ trial: { kind: "none" } as WorkspaceTrialView,
+ calls: [] as Array<{ wsId: string; enabled: boolean }>,
+}));
+
+vi.mock("@multica/core/billing", () => ({
+ useWorkspaceTrial: (wsId: string, enabled: boolean) => {
+ h.calls.push({ wsId, enabled });
+ return h.trial;
+ },
+}));
+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => h.enabled }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),
+}));
+
+function renderStatus() {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/issues",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ };
+ return renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <TrialStatus wsId="ws-1" />
+ </NavigationProvider>,
+ );
+}
+
+function active(daysLeft: number, warning: boolean): WorkspaceTrialView {
+ return {
+ kind: "active",
+ plan: "business",
+ startedAt: 0,
+ endsAt: 14,
+ daysLeft,
+ day: 15 - daysLeft,
+ totalDays: 14,
+ warning,
+ reminder: null,
+ };
+}
+
+beforeEach(() => {
+ h.enabled = true;
+ h.trial = { kind: "none" };
+ h.calls = [];
+});
+
+describe("TrialStatus", () => {
+ it("counts down to Billing while the trial runs", () => {
+ h.trial = active(9, false);
+ renderStatus();
+
+ const link = screen.getByRole("link", { name: "Business trial, 9 days left. Open Billing." });
+ expect(link).toHaveAttribute("href", "/acme/settings?tab=billing");
+ expect(link).toHaveTextContent("Business trial9 days left");
+ expect(link).not.toHaveAttribute("data-warning");
+ });
+
+ it("warns for the last three days", () => {
+ h.trial = active(1, true);
+ renderStatus();
+
+ const link = screen.getByRole("link", { name: "Business trial, 1 day left. Open Billing." });
+ expect(link).toHaveAttribute("data-warning");
+ });
+
+ it("offers an upgrade for a week after the trial, then disappears", () => {
+ h.trial = { kind: "ended", plan: "business", endsAt: 0, recent: true, confirmed: true, settledAt: 70_000, settled: true };
+ const { unmount } = renderStatus();
+ expect(screen.getByRole("link")).toHaveTextContent("FreeUpgrade");
+ unmount();
+
+ h.trial = { kind: "ended", plan: "business", endsAt: 0, recent: false, confirmed: true, settledAt: 70_000, settled: true };
+ renderStatus();
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ });
+
+ it("says the trial is ending, not that the workspace is on Free, until Cloud confirms", () => {
+ h.trial = {
+ kind: "ended",
+ plan: "business",
+ endsAt: 0,
+ recent: true,
+ confirmed: false,
+ settledAt: null,
+ settled: false,
+ };
+ renderStatus();
+
+ const link = screen.getByRole("link", { name: "Business trial ending. Open Billing." });
+ expect(link).toHaveTextContent("Business trialending");
+ expect(link).not.toHaveTextContent("Free");
+ });
+
+ it("does not read billing where workspace subscriptions are off", () => {
+ h.enabled = false;
+ renderStatus();
+ expect(h.calls).toEqual([{ wsId: "ws-1", enabled: false }]);
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/billing/trial-status.tsx b/packages/views/billing/trial-status.tsx
new file mode 100644
index 0000000000..195fa729d8
--- /dev/null
+++ b/packages/views/billing/trial-status.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { Hourglass, Sparkles } from "@multica/ui/icons";
+import { useWorkspaceTrial } from "@multica/core/billing";
+import { useFeatureEnabled } from "@multica/core/config";
+import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+import { AppLink } from "../navigation";
+import { BOTTOM_BAR_ITEM_CLASS } from "../layout/bottom-bar-styles";
+
+/**
+ * The trial's place in the status bar (MUL-9485): a countdown while the
+ * Business trial runs, a warning for its last three days, and an upgrade
+ * entry for a week after it ends. Every member sees it; it opens Billing.
+ */
+export function TrialStatus({ wsId }: { wsId: string }) {
+ const { t } = useT("billing");
+ const paths = useWorkspacePaths();
+ const enabled = useFeatureEnabled(BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG, false);
+ const trial = useWorkspaceTrial(wsId, enabled);
+ const href = `${paths.settings()}?tab=billing`;
+
+ if (trial.kind === "active") {
+ const Icon = trial.warning ? Hourglass : Sparkles;
+ return (
+ <AppLink
+ href={href}
+ data-slot="trial-status"
+ data-warning={trial.warning ? "" : undefined}
+ aria-label={t(($) => $.trial.status.active_label, { count: trial.daysLeft })}
+ className={cn(
+ BOTTOM_BAR_ITEM_CLASS,
+ trial.warning
+ ? "bg-warning/10 text-warning hover:bg-warning/15 hover:text-warning"
+ : "bg-brand/10 text-brand hover:bg-brand/15 hover:text-brand",
+ )}
+ >
+ <Icon aria-hidden="true" />
+ <span className="font-medium text-foreground">{t(($) => $.trial.status.active)}</span>
+ <span className="truncate tabular-nums">
+ {t(($) => $.trial.status.days_left, { count: trial.daysLeft })}
+ </span>
+ </AppLink>
+ );
+ }
+
+ // Past the end on this clock, but Cloud has not confirmed it: the workspace
+ // may have subscribed, so say it is ending rather than that it is on Free.
+ if (trial.kind === "ended" && !trial.confirmed) {
+ return (
+ <AppLink
+ href={href}
+ data-slot="trial-status"
+ data-warning=""
+ aria-label={t(($) => $.trial.status.ending_label)}
+ className={cn(
+ BOTTOM_BAR_ITEM_CLASS,
+ "bg-warning/10 text-warning hover:bg-warning/15 hover:text-warning",
+ )}
+ >
+ <Hourglass aria-hidden="true" />
+ <span className="font-medium text-foreground">{t(($) => $.trial.status.active)}</span>
+ <span className="truncate">{t(($) => $.trial.status.ending)}</span>
+ </AppLink>
+ );
+ }
+
+ if (trial.kind === "ended" && trial.recent) {
+ return (
+ <AppLink
+ href={href}
+ data-slot="trial-status"
+ aria-label={t(($) => $.trial.status.ended_label)}
+ className={BOTTOM_BAR_ITEM_CLASS}
+ >
+ <Sparkles aria-hidden="true" className="text-brand" />
+ <span className="font-medium text-foreground">{t(($) => $.trial.status.free)}</span>
+ <span>{t(($) => $.trial.status.upgrade)}</span>
+ </AppLink>
+ );
+ }
+
+ return null;
+}
diff --git a/packages/views/layout/bottom-bar.test.tsx b/packages/views/layout/bottom-bar.test.tsx
index 1690e8085c..1ebc43950d 100644
--- a/packages/views/layout/bottom-bar.test.tsx
+++ b/packages/views/layout/bottom-bar.test.tsx
@@ -31,6 +31,7 @@ vi.mock("@multica/ui/hooks/use-mobile", () => ({ useIsMobile: () => h.isMobile }
vi.mock("./panels/team-status", () => ({ useTeamAgentStatus: () => h.team }));
vi.mock("./app-shell-context", () => ({ useAppShell: () => null }));
vi.mock("../chat/components/chat-bar", () => ({ ChatBar: () => <div data-testid="chat-bar" /> }));
+vi.mock("../billing/trial-status", () => ({ TrialStatus: () => null }));
function renderBar(pathname = "/acme/issues") {
const adapter: NavigationAdapter = {
diff --git a/packages/views/layout/bottom-bar.tsx b/packages/views/layout/bottom-bar.tsx
index 335f032fd4..f3f65e763b 100644
--- a/packages/views/layout/bottom-bar.tsx
+++ b/packages/views/layout/bottom-bar.tsx
@@ -4,6 +4,7 @@ import { TriangleAlert } from "@multica/ui/icons";
import { useChatStore } from "@multica/core/chat";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
+import { TrialStatus } from "../billing/trial-status";
import { ChatBar } from "../chat/components/chat-bar";
import { isFloatingChatRouteSuppressed } from "../chat/floating-chat-visibility";
import { useT } from "../i18n";
@@ -43,8 +44,8 @@ function TeamStatus({ wsId }: { wsId: string }) {
}
/**
- * The bar under the content card: workspace status on the left, quick chat on
- * the right. It sits on the app shell, in the strip the card's bottom margin
+ * The bar under the content card: workspace status (the plan trial, then
+ * stuck work) on the left, quick chat on the right. It sits on the app shell, in the strip the card's bottom margin
* used to take. Below `md` there is no bar and quick chat is the floating
* launcher.
*/
@@ -70,7 +71,10 @@ export function AppBottomBar() {
// column as the page header's trailing action.
className="hidden h-8 shrink-0 items-center justify-between gap-4 pr-[18px] pl-3 md:flex"
>
- <TeamStatus wsId={wsId} />
+ <div className="flex min-w-0 items-center gap-1">
+ <TrialStatus wsId={wsId} />
+ <TeamStatus wsId={wsId} />
+ </div>
{showChat && <ChatBar />}
</footer>
);
diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsx
index 07df7412d4..06d5423686 100644
--- a/packages/views/layout/dashboard-layout.tsx
+++ b/packages/views/layout/dashboard-layout.tsx
@@ -2,6 +2,7 @@
import type { ReactNode } from "react";
import { SidebarProvider } from "@multica/ui/components/ui/sidebar";
+import { WorkspaceTrialNotices } from "../billing/trial-notices";
import { AppearanceSync } from "../common/appearance-sync";
import { ModalRegistry } from "../modals/registry";
import { SourceBackfillModal } from "../onboarding";
@@ -71,6 +72,7 @@ export function DashboardLayout({
<div className="flex min-w-0 flex-1 flex-col">
<AppShellCard>
<NavigationProgress />
+ <WorkspaceTrialNotices />
{children}
<ModalRegistry />
<SourceBackfillModal />
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.json
index 42fc0106cf..c86b8c1e52 100644
--- a/packages/views/locales/en/billing.json
+++ b/packages/views/locales/en/billing.json
@@ -239,5 +239,70 @@
"unavailable": "Not included in this workspace's plan.",
"view_plans": "View plans",
"locked_error": "This isn't included in the workspace's plan. Existing settings keep working; upgrade to add more."
+ },
+ "trial": {
+ "status": {
+ "active": "Business trial",
+ "days_left_one": "{{count}} day left",
+ "days_left_other": "{{count}} days left",
+ "active_label_one": "Business trial, {{count}} day left. Open Billing.",
+ "active_label_other": "Business trial, {{count}} days left. Open Billing.",
+ "free": "Free",
+ "upgrade": "Upgrade",
+ "ended_label": "The Business trial has ended and this workspace is on Free. Open Billing to upgrade.",
+ "ending": "ending",
+ "ending_label": "Business trial ending. Open Billing."
+ },
+ "reminder": {
+ "halfway_title_one": "Your Business trial is halfway through: {{count}} day left.",
+ "halfway_title_other": "Your Business trial is halfway through: {{count}} days left.",
+ "days_left_title_one": "{{count}} day left in your Business trial.",
+ "days_left_title_other": "{{count}} days left in your Business trial.",
+ "last_day_title": "Your Business trial ends within a day.",
+ "body": "On {{date}} this workspace moves to Free. Choose a plan to keep Business.",
+ "later": "Later",
+ "choose_plan": "Choose a plan"
+ },
+ "welcome": {
+ "title_one": "Welcome! This workspace has a free {{count}}-day Business trial",
+ "title_other": "Welcome! This workspace has a free {{count}}-day Business trial",
+ "body": "Private projects and the other Business features are on. No card needed; the workspace moves to Free when the trial ends.",
+ "action": "See what's included",
+ "close": "Dismiss"
+ },
+ "ended": {
+ "title": "Your Business trial has ended",
+ "description": "{{workspace}} is now on Free. Nothing was deleted.",
+ "description_without_name": "This workspace is now on Free. Nothing was deleted.",
+ "kept": "Members, projects, and settings you already have stay as they are.",
+ "private_projects": "Private projects stay private. Their access lists are read-only until you upgrade.",
+ "autopilot": "Automations get {{limit}} runs a month; {{used}} used this month.",
+ "autopilot_paused": "Automations get {{limit}} runs a month and {{used}} were used this month, so they are paused until {{date}}.",
+ "keep_free": "Continue on Free",
+ "upgrade": "Upgrade to Business",
+ "member_title": "This workspace is now on Free",
+ "member_description": "Existing settings keep working. Ask a workspace admin if you need more."
+ },
+ "card": {
+ "title": "Business trial",
+ "badge_one": "Trial · {{count}} day left",
+ "badge_other": "Trial · {{count}} days left",
+ "description": "Trial until {{date}}. No payment method is on file, so the workspace moves to Free afterwards and is not charged.",
+ "started": "Started {{date}}",
+ "progress": "Day {{day}} of {{total}}",
+ "ends": "Ends {{date}}",
+ "ended_title": "Business trial ended",
+ "ended_description": "The trial ended on {{date}}. Choose a plan below to get Business features back.",
+ "choose_plan": "Choose a plan",
+ "ended_description_member": "The trial ended on {{date}}. Ask a workspace admin to upgrade to get Business features back."
+ },
+ "features": {
+ "title": "Business features in your trial",
+ "description": "When the trial ends nothing is deleted or turned off; you just can't add more.",
+ "private_projects": {
+ "name": "Private projects",
+ "after": "Stay private after the trial. Their access lists become read-only."
+ }
+ }
}
}
diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.json
index 400d3ca569..f236e83b05 100644
--- a/packages/views/locales/es/billing.json
+++ b/packages/views/locales/es/billing.json
@@ -239,5 +239,70 @@
"unavailable": "No está incluido en el plan de este espacio de trabajo.",
"view_plans": "Ver planes",
"locked_error": "No está incluido en el plan del espacio de trabajo. La configuración existente sigue funcionando; mejora el plan para añadir más."
+ },
+ "trial": {
+ "status": {
+ "active": "Prueba de Business",
+ "days_left_one": "queda {{count}} día",
+ "days_left_other": "quedan {{count}} días",
+ "active_label_one": "Prueba de Business, queda {{count}} día. Abrir Facturación.",
+ "active_label_other": "Prueba de Business, quedan {{count}} días. Abrir Facturación.",
+ "free": "Free",
+ "upgrade": "Actualizar",
+ "ended_label": "La prueba de Business terminó y este espacio de trabajo está en Free. Abre Facturación para actualizar.",
+ "ending": "termina ya",
+ "ending_label": "La prueba de Business está terminando. Abrir Facturación."
+ },
+ "reminder": {
+ "halfway_title_one": "Tu prueba de Business va por la mitad: queda {{count}} día.",
+ "halfway_title_other": "Tu prueba de Business va por la mitad: quedan {{count}} días.",
+ "days_left_title_one": "Queda {{count}} día de tu prueba de Business.",
+ "days_left_title_other": "Quedan {{count}} días de tu prueba de Business.",
+ "last_day_title": "Tu prueba de Business termina en menos de un día.",
+ "body": "El {{date}} este espacio de trabajo pasa a Free. Elige un plan para seguir con Business.",
+ "later": "Más tarde",
+ "choose_plan": "Elegir un plan"
+ },
+ "welcome": {
+ "title_one": "¡Bienvenido! Este espacio de trabajo tiene una prueba gratuita de Business de {{count}} día",
+ "title_other": "¡Bienvenido! Este espacio de trabajo tiene una prueba gratuita de Business de {{count}} días",
+ "body": "Los proyectos privados y las demás funciones de Business están activos. No hace falta tarjeta; al terminar la prueba, el espacio de trabajo pasa a Free.",
+ "action": "Ver qué incluye",
+ "close": "Cerrar"
+ },
+ "ended": {
+ "title": "Tu prueba de Business ha terminado",
+ "description": "{{workspace}} ahora está en Free. No se eliminó nada.",
+ "description_without_name": "Este espacio de trabajo ahora está en Free. No se eliminó nada.",
+ "kept": "Los miembros, proyectos y ajustes que ya tienes se mantienen igual.",
+ "private_projects": "Los proyectos privados siguen siendo privados. Sus listas de acceso son de solo lectura hasta que actualices.",
+ "autopilot": "Las automatizaciones tienen {{limit}} ejecuciones al mes; este mes se usaron {{used}}.",
+ "autopilot_paused": "Las automatizaciones tienen {{limit}} ejecuciones al mes y este mes se usaron {{used}}, así que están en pausa hasta el {{date}}.",
+ "keep_free": "Seguir en Free",
+ "upgrade": "Actualizar a Business",
+ "member_title": "Este espacio de trabajo ahora está en Free",
+ "member_description": "Los ajustes existentes siguen funcionando. Si necesitas más, pregunta a un administrador del espacio de trabajo."
+ },
+ "card": {
+ "title": "Prueba de Business",
+ "badge_one": "Prueba · queda {{count}} día",
+ "badge_other": "Prueba · quedan {{count}} días",
+ "description": "Prueba hasta el {{date}}. No hay método de pago registrado, así que después el espacio de trabajo pasa a Free y no se cobra nada.",
+ "started": "Empezó el {{date}}",
+ "progress": "Día {{day}} de {{total}}",
+ "ends": "Termina el {{date}}",
+ "ended_title": "La prueba de Business terminó",
+ "ended_description": "La prueba terminó el {{date}}. Elige un plan abajo para recuperar las funciones de Business.",
+ "choose_plan": "Elegir un plan",
+ "ended_description_member": "La prueba terminó el {{date}}. Pide a un administrador del espacio de trabajo que actualice el plan para recuperar las funciones de Business."
+ },
+ "features": {
+ "title": "Funciones de Business en tu prueba",
+ "description": "Al terminar la prueba no se elimina ni se desactiva nada; solo no podrás añadir más.",
+ "private_projects": {
+ "name": "Proyectos privados",
+ "after": "Siguen siendo privados después de la prueba. Sus listas de acceso pasan a solo lectura."
+ }
+ }
}
}
diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.json
index f3b6ac9e7e..8d8a81277d 100644
--- a/packages/views/locales/fr/billing.json
+++ b/packages/views/locales/fr/billing.json
@@ -239,5 +239,70 @@
"unavailable": "Non inclus dans le forfait de cet espace de travail.",
"view_plans": "Voir les forfaits",
"locked_error": "Non inclus dans le forfait de l'espace de travail. Les réglages existants restent actifs ; changez de forfait pour en ajouter."
+ },
+ "trial": {
+ "status": {
+ "active": "Essai Business",
+ "days_left_one": "{{count}} jour restant",
+ "days_left_other": "{{count}} jours restants",
+ "active_label_one": "Essai Business, {{count}} jour restant. Ouvrir la facturation.",
+ "active_label_other": "Essai Business, {{count}} jours restants. Ouvrir la facturation.",
+ "free": "Free",
+ "upgrade": "Mettre à niveau",
+ "ended_label": "L'essai Business est terminé et cet espace de travail est sur Free. Ouvrez la facturation pour mettre à niveau.",
+ "ending": "se termine",
+ "ending_label": "L'essai Business se termine. Ouvrir la facturation."
+ },
+ "reminder": {
+ "halfway_title_one": "Votre essai Business est à mi-parcours : {{count}} jour restant.",
+ "halfway_title_other": "Votre essai Business est à mi-parcours : {{count}} jours restants.",
+ "days_left_title_one": "Il reste {{count}} jour à votre essai Business.",
+ "days_left_title_other": "Il reste {{count}} jours à votre essai Business.",
+ "last_day_title": "Votre essai Business se termine dans moins d’un jour.",
+ "body": "Le {{date}}, cet espace de travail passe sur Free. Choisissez un forfait pour garder Business.",
+ "later": "Plus tard",
+ "choose_plan": "Choisir un forfait"
+ },
+ "welcome": {
+ "title_one": "Bienvenue ! Cet espace de travail bénéficie d’un essai gratuit de Business de {{count}} jour",
+ "title_other": "Bienvenue ! Cet espace de travail bénéficie d’un essai gratuit de Business de {{count}} jours",
+ "body": "Les projets privés et les autres fonctionnalités Business sont activés. Aucune carte n'est requise ; à la fin de l'essai, l'espace de travail passe sur Free.",
+ "action": "Voir ce qui est inclus",
+ "close": "Fermer"
+ },
+ "ended": {
+ "title": "Votre essai Business est terminé",
+ "description": "{{workspace}} est maintenant sur Free. Rien n'a été supprimé.",
+ "description_without_name": "Cet espace de travail est maintenant sur Free. Rien n'a été supprimé.",
+ "kept": "Les membres, projets et paramètres existants restent tels quels.",
+ "private_projects": "Les projets privés restent privés. Leurs listes d'accès sont en lecture seule jusqu'à la mise à niveau.",
+ "autopilot": "Les automatisations ont {{limit}} exécutions par mois ; {{used}} utilisées ce mois-ci.",
+ "autopilot_paused": "Les automatisations ont {{limit}} exécutions par mois et {{used}} ont été utilisées ce mois-ci : elles sont en pause jusqu'au {{date}}.",
+ "keep_free": "Rester sur Free",
+ "upgrade": "Passer à Business",
+ "member_title": "Cet espace de travail est maintenant sur Free",
+ "member_description": "Les paramètres existants continuent de fonctionner. Si vous avez besoin de plus, contactez un administrateur de l'espace de travail."
+ },
+ "card": {
+ "title": "Essai Business",
+ "badge_one": "Essai · {{count}} jour restant",
+ "badge_other": "Essai · {{count}} jours restants",
+ "description": "Essai jusqu'au {{date}}. Aucun moyen de paiement n'est enregistré : l'espace de travail passe ensuite sur Free sans être facturé.",
+ "started": "Commencé le {{date}}",
+ "progress": "Jour {{day}} sur {{total}}",
+ "ends": "Se termine le {{date}}",
+ "ended_title": "L'essai Business est terminé",
+ "ended_description": "L'essai s'est terminé le {{date}}. Choisissez un forfait ci-dessous pour retrouver les fonctionnalités Business.",
+ "choose_plan": "Choisir un forfait",
+ "ended_description_member": "L'essai s'est terminé le {{date}}. Demandez à un administrateur de l'espace de travail de mettre à niveau pour retrouver les fonctionnalités Business."
+ },
+ "features": {
+ "title": "Fonctionnalités Business de votre essai",
+ "description": "À la fin de l'essai, rien n'est supprimé ni désactivé ; vous ne pouvez simplement plus en ajouter.",
+ "private_projects": {
+ "name": "Projets privés",
+ "after": "Restent privés après l'essai. Leurs listes d'accès passent en lecture seule."
+ }
+ }
}
}
diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.json
index e41bea0a45..08525aa28c 100644
--- a/packages/views/locales/ja/billing.json
+++ b/packages/views/locales/ja/billing.json
@@ -233,5 +233,64 @@
"unavailable": "このワークスペースのプランには含まれていません。",
"view_plans": "プランを見る",
"locked_error": "このワークスペースのプランには含まれていません。既存の設定はそのまま有効です。追加するにはアップグレードしてください。"
+ },
+ "trial": {
+ "status": {
+ "active": "Business トライアル",
+ "days_left_other": "残り {{count}} 日",
+ "active_label_other": "Business トライアル、残り {{count}} 日。請求を開きます。",
+ "free": "Free",
+ "upgrade": "アップグレード",
+ "ended_label": "Business トライアルが終了し、このワークスペースは Free になりました。請求を開いてアップグレードします。",
+ "ending": "まもなく終了",
+ "ending_label": "Business トライアルはまもなく終了します。請求を開きます。"
+ },
+ "reminder": {
+ "halfway_title_other": "Business トライアルは折り返しを過ぎました。残り {{count}} 日です。",
+ "days_left_title_other": "Business トライアルは残り {{count}} 日です。",
+ "last_day_title": "Business トライアルは 1 日以内に終了します。",
+ "body": "{{date}} にこのワークスペースは Free に切り替わります。Business を続けるにはプランを選択してください。",
+ "later": "後で",
+ "choose_plan": "プランを選択"
+ },
+ "welcome": {
+ "title_other": "ようこそ!このワークスペースは Business を {{count}} 日間無料でお試しいただけます",
+ "body": "プライベートプロジェクトなどの Business 機能を利用できます。カード登録は不要で、終了後は自動的に Free に切り替わります。",
+ "action": "含まれる機能を見る",
+ "close": "閉じる"
+ },
+ "ended": {
+ "title": "Business トライアルが終了しました",
+ "description": "{{workspace}} は Free に切り替わりました。データは削除されていません。",
+ "description_without_name": "このワークスペースは Free に切り替わりました。データは削除されていません。",
+ "kept": "既存のメンバー、プロジェクト、設定はそのまま残ります。",
+ "private_projects": "プライベートプロジェクトは非公開のままです。アクセスリストはアップグレードするまで読み取り専用です。",
+ "autopilot": "自動化は月 {{limit}} 回まで。今月は {{used}} 回使用しました。",
+ "autopilot_paused": "自動化は月 {{limit}} 回までで、今月は {{used}} 回使用したため、{{date}} まで一時停止しています。",
+ "keep_free": "Free のまま使う",
+ "upgrade": "Business にアップグレード",
+ "member_title": "このワークスペースは Free になりました",
+ "member_description": "既存の設定はそのまま使えます。さらに機能が必要な場合はワークスペースの管理者に相談してください。"
+ },
+ "card": {
+ "title": "Business トライアル",
+ "badge_other": "トライアル中 · 残り {{count}} 日",
+ "description": "{{date}} までトライアル中です。支払い方法が登録されていないため、終了後は Free に切り替わり、請求は発生しません。",
+ "started": "{{date}} 開始",
+ "progress": "{{total}} 日中 {{day}} 日目",
+ "ends": "{{date}} 終了",
+ "ended_title": "Business トライアルが終了しました",
+ "ended_description": "トライアルは {{date}} に終了しました。下でプランを選択すると Business の機能が戻ります。",
+ "choose_plan": "プランを選択",
+ "ended_description_member": "トライアルは {{date}} に終了しました。Business の機能を戻すには、ワークスペースの管理者にアップグレードを依頼してください。"
+ },
+ "features": {
+ "title": "トライアル中の Business 機能",
+ "description": "トライアル終了後も削除や無効化はされません。新規作成や追加ができなくなるだけです。",
+ "private_projects": {
+ "name": "プライベートプロジェクト",
+ "after": "終了後も非公開のまま。アクセスリストは読み取り専用になります。"
+ }
+ }
}
}
diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.json
index 1e253a87a7..576934580f 100644
--- a/packages/views/locales/ko/billing.json
+++ b/packages/views/locales/ko/billing.json
@@ -233,5 +233,64 @@
"unavailable": "이 워크스페이스의 요금제에 포함되어 있지 않습니다.",
"view_plans": "요금제 보기",
"locked_error": "이 워크스페이스의 요금제에 포함되어 있지 않습니다. 기존 설정은 계속 적용되며, 추가하려면 업그레이드하세요."
+ },
+ "trial": {
+ "status": {
+ "active": "Business 체험",
+ "days_left_other": "{{count}}일 남음",
+ "active_label_other": "Business 체험, {{count}}일 남음. 결제 화면을 엽니다.",
+ "free": "Free",
+ "upgrade": "업그레이드",
+ "ended_label": "Business 체험이 끝나 이 워크스페이스는 Free로 전환되었습니다. 결제 화면을 열어 업그레이드하세요.",
+ "ending": "곧 종료",
+ "ending_label": "Business 체험이 곧 끝납니다. 결제 화면을 엽니다."
+ },
+ "reminder": {
+ "halfway_title_other": "Business 체험이 절반 지났습니다. {{count}}일 남았습니다.",
+ "days_left_title_other": "Business 체험이 {{count}}일 남았습니다.",
+ "last_day_title": "Business 체험이 하루 안에 끝납니다.",
+ "body": "{{date}}에 이 워크스페이스는 Free로 전환됩니다. Business를 계속 사용하려면 요금제를 선택하세요.",
+ "later": "나중에",
+ "choose_plan": "요금제 선택"
+ },
+ "welcome": {
+ "title_other": "환영합니다! 이 워크스페이스는 Business를 {{count}}일 동안 무료로 체험할 수 있습니다",
+ "body": "비공개 프로젝트 등 Business 기능을 사용할 수 있습니다. 카드 등록은 필요 없으며, 체험이 끝나면 자동으로 Free로 전환됩니다.",
+ "action": "포함된 기능 보기",
+ "close": "닫기"
+ },
+ "ended": {
+ "title": "Business 체험이 끝났습니다",
+ "description": "{{workspace}}이(가) Free로 전환되었습니다. 삭제된 데이터는 없습니다.",
+ "description_without_name": "이 워크스페이스가 Free로 전환되었습니다. 삭제된 데이터는 없습니다.",
+ "kept": "기존 멤버, 프로젝트, 설정은 그대로 유지됩니다.",
+ "private_projects": "비공개 프로젝트는 비공개로 유지됩니다. 접근 목록은 업그레이드 전까지 읽기 전용입니다.",
+ "autopilot": "자동화는 월 {{limit}}회이며, 이번 달 {{used}}회 사용했습니다.",
+ "autopilot_paused": "자동화는 월 {{limit}}회이며, 이번 달 {{used}}회 사용해 {{date}}까지 일시 중지되었습니다.",
+ "keep_free": "Free로 계속 사용",
+ "upgrade": "Business로 업그레이드",
+ "member_title": "이 워크스페이스는 Free로 전환되었습니다",
+ "member_description": "기존 설정은 그대로 동작합니다. 더 필요한 기능이 있으면 워크스페이스 관리자에게 문의하세요."
+ },
+ "card": {
+ "title": "Business 체험",
+ "badge_other": "체험 중 · {{count}}일 남음",
+ "description": "{{date}}까지 체험합니다. 결제 수단이 등록되어 있지 않으므로 체험 후 Free로 전환되며 요금이 청구되지 않습니다.",
+ "started": "{{date}} 시작",
+ "progress": "{{total}}일 중 {{day}}일째",
+ "ends": "{{date}} 종료",
+ "ended_title": "Business 체험이 끝났습니다",
+ "ended_description": "체험이 {{date}}에 끝났습니다. 아래에서 요금제를 선택하면 Business 기능을 다시 사용할 수 있습니다.",
+ "choose_plan": "요금제 선택",
+ "ended_description_member": "체험이 {{date}}에 끝났습니다. Business 기능을 다시 사용하려면 워크스페이스 관리자에게 업그레이드를 요청하세요."
+ },
+ "features": {
+ "title": "체험 중인 Business 기능",
+ "description": "체험이 끝나도 삭제되거나 꺼지지 않습니다. 새로 추가할 수만 없게 됩니다.",
+ "private_projects": {
+ "name": "비공개 프로젝트",
+ "after": "체험 후에도 비공개로 유지되며, 접근 목록은 읽기 전용이 됩니다."
+ }
+ }
}
}
diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.json
index 4389d0550a..4e0b161a41 100644
--- a/packages/views/locales/ru/billing.json
+++ b/packages/views/locales/ru/billing.json
@@ -251,5 +251,82 @@
"unavailable": "Не входит в тариф этого рабочего пространства.",
"view_plans": "Посмотреть тарифы",
"locked_error": "Не входит в тариф рабочего пространства. Существующие настройки продолжают работать; чтобы добавить новые, повысьте тариф."
+ },
+ "trial": {
+ "status": {
+ "active": "Пробный Business",
+ "days_left_one": "остался {{count}} день",
+ "days_left_few": "осталось {{count}} дня",
+ "days_left_many": "осталось {{count}} дней",
+ "days_left_other": "осталось {{count}} дня",
+ "active_label_one": "Пробный Business, остался {{count}} день. Открыть оплату.",
+ "active_label_few": "Пробный Business, осталось {{count}} дня. Открыть оплату.",
+ "active_label_many": "Пробный Business, осталось {{count}} дней. Открыть оплату.",
+ "active_label_other": "Пробный Business, осталось {{count}} дня. Открыть оплату.",
+ "free": "Free",
+ "upgrade": "Повысить тариф",
+ "ended_label": "Пробный период Business закончился, рабочее пространство перешло на Free. Откройте оплату, чтобы сменить тариф.",
+ "ending": "заканчивается",
+ "ending_label": "Пробный Business заканчивается. Открыть оплату."
+ },
+ "reminder": {
+ "halfway_title_one": "Пробный период Business прошёл наполовину: остался {{count}} день.",
+ "halfway_title_few": "Пробный период Business прошёл наполовину: осталось {{count}} дня.",
+ "halfway_title_many": "Пробный период Business прошёл наполовину: осталось {{count}} дней.",
+ "halfway_title_other": "Пробный период Business прошёл наполовину: осталось {{count}} дня.",
+ "days_left_title_one": "До конца пробного Business остался {{count}} день.",
+ "days_left_title_few": "До конца пробного Business осталось {{count}} дня.",
+ "days_left_title_many": "До конца пробного Business осталось {{count}} дней.",
+ "days_left_title_other": "До конца пробного Business осталось {{count}} дня.",
+ "last_day_title": "Пробный период Business закончится меньше чем через сутки.",
+ "body": "{{date}} рабочее пространство перейдёт на Free. Выберите тариф, чтобы сохранить Business.",
+ "later": "Позже",
+ "choose_plan": "Выбрать тариф"
+ },
+ "welcome": {
+ "title_one": "Добро пожаловать! В этом рабочем пространстве действует бесплатный пробный Business на {{count}} день",
+ "title_few": "Добро пожаловать! В этом рабочем пространстве действует бесплатный пробный Business на {{count}} дня",
+ "title_many": "Добро пожаловать! В этом рабочем пространстве действует бесплатный пробный Business на {{count}} дней",
+ "title_other": "Добро пожаловать! В этом рабочем пространстве действует бесплатный пробный Business на {{count}} дня",
+ "body": "Приватные проекты и другие функции Business включены. Карта не нужна; после пробного периода рабочее пространство перейдёт на Free.",
+ "action": "Что входит",
+ "close": "Закрыть"
+ },
+ "ended": {
+ "title": "Пробный период Business закончился",
+ "description": "{{workspace}} теперь на Free. Ничего не удалено.",
+ "description_without_name": "Рабочее пространство теперь на Free. Ничего не удалено.",
+ "kept": "Участники, проекты и настройки остаются как есть.",
+ "private_projects": "Приватные проекты остаются приватными. Их списки доступа доступны только для чтения до смены тарифа.",
+ "autopilot": "Автоматизациям доступно {{limit}} запусков в месяц; в этом месяце использовано {{used}}.",
+ "autopilot_paused": "Автоматизациям доступно {{limit}} запусков в месяц, в этом месяце использовано {{used}}, поэтому они приостановлены до {{date}}.",
+ "keep_free": "Остаться на Free",
+ "upgrade": "Перейти на Business",
+ "member_title": "Рабочее пространство теперь на Free",
+ "member_description": "Существующие настройки продолжают работать. Если нужно больше, обратитесь к администратору рабочего пространства."
+ },
+ "card": {
+ "title": "Пробный Business",
+ "badge_one": "Пробный · остался {{count}} день",
+ "badge_few": "Пробный · осталось {{count}} дня",
+ "badge_many": "Пробный · осталось {{count}} дней",
+ "badge_other": "Пробный · осталось {{count}} дня",
+ "description": "Пробный период до {{date}}. Способ оплаты не указан, поэтому после этого рабочее пространство перейдёт на Free без списаний.",
+ "started": "Начало: {{date}}",
+ "progress": "День {{day}} из {{total}}",
+ "ends": "Окончание: {{date}}",
+ "ended_title": "Пробный период Business закончился",
+ "ended_description": "Пробный период закончился {{date}}. Выберите тариф ниже, чтобы вернуть функции Business.",
+ "choose_plan": "Выбрать тариф",
+ "ended_description_member": "Пробный период закончился {{date}}. Чтобы вернуть функции Business, попросите администратора рабочего пространства сменить тариф."
+ },
+ "features": {
+ "title": "Функции Business в пробном периоде",
+ "description": "После окончания пробного периода ничего не удаляется и не отключается; просто нельзя будет добавлять новое.",
+ "private_projects": {
+ "name": "Приватные проекты",
+ "after": "Остаются приватными после пробного периода. Списки доступа становятся доступны только для чтения."
+ }
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.json
index a6b6a6c869..3b2076ed5f 100644
--- a/packages/views/locales/zh-Hans/billing.json
+++ b/packages/views/locales/zh-Hans/billing.json
@@ -233,5 +233,64 @@
"unavailable": "当前工作区的套餐不包含此功能。",
"view_plans": "查看套餐",
"locked_error": "当前工作区的套餐不包含此功能。已有设置继续生效,升级后可以新增。"
+ },
+ "trial": {
+ "status": {
+ "active": "Business 试用",
+ "days_left_other": "还剩 {{count}} 天",
+ "active_label_other": "Business 试用,还剩 {{count}} 天。打开账单。",
+ "free": "Free",
+ "upgrade": "升级",
+ "ended_label": "Business 试用已结束,工作区已切换到 Free。打开账单升级。",
+ "ending": "即将结束",
+ "ending_label": "Business 试用即将结束。打开账单。"
+ },
+ "reminder": {
+ "halfway_title_other": "Business 试用已过半,还剩 {{count}} 天。",
+ "days_left_title_other": "Business 试用还剩 {{count}} 天。",
+ "last_day_title": "Business 试用将在一天内结束。",
+ "body": "{{date}} 后工作区切换到 Free。选择套餐可以继续使用 Business。",
+ "later": "稍后",
+ "choose_plan": "选择套餐"
+ },
+ "welcome": {
+ "title_other": "欢迎!你的工作区可以免费试用 {{count}} 天 Business",
+ "body": "私有项目等 Business 功能都可以用。不需要绑卡,到期自动切换到 Free。",
+ "action": "看看有什么",
+ "close": "关闭"
+ },
+ "ended": {
+ "title": "Business 试用已结束",
+ "description": "{{workspace}} 已切换到 Free。没有任何数据被删除。",
+ "description_without_name": "工作区已切换到 Free。没有任何数据被删除。",
+ "kept": "已有的成员、项目和设置都保留。",
+ "private_projects": "私有项目保持私有,访问名单在升级前只读。",
+ "autopilot": "自动化每月 {{limit}} 次,本月已用 {{used}} 次。",
+ "autopilot_paused": "自动化每月 {{limit}} 次,本月已用 {{used}} 次,自动化已暂停到 {{date}}。",
+ "keep_free": "继续使用 Free",
+ "upgrade": "升级到 Business",
+ "member_title": "工作区已切换到 Free",
+ "member_description": "已有的设置照常生效。如需更多功能,请联系工作区管理员。"
+ },
+ "card": {
+ "title": "Business 试用",
+ "badge_other": "试用中 · 还剩 {{count}} 天",
+ "description": "试用到 {{date}}。没有绑定付款方式,到期后自动切换到 Free,不会扣款。",
+ "started": "{{date}} 开始",
+ "progress": "第 {{day}} / {{total}} 天",
+ "ends": "{{date}} 结束",
+ "ended_title": "Business 试用已结束",
+ "ended_description": "试用已于 {{date}} 结束。在下方选择套餐即可恢复 Business 功能。",
+ "choose_plan": "选择套餐",
+ "ended_description_member": "试用已于 {{date}} 结束。如需恢复 Business 功能,请联系工作区管理员升级。"
+ },
+ "features": {
+ "title": "试用中的 Business 功能",
+ "description": "试用结束后不会被删除或关闭,只是不能新建和修改。",
+ "private_projects": {
+ "name": "私有项目",
+ "after": "到期后保持私有,访问名单只读。"
+ }
+ }
}
}
diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.json
index 38955f97ae..66087973d7 100644
--- a/packages/views/locales/zh-Hant/billing.json
+++ b/packages/views/locales/zh-Hant/billing.json
@@ -233,5 +233,64 @@
"unavailable": "目前工作區的套餐不包含此功能。",
"view_plans": "查看套餐",
"locked_error": "目前工作區的套餐不包含此功能。既有設定繼續生效,升級後可以新增。"
+ },
+ "trial": {
+ "status": {
+ "active": "Business 試用",
+ "days_left_other": "還剩 {{count}} 天",
+ "active_label_other": "Business 試用,還剩 {{count}} 天。開啟帳單。",
+ "free": "Free",
+ "upgrade": "升級",
+ "ended_label": "Business 試用已結束,工作區已切換到 Free。開啟帳單升級。",
+ "ending": "即將結束",
+ "ending_label": "Business 試用即將結束。開啟帳單。"
+ },
+ "reminder": {
+ "halfway_title_other": "Business 試用已過半,還剩 {{count}} 天。",
+ "days_left_title_other": "Business 試用還剩 {{count}} 天。",
+ "last_day_title": "Business 試用將在一天內結束。",
+ "body": "{{date}} 後工作區切換到 Free。選擇方案即可繼續使用 Business。",
+ "later": "稍後",
+ "choose_plan": "選擇方案"
+ },
+ "welcome": {
+ "title_other": "歡迎!你的工作區可以免費試用 {{count}} 天 Business",
+ "body": "私有專案等 Business 功能都可以使用。不需要綁卡,到期自動切換到 Free。",
+ "action": "看看有什麼",
+ "close": "關閉"
+ },
+ "ended": {
+ "title": "Business 試用已結束",
+ "description": "{{workspace}} 已切換到 Free。沒有任何資料被刪除。",
+ "description_without_name": "工作區已切換到 Free。沒有任何資料被刪除。",
+ "kept": "已有的成員、專案和設定都保留。",
+ "private_projects": "私有專案保持私有,存取名單在升級前唯讀。",
+ "autopilot": "自動化每月 {{limit}} 次,本月已用 {{used}} 次。",
+ "autopilot_paused": "自動化每月 {{limit}} 次,本月已用 {{used}} 次,自動化已暫停到 {{date}}。",
+ "keep_free": "繼續使用 Free",
+ "upgrade": "升級到 Business",
+ "member_title": "工作區已切換到 Free",
+ "member_description": "已有的設定照常生效。如需更多功能,請聯絡工作區管理員。"
+ },
+ "card": {
+ "title": "Business 試用",
+ "badge_other": "試用中 · 還剩 {{count}} 天",
+ "description": "試用到 {{date}}。沒有綁定付款方式,到期後自動切換到 Free,不會扣款。",
+ "started": "{{date}} 開始",
+ "progress": "第 {{day}} / {{total}} 天",
+ "ends": "{{date}} 結束",
+ "ended_title": "Business 試用已結束",
+ "ended_description": "試用已於 {{date}} 結束。在下方選擇方案即可恢復 Business 功能。",
+ "choose_plan": "選擇方案",
+ "ended_description_member": "試用已於 {{date}} 結束。如需恢復 Business 功能,請聯絡工作區管理員升級。"
+ },
+ "features": {
+ "title": "試用中的 Business 功能",
+ "description": "試用結束後不會被刪除或關閉,只是不能新增和修改。",
+ "private_projects": {
+ "name": "私有專案",
+ "after": "到期後保持私有,存取名單唯讀。"
+ }
+ }
}
}
diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.ts
index ca3cf1a622..7f476de1ec 100644
--- a/packages/views/settings/components/billing-state.test.ts
+++ b/packages/views/settings/components/billing-state.test.ts
@@ -146,6 +146,7 @@ describe("billing subscription state", () => {
checkPlanChange: false,
},
planChange: null,
+ trial: null,
} satisfies WorkspaceSubscriptionSummary;
expect(hasActiveWorkspaceSeatCapacity(canceledSummary)).toBe(false);
@@ -187,6 +188,7 @@ describe("resolvePlanChangeTarget", () => {
checkPlanChange: false,
},
planChange: null,
+ trial: null,
});
it("switches between Pro and Business only when Cloud offers it", () => {
diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsx
index 3228ee5e9b..da720ae5c3 100644
--- a/packages/views/settings/components/billing-tab.test.tsx
+++ b/packages/views/settings/components/billing-tab.test.tsx
@@ -83,6 +83,7 @@ const mocks = vi.hoisted(() => ({
checkPlanChange: false,
},
planChange: null as WorkspaceSubscriptionSummary["planChange"],
+ trial: null as WorkspaceSubscriptionSummary["trial"],
} as WorkspaceSubscriptionSummary,
usage: {
action: "enforce" as "off" | "observe" | "enforce",
@@ -300,6 +301,7 @@ describe("BillingTab", () => {
checkPlanChange: false,
},
planChange: null,
+ trial: null,
});
Object.assign(mocks.usage, {
action: "enforce",
@@ -770,7 +772,7 @@ describe("BillingTab", () => {
autopilotRuns: { mode: "unlimited", limit: null },
},
});
- mocks.summary.availableActions.checkout = false;
+ setSeatCapacity({ humanMembers: 3, purchased: 3 });
mocks.summaryDataUpdatedAt = Date.now() + 1;
mocks.summaryFetchedAfterMount = true;
try {
@@ -784,6 +786,45 @@ describe("BillingTab", () => {
}
});
+ it("keeps syncing a checkout started during a trial until paid seats take effect", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2030-01-01T00:00:00Z"));
+ navigationState.search = "tab=billing&result=success&session_id=cs_test_1";
+ // Still on the Business trial while the first Pro payment is incomplete:
+ // the plan is paid and Checkout is gone, but nothing has been paid for.
+ Object.assign(mocks.entitlements, {
+ plan: "business",
+ status: "trialing",
+ limits: { autopilotRuns: { mode: "unlimited", limit: null } },
+ });
+ mocks.summary.trial = {
+ plan: "business",
+ state: "active",
+ startedAt: "2029-12-25T00:00:00Z",
+ endsAt: "2030-01-08T00:00:00Z",
+ };
+ mocks.summary.availableActions.checkout = false;
+ mocks.summaryDataUpdatedAt = Date.now() + 1;
+ mocks.summaryFetchedAfterMount = true;
+ try {
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByText("Activating your subscription")).toBeInTheDocument();
+ expect(screen.queryByText("Business is active")).not.toBeInTheDocument();
+ const summaryOptions = mocks.useQuery.mock.calls
+ .map(([options]) => options)
+ .find(
+ (options) =>
+ options.queryKey?.[options.queryKey.length - 1] === "summary",
+ );
+ expect(
+ summaryOptions.refetchInterval({ state: { data: mocks.summary } }),
+ ).toBe(2_000);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("keeps plan facts visible but hides mutations denied by Cloud", () => {
Object.assign(mocks.summary.availableActions, {
checkout: false,
@@ -2016,4 +2057,100 @@ describe("BillingTab", () => {
expect(mocks.refetchSummary).toHaveBeenCalled();
});
});
+ describe("no-card trial", () => {
+ const DAY = 24 * 60 * 60 * 1000;
+
+ function setTrial(state: "active" | "expired", startedAt: number, days = 14) {
+ const endsAt = startedAt + days * DAY;
+ mocks.summary.trial = {
+ plan: "business",
+ state,
+ startedAt: new Date(startedAt).toISOString(),
+ endsAt: new Date(endsAt).toISOString(),
+ };
+ if (state === "active") {
+ Object.assign(mocks.entitlements, {
+ plan: "business",
+ status: "trialing",
+ limits: { autopilotRuns: { mode: "unlimited", limit: null } },
+ currentPeriodEnd: new Date(endsAt).toISOString(),
+ });
+ }
+ return endsAt;
+ }
+
+ it("shows where the trial stands and what each Business feature keeps", () => {
+ const endsAt = setTrial("active", Date.now() - 4.5 * DAY);
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByRole("heading", { name: "Business trial" })).toBeInTheDocument();
+ expect(screen.getByText("Trial · 10 days left")).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ `Trial until ${new Intl.DateTimeFormat("en", { dateStyle: "medium" }).format(new Date(endsAt))}. No payment method is on file, so the workspace moves to Free afterwards and is not charged.`,
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getAllByText("Day 5 of 14").length).toBeGreaterThan(0);
+ expect(screen.getByText("Private projects")).toBeInTheDocument();
+ expect(
+ screen.getByText("Stay private after the trial. Their access lists become read-only."),
+ ).toBeInTheDocument();
+ // A trialling manager subscribes through the same plan cards.
+ expect(screen.getByRole("button", { name: "Upgrade to Business" })).toBeInTheDocument();
+ });
+
+ it("takes a manager from the trial card to the plan cards", async () => {
+ setTrial("active", Date.now() - 4.5 * DAY);
+ const scrollIntoView = vi.fn();
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = scrollIntoView;
+ try {
+ renderWithI18n(<BillingTab />);
+ await userEvent.setup().click(screen.getByRole("button", { name: "Choose a plan" }));
+
+ expect(scrollIntoView).toHaveBeenCalledOnce();
+ expect(scrollIntoView.mock.contexts[0]).toHaveAttribute("data-settings-anchor", "billing-upgrade");
+ } finally {
+ Element.prototype.scrollIntoView = original;
+ }
+ });
+
+ it("offers no plan choice to a member who cannot subscribe", () => {
+ setTrial("active", Date.now() - 4.5 * DAY);
+ mocks.summary.availableActions.checkout = false;
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.queryByRole("button", { name: "Choose a plan" })).not.toBeInTheDocument();
+ });
+
+ it("points an ended trial at the plans below", () => {
+ const endsAt = setTrial("expired", Date.now() - 20 * DAY);
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByText("Business trial ended")).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ `The trial ended on ${new Intl.DateTimeFormat("en", { dateStyle: "medium" }).format(new Date(endsAt))}. Choose a plan below to get Business features back.`,
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/days? left/)).not.toBeInTheDocument();
+ });
+
+ it("does not send a member to plan cards that are hidden after trial expiry", () => {
+ setTrial("expired", Date.now() - 15 * DAY);
+ mocks.summary.availableActions.checkout = false;
+ renderWithI18n(<BillingTab />);
+ expect(screen.getByText("Business trial ended")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Upgrade to Pro" })).not.toBeInTheDocument();
+ expect(screen.queryByText(/Choose a plan below/)).not.toBeInTheDocument();
+ expect(screen.getByText(/Ask a workspace admin to upgrade/)).toBeInTheDocument();
+ });
+
+ it("says nothing about an end that only this clock has seen", () => {
+ // Cloud still reports the trial active, a moment past its end here.
+ setTrial("active", Date.now() - 14 * DAY - 1000);
+ renderWithI18n(<BillingTab />);
+ expect(screen.queryByText("Business trial ended")).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsx
index a2dc8b800b..db80b67bd4 100644
--- a/packages/views/settings/components/billing-tab.tsx
+++ b/packages/views/settings/components/billing-tab.tsx
@@ -81,6 +81,7 @@ import { useLocale, useT } from "../../i18n";
import { useNavigation } from "../../navigation";
import { openExternal } from "../../platform";
import {
+ SETTINGS_ANCHOR_ATTR,
SettingsCard,
SettingsRow,
SettingsSection,
@@ -93,10 +94,23 @@ import {
yearlyPriceMonthlyEquivalent,
} from "./billing-state";
import { formatStripeMinorAmount } from "./billing-format";
+import { BillingTrialSection } from "./billing-trial-section";
export { formatStripeMinorAmount } from "./billing-format";
const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;
+const UPGRADE_SECTION_ANCHOR = "billing-upgrade";
+
+/** Brings the plan cards into view, as a settings deep link would. */
+function scrollToUpgrade() {
+ const target = document.querySelector<HTMLElement>(
+ `[${SETTINGS_ANCHOR_ATTR}="${UPGRADE_SECTION_ANCHOR}"]`,
+ );
+ const reduceMotion =
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ target?.scrollIntoView?.({ block: "start", behavior: reduceMotion ? "auto" : "smooth" });
+}
const SEAT_PURCHASE_POLL_TIMEOUT_MS = 2 * 60_000;
const SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS = 800;
const PAID_PLANS = ["pro", "business"] as const;
@@ -346,10 +360,13 @@ function BillingTabContent() {
: false,
});
const entitlements = summaryQuery.data?.entitlement;
+ // Checkout is done once paid seats are in effect. Neither the plan nor
+ // Checkout going away proves it: a trial already reports Business, and a
+ // first payment still incomplete also takes Checkout away.
const isCheckoutConfirmed =
returnResult === "success" &&
returnObservedAt !== null &&
- summaryQuery.data?.availableActions.checkout === false &&
+ hasActiveWorkspaceSeatCapacity(summaryQuery.data) &&
summaryQuery.isFetchedAfterMount &&
summaryQuery.dataUpdatedAt >= returnObservedAt;
const activeSeatPurchaseRequestId =
@@ -1326,6 +1343,11 @@ function BillingTabContent() {
</Alert>
) : null}
+ <BillingTrialSection
+ summary={summaryQuery.data}
+ onChoosePlan={canUpgrade ? scrollToUpgrade : undefined}
+ />
+
<SettingsSection title={t(($) => $.workspace.current.title)}>
<SettingsCard>
<SettingsRow
@@ -1450,7 +1472,10 @@ function BillingTabContent() {
</SettingsSection>
{canUpgrade ? (
- <SettingsSection title={t(($) => $.workspace.upgrade.title)}>
+ <SettingsSection
+ title={t(($) => $.workspace.upgrade.title)}
+ anchor={UPGRADE_SECTION_ANCHOR}
+ >
<SettingsCard>
<div className="space-y-5 p-4 sm:p-5">
<div
diff --git a/packages/views/settings/components/billing-trial-section.tsx b/packages/views/settings/components/billing-trial-section.tsx
new file mode 100644
index 0000000000..4f325ea428
--- /dev/null
+++ b/packages/views/settings/components/billing-trial-section.tsx
@@ -0,0 +1,128 @@
+"use client";
+
+import { Lock, Sparkles } from "@multica/ui/icons";
+import { resolveWorkspaceTrial } from "@multica/core/billing/trial";
+import type { PaidFeature, WorkspaceSubscriptionSummary } from "@multica/core/types";
+import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button } from "@multica/ui/components/ui/button";
+import { Progress } from "@multica/ui/components/ui/progress";
+import type { IconComponent } from "@multica/ui/icons";
+import { useLocale, useT } from "../../i18n";
+import { SettingsCard, SettingsRow, SettingsSection } from "./settings-layout";
+
+const TRIAL_FEATURE_ICONS: Record<PaidFeature, IconComponent> = {
+ private_projects: Lock,
+};
+const TRIAL_FEATURES = Object.keys(TRIAL_FEATURE_ICONS) as PaidFeature[];
+
+function formatDate(value: number, locale: string): string {
+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(value));
+}
+
+/**
+ * The Billing page's view of the no-card trial (MUL-9485): where the trial
+ * stands and what happens to each Business feature when it ends, or, once
+ * Cloud confirms it ended, a pointer to the plans below (or to an admin, for
+ * someone who cannot subscribe).
+ */
+export function BillingTrialSection({
+ summary,
+ onChoosePlan,
+}: {
+ summary: WorkspaceSubscriptionSummary | null | undefined;
+ /** Shows "Choose a plan" for a caller who may subscribe. */
+ onChoosePlan?: () => void;
+}) {
+ const { t } = useT("billing");
+ const locale = useLocale();
+ // The status bar refetches the summary the moment the trial ends; this
+ // section only reads it.
+ const trial = resolveWorkspaceTrial(summary, Date.now());
+
+ if (trial.kind === "ended") {
+ // Only Cloud's word ends the trial here; this clock alone does not.
+ if (!trial.confirmed) return null;
+ const date = formatDate(trial.endsAt, locale);
+ return (
+ <Alert data-slot="billing-trial-ended">
+ <Sparkles />
+ <AlertTitle>{t(($) => $.trial.card.ended_title)}</AlertTitle>
+ <AlertDescription>
+ {onChoosePlan
+ ? t(($) => $.trial.card.ended_description, { date })
+ : t(($) => $.trial.card.ended_description_member, { date })}
+ </AlertDescription>
+ </Alert>
+ );
+ }
+ if (trial.kind !== "active") return null;
+
+ const endsOn = formatDate(trial.endsAt, locale);
+ return (
+ <>
+ <SettingsSection title={t(($) => $.trial.card.title)}>
+ <SettingsCard>
+ <div className="space-y-4 p-4 sm:p-5" data-slot="billing-trial">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0 space-y-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-title-sm font-semibold">{t(($) => $.workspace.plan.business)}</h3>
+ <Badge
+ variant="secondary"
+ className={trial.warning ? "bg-warning/10 text-warning tabular-nums" : "bg-brand/10 text-brand tabular-nums"}
+ >
+ {t(($) => $.trial.card.badge, { count: trial.daysLeft })}
+ </Badge>
+ </div>
+ <p className="max-w-[65ch] text-body text-muted-foreground">
+ {t(($) => $.trial.card.description, { date: endsOn })}
+ </p>
+ </div>
+ {/* The public pricing page is not released yet, so the plan
+ cards below are where plans are compared and chosen. */}
+ {onChoosePlan ? (
+ <Button size="sm" className="shrink-0" onClick={onChoosePlan}>
+ {t(($) => $.trial.card.choose_plan)}
+ </Button>
+ ) : null}
+ </div>
+ <Progress
+ value={(trial.day / trial.totalDays) * 100}
+ aria-label={t(($) => $.trial.card.progress, { day: trial.day, total: trial.totalDays })}
+ />
+ <div className="flex flex-wrap justify-between gap-2 text-caption text-muted-foreground tabular-nums">
+ <span>{t(($) => $.trial.card.started, { date: formatDate(trial.startedAt, locale) })}</span>
+ <span>{t(($) => $.trial.card.progress, { day: trial.day, total: trial.totalDays })}</span>
+ <span>{t(($) => $.trial.card.ends, { date: endsOn })}</span>
+ </div>
+ </div>
+ </SettingsCard>
+ </SettingsSection>
+ <SettingsSection
+ title={t(($) => $.trial.features.title)}
+ description={t(($) => $.trial.features.description)}
+ >
+ <SettingsCard>
+ {TRIAL_FEATURES.map((feature) => {
+ const Icon = TRIAL_FEATURE_ICONS[feature];
+ return (
+ <SettingsRow
+ key={feature}
+ label={
+ <span className="inline-flex items-center gap-2">
+ <Icon aria-hidden="true" className="size-4 text-muted-foreground" />
+ {t(($) => $.trial.features[feature].name)}
+ </span>
+ }
+ description={t(($) => $.trial.features[feature].after)}
+ >
+ {null}
+ </SettingsRow>
+ );
+ })}
+ </SettingsCard>
+ </SettingsSection>
+ </>
+ );
+}
diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.ts
index 6dfd36caa8..5facc263f7 100644
--- a/packages/views/settings/components/seat-invite-purchase.test.ts
+++ b/packages/views/settings/components/seat-invite-purchase.test.ts
@@ -62,6 +62,7 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSum
checkPlanChange: false,
},
planChange: null,
+ trial: null,
};
}