#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Offer account linking when unlinked free credits run out (#7980)
ConnorYohc7bff2d639c1
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/DownstreamEntitlementError.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/DownstreamEntitlementError.javaindex 52d9500a50..c36823c012 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/DownstreamEntitlementError.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/DownstreamEntitlementError.java@@ -27,6 +27,8 @@ public final class DownstreamEntitlementError {private static final Pattern ERROR_CODE_FIELD =Pattern.compile("\"error\"\\s*:\\s*\"([^\"]+)\"");+ private static final Pattern REASON_FIELD = Pattern.compile("\"reason\"\\s*:\\s*\"([^\"]+)\"");+/** Matches the {@code "subscribed":true|false} field of a small JSON error body. */private static final Pattern SUBSCRIBED_FIELD =Pattern.compile("\"subscribed\"\\s*:\\s*(true|false)");@@ -45,7 +47,17 @@ public final class DownstreamEntitlementError {return null;}Matcher m = ERROR_CODE_FIELD.matcher(body);- return m.find() ? m.group(1) : null;+ if (!m.find()) {+ return null;+ }+ String code = m.group(1);+ if (status == 402 && "ACCOUNT_LINK_REQUIRED".equals(code)) {+ Matcher reason = REASON_FIELD.matcher(body);+ if (reason.find() && "FREE_TIER_EXHAUSTED".equals(reason.group(1))) {+ return "FREE_TIER_EXHAUSTED";+ }+ }+ return code;}/**diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/DownstreamEntitlementErrorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/DownstreamEntitlementErrorTest.javanew file mode 100644index 0000000000..e80930cb75--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/DownstreamEntitlementErrorTest.java@@ -0,0 +1,51 @@+package stirling.software.proprietary.service;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;++import java.nio.charset.StandardCharsets;++import org.junit.jupiter.api.Test;+import org.springframework.http.HttpHeaders;+import org.springframework.http.HttpStatus;+import org.springframework.web.client.HttpClientErrorException;++class DownstreamEntitlementErrorTest {++ @Test+ void carriesTheLocalExhaustionReasonThroughServerSideRuns() {+ assertEquals(+ "FREE_TIER_EXHAUSTED",+ code(+ HttpStatus.PAYMENT_REQUIRED,+ "{\"error\":\"ACCOUNT_LINK_REQUIRED\",\"reason\":\"FREE_TIER_EXHAUSTED\"}"));+ }++ @Test+ void doesNotOfferLinkingForOtherAccountOrHttpFailures() {+ assertEquals(+ "ACCOUNT_LINK_REQUIRED",+ code(+ HttpStatus.PAYMENT_REQUIRED,+ "{\"error\":\"ACCOUNT_LINK_REQUIRED\",\"reason\":\"OVER_LIMIT\"}"));+ assertNull(+ code(+ HttpStatus.FORBIDDEN,+ "{\"error\":\"ACCOUNT_LINK_REQUIRED\",\"reason\":\"FREE_TIER_EXHAUSTED\"}"));+ assertEquals(+ "PAYG_LIMIT_REACHED",+ code(+ HttpStatus.PAYMENT_REQUIRED,+ "{\"error\":\"PAYG_LIMIT_REACHED\",\"subscribed\":true}"));+ }++ private static String code(HttpStatus status, String body) {+ return DownstreamEntitlementError.extractCode(+ HttpClientErrorException.create(+ status,+ "Blocked",+ new HttpHeaders(),+ body.getBytes(StandardCharsets.UTF_8),+ StandardCharsets.UTF_8));+ }+}diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex a7e6dd57b5..1187ffb881 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -7387,19 +7387,25 @@ description = "Ask your server administrator to enable the connection to Stirlintitle = "Account connection unavailable"[portal.accountLink.connect]+adminRequired = "Ask your server administrator to open Usage & billing and link a Stirling account for more monthly credits. Manual PDF tools are still available."+adminTitle = "Ask your server administrator"close = "Close"-exhaustedLede = "This server has used its free credits for the month. They reset when the period rolls over. Connecting a Stirling account adds a further monthly allowance on top."+copied = "Copied"+copyAdminMessage = "Copy message for administrator"+exhaustedLede = "This server has used its free credits for the month. Link a new or existing Stirling account to access your team’s monthly allowance."notNow = "Not now"start = "Connect Stirling account"step = "Step {{current}} of {{total}}"[portal.accountLink.connect.benefits]-creditsDetailMonthly = "Free monthly allowance"-creditsLabel = "Credits"-processorDetail = "Pipelines, policies, sources and audit"-processorLabel = "Processor"-teamsDetail = "Free for up to 5 users"-teamsLabel = "Teams"+billingDetail = "Manage usage, billing and linked servers together"+billingLabel = "One account"+creditsDetail = "Access your team’s free monthly allowance"+creditsLabel = "Monthly credits"+processingDetail = "Buy more credits for API, AI and automation as you grow"+processingLabel = "More processing"+teamsDetail = "Add more users with a paid Team plan"+teamsLabel = "Larger teams"[portal.accountLink.connect.callback]linkedNotSignedIn = "You are not signed in to Stirling in this browser, so usage and billing will ask you to sign in."@@ -7450,6 +7456,15 @@ retry = "Check connection"revokedBody = "Stirling Cloud rejected this account connection. Reconnect the account in Settings to restore eligible cloud-backed features."revokedTitle = "Account connection revoked"+[portal.accountLink.failure]+automatic = "Pipeline “{{pipeline}}” stopped during an automatic run because this server is out of credits."+export = "Pipeline “{{pipeline}}” stopped before download because this server is out of credits."+manage = "Open pipeline settings"+manual = "Pipeline “{{pipeline}}” stopped when you ran it because this server is out of credits."+openFailed = "Open the Processor on your connected server to manage this pipeline."+pipeline = "Pipeline"+upload = "Pipeline “{{pipeline}}” stopped after upload because this server is out of credits."+[portal.accountLink.gate]retry = "Try again"@@ -7466,7 +7481,7 @@ title = "No connected instances"callbackMismatch = "This server's configured frontend address does not match the address you opened. Open the server at its configured address, or update Frontend URL in General settings, then try again."cancel = "Cancel"continueReauth = "Sign in again"-exhaustedTitle = "Add more monthly credits"+exhaustedTitle = "Keep your workflows running"identity = "Stirling account"linkTitle = "Connect your Stirling account"noAuthorizeUrl = "Stirling did not return somewhere to continue. Try again in a moment."@@ -7478,6 +7493,9 @@ and = "and"before = "Set"title = "Stirling connection not configured"+[portal.accountLink.notice]+openFailed = "Could not open your browser. Open Usage & billing on your connected server to link an account."+[portal.accountLink.panel]instancesSub = "Self-hosted servers connected to the same team."instancesTitle = "Connected instances"@@ -7493,6 +7511,27 @@ forbidden = "Only the team owner can manage connected instances."generic = "Your connections could not be checked. Try again."title = "Couldn’t load connected instances"+[portal.accountLink.pipelines]+editorExport = "Editor · before download"+editorUpload = "Editor · on upload"+empty = "No active pipelines."+loadFailed = "Could not load pipelines. Open pipeline settings to try again."+loading = "Loading pipelines…"+manual = "Manual runs"+paused = "Paused"+required = "Required policy · manage in pipeline settings"+saveFailed = "Could not change this pipeline. Open pipeline settings to review it."+title = "Active pipelines"+triggered = "Triggered this prompt"+viewAll = "View all pipelines"++[portal.accountLink.rail]+adminCta = "How to get more credits"+adminSub = "Ask your server administrator to link a Stirling account for more credits. Manual PDF tools are still available."+exhaustedCta = "Link account for more credits"+exhaustedSub = "Link for monthly credits, shared billing and the option to grow with a Team plan."+exhaustedTitle = "This server’s free credits are used up"+[portal.accountLink.renewal]dataUnavailable = "Your plan and usage will appear after you renew billing access. This server stays connected, and local document processing remains available."expired = "This sign-in request expired. Try again to renew billing access; your server is still connected."@@ -10187,11 +10226,15 @@ walletUnavailable = "Wallet unavailable: {{status}} {{statusText}}"[portal.usage.freeTier]adminOnly = "This server's monthly credits are shared by everyone on it, so only an administrator can see the figures. Everything you can run stays available."+barAria = "Free credits remaining"+capSuffix_one = "of {{allowance}} free credit left this month"+capSuffix_other = "of {{allowance}} free credits left this month"connect = "Connect a Stirling account"connectBody = "Connecting adds a second monthly allowance, raises the users this server can have, and turns on the Processor."connectTitle = "This server has no Stirling account"loadError = "Couldn't read this server's credit usage. Try again in a moment."loadErrorTitle = "Couldn't load credit usage"+resets = "Resets {{date}}"[portal.usage.sessionExpired]body = "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked."diff --git a/frontend/editor/src/cloud/components/AccountLinkNotice.tsx b/frontend/editor/src/cloud/components/AccountLinkNotice.tsxnew file mode 100644index 0000000000..6880bdc15b--- /dev/null+++ b/frontend/editor/src/cloud/components/AccountLinkNotice.tsx@@ -0,0 +1,4 @@+/** Hosted sessions already have a Stirling account; server linking applies only to self-hosting. */+export function AccountLinkNotice() {+ return null;+}diff --git a/frontend/editor/src/core/services/__tests__/httpErrorHandler.test.ts b/frontend/editor/src/core/services/__tests__/httpErrorHandler.test.tsindex e94616976b..6f9448b3fb 100644--- a/frontend/editor/src/core/services/__tests__/httpErrorHandler.test.ts+++ b/frontend/editor/src/core/services/__tests__/httpErrorHandler.test.ts@@ -1,6 +1,11 @@import { describe, it, expect, vi, beforeEach } from "vitest";import { alert } from "@app/components/toast";import { handleHttpError } from "@app/services/httpErrorHandler";+import {+ clearAccountLinkBlock,+ useAccountLinkBlock,+} from "@app/services/accountLinkBlock";+import { act, renderHook } from "@testing-library/react";// Only the toast surface matters here; the rest of the handler's graph is// heavy UI that these cases never reach.@@ -62,3 +67,63 @@ describe("handleHttpError - suppressErrorToast", () => {expect(window.location.href).toBe(before);});});++describe("local free allowance failures", () => {+ beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ vi.clearAllMocks();+ });++ it("recognizes a blob 402 before generic toast suppression", async () => {+ const probe = renderHook(() => useAccountLinkBlock());+ const error = {+ ...axiosError({ suppressErrorToast: true }, 402),+ response: {+ status: 402,+ data: {+ text: async () =>+ JSON.stringify({+ error: "ACCOUNT_LINK_REQUIRED",+ reason: "FREE_TIER_EXHAUSTED",+ }),+ },+ },+ };+ await act(async () => {+ expect(await handleHttpError(error)).toBe(true);+ });+ expect(probe.result.current.promptPending).toBe(true);+ expect(alert).not.toHaveBeenCalled();+ });++ it("requests the first modal for a JSON exhaustion response", async () => {+ const probe = renderHook(() => useAccountLinkBlock());+ const error = {+ ...axiosError({}, 402),+ response: {+ status: 402,+ data: { error: "ACCOUNT_LINK_REQUIRED", reason: "FREE_TIER_EXHAUSTED" },+ },+ };+ await act(async () => {+ await handleHttpError(error);+ });+ expect(probe.result.current.exhausted).toBe(true);+ expect(probe.result.current.promptPending).toBe(true);+ expect(alert).not.toHaveBeenCalled();+ });++ it("does not offer linking for a linked team's exhausted wallet", async () => {+ const probe = renderHook(() => useAccountLinkBlock());+ await handleHttpError({+ ...axiosError({}, 402),+ response: {+ status: 402,+ data: { error: "ACCOUNT_LINK_REQUIRED", reason: "OVER_LIMIT" },+ },+ });+ expect(probe.result.current.exhausted).toBe(false);+ expect(alert).toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/services/accountLinkBlock.test.ts b/frontend/editor/src/core/services/accountLinkBlock.test.tsnew file mode 100644index 0000000000..d1018a5cd7--- /dev/null+++ b/frontend/editor/src/core/services/accountLinkBlock.test.ts@@ -0,0 +1,110 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ acknowledgeAccountLinkPrompt,+ clearAccountLinkBlock,+ reportFreeTierExhausted,+ useAccountLinkBlock,+} from "@app/services/accountLinkBlock";++const cause = {+ pipelineId: "rotate",+ pipelineName: "Rotate",+ trigger: "upload" as const,+};++describe("credit prompt session", () => {+ beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ });++ it("keeps the first failed pipeline as the cause of concurrent failures", () => {+ const { result } = renderHook(useAccountLinkBlock);+ act(() => {+ reportFreeTierExhausted(cause);+ reportFreeTierExhausted({+ ...cause,+ pipelineId: "other-pipeline",+ });+ });+ expect(result.current.promptPending).toBe(true);+ expect(result.current.context).toEqual(cause);+ });++ it("suppresses further automatic prompts after recovery", () => {+ const { result } = renderHook(useAccountLinkBlock);+ act(() => {+ reportFreeTierExhausted(cause);+ acknowledgeAccountLinkPrompt();+ clearAccountLinkBlock();+ reportFreeTierExhausted(cause);+ });+ expect(result.current.promptPending).toBe(false);+ });++ it("does not attach a later pipeline failure to a prompt opened by a direct feature", () => {+ const { result } = renderHook(useAccountLinkBlock);+ act(() => {+ reportFreeTierExhausted();+ reportFreeTierExhausted(cause);+ });+ expect(result.current.promptPending).toBe(true);+ expect(result.current.context).toBeUndefined();+ });++ it("honours persisted session suppression and rearms for a fresh tab session", () => {+ sessionStorage.setItem("stirling:credit-prompt-shown", "true");+ clearAccountLinkBlock();+ const { result } = renderHook(useAccountLinkBlock);+ act(() => reportFreeTierExhausted(cause));+ expect(result.current.promptPending).toBe(false);+ act(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ reportFreeTierExhausted(cause);+ });+ expect(result.current.promptPending).toBe(true);+ });++ it("retains suppression when session storage becomes unavailable", () => {+ const { result } = renderHook(useAccountLinkBlock);+ act(() => {+ reportFreeTierExhausted(cause);+ acknowledgeAccountLinkPrompt();+ });+ const read = vi+ .spyOn(Storage.prototype, "getItem")+ .mockImplementation(() => {+ throw new Error("blocked");+ });+ try {+ act(() => {+ clearAccountLinkBlock();+ reportFreeTierExhausted(cause);+ });+ expect(result.current.promptPending).toBe(false);+ } finally {+ read.mockRestore();+ }+ });+ it("retains suppression when storage is readable but refuses writes", () => {+ const { result } = renderHook(useAccountLinkBlock);+ const write = vi+ .spyOn(Storage.prototype, "setItem")+ .mockImplementation(() => {+ throw new Error("quota exceeded");+ });+ try {+ act(() => {+ reportFreeTierExhausted(cause);+ acknowledgeAccountLinkPrompt();+ clearAccountLinkBlock();+ reportFreeTierExhausted(cause);+ });+ expect(result.current.promptPending).toBe(false);+ } finally {+ write.mockRestore();+ }+ });+});diff --git a/frontend/editor/src/core/services/accountLinkBlock.ts b/frontend/editor/src/core/services/accountLinkBlock.tsnew file mode 100644index 0000000000..ad65edb717--- /dev/null+++ b/frontend/editor/src/core/services/accountLinkBlock.ts@@ -0,0 +1,134 @@+import { useSyncExternalStore } from "react";++/** Shared by the editor and Processor, including runs outside the portal HTTP client. */+export const FREE_TIER_EXHAUSTED_EVENT = "stirling:portal-free-tier-exhausted";++export type AccountLinkBlockReason =+ | "FREE_TIER_EXHAUSTED"+ | "OVER_LIMIT"+ | "REVOKED"+ | "GRACE_EXPIRED";+export type AccountLinkBlockSource = "foreground" | "background";++export interface AccountLinkBlockContext {+ pipelineId?: string;+ pipelineName?: string;+ trigger: "upload" | "export" | "manual" | "automatic";+}++const PROMPT_SESSION_KEY = "stirling:credit-prompt-shown";+let shownInMemory = false;+let storageWriteFailed = false;+const EMPTY = {+ exhausted: false,+ promptPending: false,+ context: undefined as AccountLinkBlockContext | undefined,+};+let state = EMPTY;+const listeners = new Set<() => void>();++function shownThisSession(): boolean {+ try {+ return (+ window.sessionStorage.getItem(PROMPT_SESSION_KEY) === "true" ||+ (storageWriteFailed && shownInMemory)+ );+ } catch {+ return shownInMemory;+ }+}++function publish(next: typeof state): void {+ state = next;+ listeners.forEach((listener) => listener());+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/** The first failed operation requests a dialog; route changes retain its cause. */+export function useAccountLinkBlock() {+ return useSyncExternalStore(+ subscribe,+ () => state,+ () => EMPTY,+ );+}++/** Clears recovered exhaustion without rearming the automatic prompt in this tab session. */+export function clearAccountLinkBlock(): void {+ if (state !== EMPTY) publish(EMPTY);+}++/** Coalesces failures across navigation and reloads; blocked storage falls back to this app lifetime. */+export function acknowledgeAccountLinkPrompt(): void {+ shownInMemory = true;+ try {+ window.sessionStorage.setItem(PROMPT_SESSION_KEY, "true");+ } catch {+ // Restricted webviews can deny storage; the in-memory suppression still applies.+ storageWriteFailed = true;+ }+ publish({ ...state, promptPending: false });+}++/** Records a failed operation and preserves the first cause while its exhaustion notice is active. */+export function reportFreeTierExhausted(+ context?: AccountLinkBlockContext,+): void {+ const promptPending = state.promptPending || !shownThisSession();+ const cause = state.exhausted ? state.context : context;+ if (+ state.exhausted &&+ state.promptPending === promptPending &&+ state.context === cause+ )+ return;+ publish({ exhausted: true, promptPending, context: cause });+ if (typeof window !== "undefined") {+ window.dispatchEvent(new Event(FREE_TIER_EXHAUSTED_EVENT));+ }+}++/** Accepts parsed portal errors and Axios errors; unrelated 402s fall through. */+export function classifyAccountLinkBlock(+ error: unknown,+): AccountLinkBlockReason | null {+ if (!error || typeof error !== "object") return null;+ const failure = error as {+ status?: unknown;+ body?: unknown;+ response?: { status?: unknown; data?: unknown };+ };+ if ((failure.response?.status ?? failure.status) !== 402) return null;+ const body = failure.response?.data ?? failure.body;+ if (!body || typeof body !== "object") return null;+ const { error: sentinel, reason } = body as {+ error?: unknown;+ reason?: unknown;+ };+ if (sentinel !== "ACCOUNT_LINK_REQUIRED") return null;+ switch (reason) {+ case "FREE_TIER_EXHAUSTED":+ case "OVER_LIMIT":+ case "REVOKED":+ case "GRACE_EXPIRED":+ return reason;+ default:+ return null;+ }+}++/** Returns whether this is a spent local allowance, so callers can suppress generic errors. */+export function reportAccountLinkBlock(+ error: unknown,+ context?: AccountLinkBlockContext,+): boolean {+ if (classifyAccountLinkBlock(error) !== "FREE_TIER_EXHAUSTED") return false;+ reportFreeTierExhausted(context);+ return true;+}diff --git a/frontend/editor/src/core/services/httpErrorHandler.ts b/frontend/editor/src/core/services/httpErrorHandler.tsindex e36c5ad8b0..958e145cbd 100644--- a/frontend/editor/src/core/services/httpErrorHandler.ts+++ b/frontend/editor/src/core/services/httpErrorHandler.ts@@ -14,6 +14,7 @@ import {} from "@app/services/httpErrorUtils";import { stripBasePath, withBasePath } from "@app/constants/app";import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";+import { reportAccountLinkBlock } from "@app/services/accountLinkBlock";// Module-scoped state to reduce global variable usageconst recentSpecialByEndpoint: Record<string, number> = {};@@ -82,6 +83,18 @@ if (typeof window !== "undefined") {*/export async function handleHttpError(error: unknown): Promise<boolean> {const axiosError = axios.isAxiosError(error) ? error : undefined;+ if (axiosError?.response?.status === 402) {+ const body = await normalizeAxiosErrorData(axiosError.response.data).catch(+ () => undefined,+ );+ if (+ reportAccountLinkBlock(+ { status: 402, body },+ axiosError.config?.accountLinkBlockContext,+ )+ )+ return true;+ }const skipAuthRedirect = axiosError?.config?.skipAuthRedirect === true;// Check if this error should skip the global toast (component will handle it)if (axiosError?.config?.suppressErrorToast === true) {diff --git a/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.ts b/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.tsindex 90ee58282c..0b72a59273 100644--- a/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.ts@@ -125,21 +125,38 @@ test("dismissing the trial connection prerequisite does not reopen it", async ({test("late exhausted-credit responses do not reopen a dismissed dialog", async ({page,}) => {- await page.goto("/processor/pipelines");- await expect(- page.getByRole("button", { name: "Link Stirling account" }),- ).toBeVisible();- await page.evaluate(() =>- window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted")),+ await page.route("**/api/v1/account-link/free-tier", (route) =>+ route.fulfill({+ json: {+ grantUnits: 1000,+ usedUnits: 1000,+ remainingUnits: 0,+ periodStart: "2026-09-01T00:00:00",+ periodEnd: "2026-10-01T00:00:00",+ },+ }),+ );+ await page.route("**/api/v1/policies", (route) =>+ route.fulfill({+ status: 402,+ json: { error: "ACCOUNT_LINK_REQUIRED", reason: "FREE_TIER_EXHAUSTED" },+ }),);+ await page.goto("/processor/pipelines");await expect(page.getByRole("dialog")).toHaveCount(1);await page.getByRole("dialog").getByRole("button", { name: "Not now", exact: true }).click();- await page.evaluate(() =>- window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted")),+ const repeatedFailure = page.waitForResponse(+ (response) =>+ response.url().endsWith("/api/v1/policies") && response.status() === 402,);+ await page.reload();+ await repeatedFailure;+ await expect(+ page.getByRole("button", { name: "Link Stirling account" }),+ ).toBeVisible();await expect(page.getByRole("dialog")).toHaveCount(0);await page.getByRole("button", { name: "Link Stirling account" }).click();await expect(page.getByRole("dialog")).toHaveCount(1);diff --git a/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsx b/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsxnew file mode 100644index 0000000000..fca4d9bf3b--- /dev/null+++ b/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsx@@ -0,0 +1,308 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter, useLocation } from "react-router-dom";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MantineProvider } from "@mantine/core";+import { AccountLinkNotice } from "@app/components/AccountLinkNotice";+import { handleHttpError } from "@app/services/httpErrorHandler";+import { clearAccountLinkBlock } from "@app/services/accountLinkBlock";+import type { ConnectionConfig } from "@app/services/connectionModeService";++const {+ auth,+ alert,+ dismissToast,+ openExternal,+ getCurrentConfig,+ listeners,+ get,+} = vi.hoisted(() => ({+ auth: { isAdmin: true, loading: false },+ alert: vi.fn(),+ dismissToast: vi.fn(),+ openExternal: vi.fn(),+ getCurrentConfig: vi.fn(),+ get: vi.fn(),+ listeners: new Set<(config: ConnectionConfig) => void>(),+}));++vi.mock("@app/auth", () => ({ useAuth: () => auth }));+vi.mock("@app/components/toast", () => ({ alert, dismissToast }));+vi.mock("@app/platform/openExternal", () => ({ openExternal }));+vi.mock("@app/services/apiClient", () => ({ default: { get } }));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentConfig,+ subscribeToModeChanges: (listener: (config: ConnectionConfig) => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+}));+vi.mock("@app/services/specialErrorToasts", () => ({+ showSpecialErrorToast: vi.fn().mockReturnValue(false),+}));+vi.mock("react-i18next", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-i18next")>()),+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));+vi.mock("@app/ui", async () => ({+ ...(await import("@app/ui/Button")),+ ...(await import("@app/ui/Modal")),+ ...(await import("@app/ui/Banner")),+}));++function config(+ mode: ConnectionConfig["mode"] = "selfhosted",+ url = "https://server.example/stirling/",+): ConnectionConfig {+ return { mode, server_config: { url }, lock_connection_mode: false };+}++function LocationProbe() {+ return <output>{useLocation().pathname}</output>;+}++async function mount(path = "/editor") {+ const view = render(+ <MantineProvider>+ <QueryClientProvider client={new QueryClient()}>+ <MemoryRouter initialEntries={[path]}>+ <AccountLinkNotice />+ <LocationProbe />+ </MemoryRouter>+ </QueryClientProvider>+ </MantineProvider>,+ );+ await act(async () => {});+ return view;+}++async function exhaust() {+ await act(async () => {+ expect(+ await handleHttpError({+ isAxiosError: true,+ config: {},+ response: {+ status: 402,+ data: {+ error: "ACCOUNT_LINK_REQUIRED",+ reason: "FREE_TIER_EXHAUSTED",+ },+ },+ }),+ ).toBe(true);+ });+}++describe("desktop self-hosted account-link triggers", () => {+ beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ vi.clearAllMocks();+ listeners.clear();+ auth.isAdmin = true;+ getCurrentConfig.mockResolvedValue(config());+ openExternal.mockResolvedValue(undefined);+ get.mockResolvedValue({+ data: {+ linked: false,+ remainingUnits: 0,+ grantUnits: 500,+ periodEnd: "2026-10-01T00:00:00",+ },+ });+ });++ it.each(["/editor", "/settings/billing", "/settings/account-link"])(+ "opens server billing externally from %s, preserving the deployment subpath",+ async (path) => {+ await mount(path);+ await exhaust();+ expect(screen.getByRole("dialog")).toBeTruthy();+ fireEvent.click(+ screen.getByRole("button", { name: "Link account for more credits" }),+ );+ expect(openExternal).toHaveBeenCalledWith(+ "https://server.example/stirling/settings/billing",+ );+ expect(screen.getByRole("status").textContent).toBe(path);+ },+ );++ it("opens the failed pipeline on the connected server while preserving its deployment subpath", async () => {+ await mount();+ await act(async () =>+ handleHttpError({+ isAxiosError: true,+ config: {+ accountLinkBlockContext: {+ pipelineId: "rotate-id",+ pipelineName: "Quarterly rotation",+ trigger: "upload",+ },+ },+ response: {+ status: 402,+ data: {+ error: "ACCOUNT_LINK_REQUIRED",+ reason: "FREE_TIER_EXHAUSTED",+ },+ },+ }),+ );+ fireEvent.click(screen.getByText("Active pipelines"));+ fireEvent.click(+ await screen.findByRole("button", { name: "Open pipeline settings" }),+ );+ expect(openExternal).toHaveBeenCalledWith(+ "https://server.example/stirling/processor/pipelines/rotate-id",+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("does not reopen a dismissed modal for repeated exhaustion", async () => {+ await mount();+ await exhaust();+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ await exhaust();+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(alert).not.toHaveBeenCalled();+ });++ it("tells members to contact their server administrator", async () => {+ auth.isAdmin = false;+ await mount();+ await exhaust();+ expect(+ screen.getByRole("dialog", { name: "Ask your server administrator" }),+ ).toBeTruthy();+ expect(+ screen.queryByRole("button", { name: "Link account for more credits" }),+ ).toBeNull();+ expect(openExternal).not.toHaveBeenCalled();+ expect(get).not.toHaveBeenCalled();+ });++ it.each(["saas", "local"] as const)(+ "stays hidden in %s mode",+ async (mode) => {+ getCurrentConfig.mockResolvedValue(config(mode));+ await mount();+ await exhaust();+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(alert).not.toHaveBeenCalled();+ expect(openExternal).not.toHaveBeenCalled();+ },+ );++ it("clears exhaustion when switching servers or leaving self-hosted mode", async () => {+ await mount();+ await exhaust();+ act(() =>+ listeners.forEach((listener) =>+ listener(config("selfhosted", "https://other.example")),+ ),+ );+ expect(alert).not.toHaveBeenCalled();+ expect(screen.queryByRole("dialog")).toBeNull();+ await exhaust();+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(openExternal).not.toHaveBeenCalled();+ act(() => listeners.forEach((listener) => listener(config("saas"))));+ act(() => listeners.forEach((listener) => listener(config())));+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("does not let delayed initial config overwrite a mode change", async () => {+ let finish: (value: ConnectionConfig) => void = () => {};+ getCurrentConfig.mockReturnValue(+ new Promise<ConnectionConfig>((resolve) => {+ finish = resolve;+ }),+ );+ await mount();+ act(() => listeners.forEach((listener) => listener(config("local"))));+ await act(async () => finish(config()));+ await exhaust();+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(alert).not.toHaveBeenCalled();+ });++ it("dismisses the notice when the exhaustion state is cleared", async () => {+ await mount();+ await exhaust();+ act(() => clearAccountLinkBlock());+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(alert).not.toHaveBeenCalled();+ });++ it("offers recovery instructions if the system browser cannot open", async () => {+ openExternal.mockRejectedValue(new Error("Shell unavailable"));+ await mount();+ await exhaust();+ await act(async () =>+ fireEvent.click(+ screen.getByRole("button", { name: "Link account for more credits" }),+ ),+ );+ expect(alert).toHaveBeenCalledWith(+ expect.objectContaining({+ alertType: "error",+ title: expect.stringContaining("Could not open your browser"),+ }),+ );+ });++ it.each([+ { linked: true, remainingUnits: 0 },+ { linked: false, remainingUnits: 500 },+ ])("refreshes recovery when returning from the browser: %j", async (data) => {+ await mount();+ await exhaust();+ expect(get).toHaveBeenCalledWith(+ "https://server.example/stirling/api/v1/account-link/status",+ expect.objectContaining({ suppressErrorToast: true }),+ );+ get.mockResolvedValue({ data });+ await act(async () => {+ window.dispatchEvent(new Event("focus"));+ });+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("keeps the notice when recovery checks fail", async () => {+ get.mockRejectedValue(new Error("Offline"));+ await mount();+ await exhaust();+ expect(screen.getByRole("dialog")).toBeTruthy();+ });++ it("retains the balance when the same server config is emitted again", async () => {+ await mount();+ await exhaust();+ expect(screen.getByRole("progressbar")).toBeTruthy();+ get.mockClear();+ await act(async () => {+ listeners.forEach((listener) => listener(config()));+ });+ expect(screen.getByRole("progressbar")).toBeTruthy();+ expect(screen.getByRole("dialog")).toBeTruthy();+ expect(get).not.toHaveBeenCalled();+ });++ it("retains the last balance when a recovery refetch fails", async () => {+ await mount();+ await exhaust();+ expect(screen.getByRole("progressbar")).toBeTruthy();+ get.mockRejectedValue(new Error("Offline"));+ await act(async () => {+ window.dispatchEvent(new Event("focus"));+ });+ expect(screen.getByRole("progressbar")).toBeTruthy();+ expect(screen.getByRole("dialog")).toBeTruthy();+ });+});diff --git a/frontend/editor/src/desktop/components/AccountLinkNotice.tsx b/frontend/editor/src/desktop/components/AccountLinkNotice.tsxnew file mode 100644index 0000000000..7f82b4f48d--- /dev/null+++ b/frontend/editor/src/desktop/components/AccountLinkNotice.tsx@@ -0,0 +1,147 @@+import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { AccountLinkNotice as SelfHostedAccountLinkNotice } from "@proprietary/components/AccountLinkNotice";+import {+ connectionModeService,+ type ConnectionConfig,+} from "@app/services/connectionModeService";+import {+ clearAccountLinkBlock,+ useAccountLinkBlock,+} from "@app/services/accountLinkBlock";+import { useAuth } from "@app/auth";+import apiClient from "@app/services/apiClient";+import { openExternal } from "@app/platform/openExternal";+import { alert } from "@app/components/toast";+import type { FreeTierBalance } from "@app/components/account-link/FreeTierBalanceSummary";++function billingUrl(config: ConnectionConfig): string | null {+ if (config.mode !== "selfhosted" || !config.server_config?.url) return null;+ try {+ const url = new URL(config.server_config.url);+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;+ url.pathname = `${url.pathname.replace(/\/+$/, "")}/settings/billing`;+ url.search = "";+ url.hash = "";+ url.username = "";+ url.password = "";+ return url.href;+ } catch {+ return null;+ }+}++/** Desktop has no Processor; self-hosted linking belongs to the connected server's browser UI. */+export function AccountLinkNotice() {+ const { t } = useTranslation();+ const { isAdmin, loading } = useAuth();+ const { exhausted } = useAccountLinkBlock();+ const [target, setTarget] = useState<string | null>(null);+ const [balance, setBalance] = useState<FreeTierBalance>();++ useEffect(() => {+ let active = true;+ let receivedUpdate = false;+ let previous: string | null | undefined;+ const update = (config: ConnectionConfig) => {+ if (!active) return;+ const next = billingUrl(config);+ if (previous === next) return;+ if (previous !== undefined) clearAccountLinkBlock();+ previous = next;+ setBalance(undefined);+ setTarget(next);+ };+ const unsubscribe = connectionModeService.subscribeToModeChanges(+ (config) => {+ receivedUpdate = true;+ update(config);+ },+ );+ void connectionModeService.getCurrentConfig().then((config) => {+ if (!receivedUpdate) update(config);+ });+ return () => {+ active = false;+ unsubscribe();+ };+ }, []);++ useEffect(() => {+ if (!target || !exhausted || !isAdmin || loading) return;+ let active = true;+ let refreshing = false;+ const refresh = async () => {+ if (refreshing) return;+ refreshing = true;+ const options = { suppressErrorToast: true, skipAuthRedirect: true };+ try {+ const status = await apiClient.get<{ linked: boolean }>(+ new URL("../api/v1/account-link/status", target).href,+ options,+ );+ if (!active) return;+ if (status.data.linked) {+ clearAccountLinkBlock();+ return;+ }+ const balance = await apiClient.get<FreeTierBalance>(+ new URL("../api/v1/account-link/free-tier", target).href,+ options,+ );+ if (active) {+ setBalance(balance.data);+ if (balance.data.remainingUnits > 0) clearAccountLinkBlock();+ }+ } catch {+ // An unavailable balance is not evidence that the server's allowance recovered.+ } finally {+ refreshing = false;+ }+ };+ void refresh();+ window.addEventListener("focus", refresh);+ const interval = window.setInterval(refresh, 60_000);+ return () => {+ active = false;+ window.removeEventListener("focus", refresh);+ window.clearInterval(interval);+ };+ }, [target, exhausted, isAdmin, loading]);++ const showOptions = useCallback(() => {+ if (!target) return;+ void openExternal(target).catch(() => {+ alert({+ alertType: "error",+ title: t(+ "portal.accountLink.notice.openFailed",+ "Could not open your browser. Open Usage & billing on your connected server to link an account.",+ ),+ });+ });+ }, [target, t]);++ return target ? (+ <SelfHostedAccountLinkNotice+ key={target}+ onShowOptions={showOptions}+ onManagePipeline={(id) => {+ const url = new URL(+ `../processor/pipelines${id ? `/${encodeURIComponent(id)}` : ""}`,+ target,+ );+ void openExternal(url.href).catch(() => {+ alert({+ alertType: "error",+ title: t(+ "portal.accountLink.failure.openFailed",+ "Open the Processor on your connected server to manage this pipeline.",+ ),+ });+ });+ }}+ balance={balance}+ />+ ) : null;+}diff --git a/frontend/editor/src/desktop/components/account-link/EditorLinkModal.tsx b/frontend/editor/src/desktop/components/account-link/EditorLinkModal.tsxnew file mode 100644index 0000000000..4598ca23d2--- /dev/null+++ b/frontend/editor/src/desktop/components/account-link/EditorLinkModal.tsx@@ -0,0 +1 @@+export { ExhaustedAccountLinkModal as EditorLinkModal } from "@app/components/account-link/ExhaustedAccountLinkModal";diff --git a/frontend/editor/src/desktop/services/tauriHttpClient.ts b/frontend/editor/src/desktop/services/tauriHttpClient.tsindex d3fe07e4d1..da8df69f68 100644--- a/frontend/editor/src/desktop/services/tauriHttpClient.ts+++ b/frontend/editor/src/desktop/services/tauriHttpClient.ts@@ -37,6 +37,7 @@ export interface TauriHttpRequestConfig {skipAuthRedirect?: boolean;// Axios compatibility properties (ignored by Tauri HTTP)suppressErrorToast?: boolean;+ accountLinkBlockContext?: import("@app/services/accountLinkBlock").AccountLinkBlockContext;cancelToken?: any;signal?: AbortSignal;}diff --git a/frontend/editor/src/global.d.ts b/frontend/editor/src/global.d.tsindex 03f91e675d..9b577f0c78 100644--- a/frontend/editor/src/global.d.ts+++ b/frontend/editor/src/global.d.ts@@ -52,6 +52,8 @@ declare global {declare module "axios" {export interface AxiosRequestConfig<_D = unknown> {suppressErrorToast?: boolean;+ /** Supplies pipeline details only when that request caused the credit prompt. */+ accountLinkBlockContext?: import("@app/services/accountLinkBlock").AccountLinkBlockContext;skipAuthRedirect?: boolean;skipBackendReadyCheck?: boolean;}diff --git a/frontend/editor/src/portal/api/http.ts b/frontend/editor/src/portal/api/http.tsindex d319ea9d08..1d8e92ecee 100644--- a/frontend/editor/src/portal/api/http.ts+++ b/frontend/editor/src/portal/api/http.ts@@ -41,6 +41,7 @@* entitlement calls. It never enters the portal — the browser is the human* admin and uses the Supabase JWT for SaaS reads. Don't add it here.*/+import type { AccountLinkBlockContext } from "@app/services/accountLinkBlock";import { withPortalSaasSession } from "@app/portal/auth/portalSaasSession";import { reportAccountLinkBlock } from "@app/portal/services/accountLinkBlock";export { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";@@ -63,6 +64,7 @@ function saasBaseUrl(): string | null {}export interface HttpRequestOptions {+ accountLinkBlockContext?: AccountLinkBlockContext;method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";body?: unknown;/** Extra headers; Content-Type and Accept are set automatically. */@@ -114,7 +116,10 @@ export function errorMessage(error: unknown): string {// Shared response handler// ────────────────────────────────────────────────────────────────────────────-async function unwrap<T>(res: Response): Promise<T> {+async function unwrap<T>(+ res: Response,+ context?: AccountLinkBlockContext,+): Promise<T> {if (!res.ok) {let body: unknown = null;try {@@ -126,7 +131,7 @@ async function unwrap<T>(res: Response): Promise<T> {// The instance's entitlement gate answers a spent free grant here, and the prompt it raises is// the actionable surface. Reported for every domain rather than only the local one because the// classifier keys on a sentinel only the local backend sends, so a SaaS 402 cannot reach it.- reportAccountLinkBlock(error);+ reportAccountLinkBlock(error, context);throw error;}// 204 / empty-body responses have nothing to parse.@@ -150,7 +155,7 @@ async function localJson<T>(new URL(`${localBaseUrl()}${path}`, window.location.origin),options,);- if (demo) return unwrap<T>(demo);+ if (demo) return unwrap<T>(demo, options.accountLinkBlockContext);const res = await fetch(`${localBaseUrl()}${path}`, {method: options.method ?? "GET",headers: {@@ -169,7 +174,7 @@ async function localJson<T>(// Spring token to re-show login; SaaS lets the auth boundary handle it).onLocalUnauthorized();}- return unwrap<T>(res);+ return unwrap<T>(res, options.accountLinkBlockContext);}/** GET returning a binary Blob (e.g. a CSV/JSON export download), via the@@ -211,7 +216,11 @@ async function localForm<T>(/** POST a multipart/form-data body (file uploads), via the localBackend seam. The Content-Type is* deliberately left unset so the browser writes it with the multipart boundary. */-async function localMultipart<T>(path: string, body: FormData): Promise<T> {+async function localMultipart<T>(+ path: string,+ body: FormData,+ context?: AccountLinkBlockContext,+): Promise<T> {const res = await fetch(`${localBaseUrl()}${path}`, {method: "POST",headers: { Accept: "application/json", ...(await localAuthHeader()) },@@ -220,7 +229,7 @@ async function localMultipart<T>(path: string, body: FormData): Promise<T> {if (res.status === 401) {onLocalUnauthorized();}- return unwrap<T>(res);+ return unwrap<T>(res, context);}// ────────────────────────────────────────────────────────────────────────────diff --git a/frontend/editor/src/portal/api/pipelines.ts b/frontend/editor/src/portal/api/pipelines.tsindex 940d8d9c7f..fdedd95220 100644--- a/frontend/editor/src/portal/api/pipelines.ts+++ b/frontend/editor/src/portal/api/pipelines.ts@@ -220,7 +220,10 @@ export interface TriggerOutcome {export async function triggerPipeline(id: string): Promise<TriggerOutcome> {return apiClient.local.json<TriggerOutcome>(`/api/v1/policies/${encodeURIComponent(id)}/trigger`,- { method: "POST" },+ {+ method: "POST",+ accountLinkBlockContext: { pipelineId: id, trigger: "manual" },+ },);}@@ -270,6 +273,11 @@ export async function runPipelineTest(const res = await apiClient.local.multipart<{ jobId: string }>("/api/v1/policies/run",form,+ {+ pipelineId: policyId,+ pipelineName: definition.name,+ trigger: "manual",+ },);return { runId: res.jobId };}diff --git a/frontend/editor/src/portal/components/AppShell.css b/frontend/editor/src/portal/components/AppShell.cssindex ffbfc2fb21..63e34f58a7 100644--- a/frontend/editor/src/portal/components/AppShell.css+++ b/frontend/editor/src/portal/components/AppShell.css@@ -35,6 +35,12 @@animation: fadeInUp var(--motion-enter) both;}+.portal-shell__view > .portal-connect-rail {+ width: calc(100% - 3rem);+ max-width: 75rem;+ margin: 0.75rem auto 0;+}+/* Mobile topbar — hidden on desktop, where the sidebar is always visible.Height matches the sidebar's logo row so the brand sits at the same level. */.portal-shell__topbar {diff --git a/frontend/editor/src/portal/components/AppShell.tsx b/frontend/editor/src/portal/components/AppShell.tsxindex 30758725da..723285efb9 100644--- a/frontend/editor/src/portal/components/AppShell.tsx+++ b/frontend/editor/src/portal/components/AppShell.tsx@@ -12,6 +12,7 @@ import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostimport "@portal/components/AppShell.css";import { NotificationBell } from "@app/components/notifications/NotificationBell";import { useIsPhone } from "@app/hooks/useIsMobile";+import { ConnectAccountRail } from "@portal/components/ConnectAccountRail";/*** Compact header shown only under the mobile breakpoint (CSS-hidden on@@ -104,7 +105,10 @@ export function AppShell({ children }: { children: ReactNode }) {<NotificationBell /></div>)}- <main className="portal-shell__view">{children}</main>+ <main className="portal-shell__view">+ <ConnectAccountRail />+ {children}+ </main></div></div>);diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.css b/frontend/editor/src/portal/components/ConnectAccountRail.cssnew file mode 100644index 0000000000..079b161cf1--- /dev/null+++ b/frontend/editor/src/portal/components/ConnectAccountRail.css@@ -0,0 +1,48 @@+.portal-connect-rail {+ display: flex;+ align-items: center;+ gap: 1rem;+ padding: 0.875rem 1rem;+ margin-bottom: 0.75rem;+ border: 1px solid var(--c-border);+ border-radius: 0.5rem;+ background: var(--c-surface);+}++.portal-connect-rail__text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}++.portal-connect-rail__title {+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--c-text);+}++.portal-connect-rail__sub {+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}++.portal-connect-rail__actions {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin-left: auto;+ flex: none;+ flex-wrap: wrap;+ max-width: 100%;+}++@media (max-width: 40rem) {+ .portal-connect-rail {+ flex-direction: column;+ align-items: flex-start;+ }++ .portal-connect-rail__actions {+ margin-left: 0;+ }+}diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.stories.tsx b/frontend/editor/src/portal/components/ConnectAccountRail.stories.tsxnew file mode 100644index 0000000000..1bcca3018c--- /dev/null+++ b/frontend/editor/src/portal/components/ConnectAccountRail.stories.tsx@@ -0,0 +1,89 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse } from "msw";+import { useAuth } from "@app/auth";+import { AuthContext } from "@app/auth/context";+import { LinkProvider, type LinkState } from "@portal/contexts/LinkContext";+import { ConnectAccountRail } from "@portal/components/ConnectAccountRail";++/**+ * Both halves of "can link but has not" come from outside the component, and the global mock answers+ * app-config without the flag — so a story that wants the rail has to ask for it.+ */+const canLink = {+ msw: {+ handlers: [+ http.get("/api/v1/account-link/free-tier", () =>+ HttpResponse.json({+ grantUnits: 500,+ usedUnits: 500,+ remainingUnits: 0,+ periodStart: "2026-09-01T00:00:00",+ periodEnd: "2026-10-01T00:00:00",+ }),+ ),+ http.get("/api/v1/config/app-config", () =>+ HttpResponse.json({ accountLinkAvailable: true }),+ ),+ ],+ },+};++const withLinkState = (state: LinkState) => [+ (Story: () => React.JSX.Element) => (+ <LinkProvider initialState={state}>+ <Story />+ </LinkProvider>+ ),+];++const meta: Meta<typeof ConnectAccountRail> = {+ title: "Portal/AccountLink/ConnectAccountRail",+ component: ConnectAccountRail,+ parameters: { layout: "padded" },+ decorators: [+ function Administrator(Story) {+ const auth = useAuth();+ return (+ <AuthContext.Provider+ value={{ ...auth, isAdmin: true, loading: false }}+ >+ <Story />+ </AuthContext.Provider>+ );+ },+ ],+};+export default meta;+type Story = StoryObj<typeof ConnectAccountRail>;++/** Exhausted local allowance; retains the bespoke rail styling across Processor pages. */+export const Default: Story = {+ parameters: canLink,+ decorators: withLinkState("unlinked"),+};++/** Connected, so the rail removes itself. Renders nothing on purpose. */+export const Hidden: Story = {+ parameters: canLink,+ decorators: withLinkState("linked-free"),+};++export const CreditsRemaining: Story = {+ parameters: {+ msw: {+ handlers: [+ ...canLink.msw.handlers.filter((_handler, index) => index !== 0),+ http.get("/api/v1/account-link/free-tier", () =>+ HttpResponse.json({+ grantUnits: 500,+ usedUnits: 120,+ remainingUnits: 380,+ periodStart: "2026-09-01T00:00:00",+ periodEnd: "2026-10-01T00:00:00",+ }),+ ),+ ],+ },+ },+ decorators: withLinkState("unlinked"),+};diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.test.tsx b/frontend/editor/src/portal/components/ConnectAccountRail.test.tsxnew file mode 100644index 0000000000..0d9ba11eee--- /dev/null+++ b/frontend/editor/src/portal/components/ConnectAccountRail.test.tsx@@ -0,0 +1,92 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { ConnectAccountRail } from "@portal/components/ConnectAccountRail";+import {+ clearAccountLinkBlock,+ reportFreeTierExhausted,+} from "@app/services/accountLinkBlock";+import { PortalTestProviders } from "@portal/test/TestQueryProvider";++const mocks = vi.hoisted(() => ({+ isAdmin: true,+ linked: false,+ balance: undefined as+ | { remainingUnits: number; periodEnd: string }+ | undefined,+ openLinkModal: vi.fn(),+}));+vi.mock("@app/auth", () => ({ useAuth: () => ({ isAdmin: mocks.isAdmin }) }));+vi.mock("@app/ui", async () => ({ ...(await import("@app/ui/Button")) }));+vi.mock("@portal/hooks/useFreeTierBalance", () => ({+ useFreeTierBalance: () => ({ data: mocks.balance }),+}));+vi.mock("@portal/contexts/LinkContext", () => ({+ useLinkOptional: () => ({ isLinked: mocks.linked }),+}));+vi.mock("@portal/contexts/UIContext", () => ({+ useUI: () => ({ openLinkModal: mocks.openLinkModal }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback: string) => fallback,+ i18n: { language: "en-US" },+ }),+}));++describe("exhausted Processor rail", () => {+ beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ mocks.isAdmin = true;+ mocks.linked = false;+ mocks.balance = undefined;+ mocks.openLinkModal.mockReset();+ });+ const mount = () =>+ render(+ <PortalTestProviders>+ <ConnectAccountRail />+ </PortalTestProviders>,+ );++ it("does not pitch linking just because the server is unlinked", () => {+ mount();+ expect(screen.queryByRole("status")).toBeNull();+ });+ it("keeps the bespoke rail actionable after a background failure", () => {+ const view = mount();+ act(() => reportFreeTierExhausted());+ expect(+ view.container.querySelector(".portal-connect-rail"),+ ).toBeInTheDocument();+ expect(screen.getByText(/Team plan/)).toBeInTheDocument();+ expect(mocks.openLinkModal).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole("button", { name: "Link account for more credits" }),+ );+ expect(mocks.openLinkModal).toHaveBeenCalledWith("exhausted");+ });+ it("shows an exhausted balance without automatically opening a dialog", () => {+ mocks.balance = { remainingUnits: 0, periodEnd: "2026-10-01T00:00:00" };+ mount();+ expect(screen.getByRole("status")).toBeInTheDocument();+ expect(mocks.openLinkModal).not.toHaveBeenCalled();+ });+ it("directs members to an administrator", () => {+ mocks.isAdmin = false;+ reportFreeTierExhausted();+ mount();+ expect(+ screen.getByText(/Ask your server administrator/),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Link account for more credits" }),+ ).toBeNull();+ });+ it("removes the notice after linking", () => {+ mocks.linked = true;+ reportFreeTierExhausted();+ mount();+ expect(screen.queryByRole("status")).toBeNull();+ });+});diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.tsx b/frontend/editor/src/portal/components/ConnectAccountRail.tsxnew file mode 100644index 0000000000..07fd009efb--- /dev/null+++ b/frontend/editor/src/portal/components/ConnectAccountRail.tsx@@ -0,0 +1,65 @@+import { useTranslation } from "react-i18next";+import { useAuth } from "@app/auth";+import { Button } from "@app/ui";+import { formatPeriodDate } from "@app/billing";+import { useAccountLinkBlock } from "@app/services/accountLinkBlock";+import { useFreeTierBalance } from "@portal/hooks/useFreeTierBalance";+import { useLinkOptional } from "@portal/contexts/LinkContext";+import { useUI } from "@portal/contexts/UIContext";+import "@portal/components/ConnectAccountRail.css";++/** The exhausted allowance stays actionable across Processor routes, even after the dialog closes. */+export function ConnectAccountRail() {+ const { t } = useTranslation();+ const { isAdmin } = useAuth();+ const link = useLinkOptional();+ const { openLinkModal } = useUI();+ const { exhausted } = useAccountLinkBlock();+ const { data: balance } = useFreeTierBalance();+ if (!link || link.isLinked || (!exhausted && balance?.remainingUnits !== 0))+ return null;+ const resets = balance ? formatPeriodDate(balance.periodEnd) : null;++ return (+ <section className="portal-connect-rail" role="status">+ <div className="portal-connect-rail__text">+ <b className="portal-connect-rail__title">+ {t(+ "portal.accountLink.rail.exhaustedTitle",+ "This server’s free credits are used up",+ )}+ </b>+ <span className="portal-connect-rail__sub">+ {isAdmin+ ? t(+ "portal.accountLink.rail.exhaustedSub",+ "Link for monthly credits, shared billing and the option to grow with a Team plan.",+ )+ : t(+ "portal.accountLink.rail.adminSub",+ "Ask your server administrator to link a Stirling account for more credits. Manual PDF tools are still available.",+ )}+ {resets && (+ <>+ {" "}+ {t("portal.usage.freeTier.resets", "Resets {{date}}", {+ date: resets,+ })}+ .+ </>+ )}+ </span>+ </div>+ <div className="portal-connect-rail__actions">+ <Button variant="primary" onClick={() => openLinkModal("exhausted")}>+ {isAdmin+ ? t(+ "portal.accountLink.rail.exhaustedCta",+ "Link account for more credits",+ )+ : t("portal.accountLink.rail.adminCta", "How to get more credits")}+ </Button>+ </div>+ </section>+ );+}diff --git a/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx b/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsxindex 123199ecad..5ae67d784f 100644--- a/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx+++ b/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx@@ -1,5 +1,6 @@import { useEffect, useRef } from "react";import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { clearAccountLinkBlock } from "@app/services/accountLinkBlock";import { useLocation, useNavigate } from "react-router-dom";import { completeConnect, type ConnectPhase } from "@app/portal/api/link";import { ensureSaasSupabase } from "@app/portal/auth/saasSupabase";@@ -131,6 +132,7 @@ export function ConnectCallbackHost() {return;}accepted = true;+ clearAccountLinkBlock();await refreshRef.current();if (!current()) return;}diff --git a/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsx b/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsxindex 0b2e470c4b..1038d46222 100644--- a/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsx+++ b/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsx@@ -2,7 +2,7 @@ import { useTranslation } from "react-i18next";import { Banner, Spinner } from "@app/ui";import { ConnectDoneSlide } from "@app/portal/components/account-link/connect/ConnectDoneSlide";import type { ConnectMode } from "@app/portal/auth/pendingConnect";-import "@app/portal/components/account-link/connect/connect.css";+import "@app/components/account-link/connect.css";/** Outcomes of returning from the approval page. */export type ConnectCallbackState =diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsxindex b7ba6647bf..fe97f69a4c 100644--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx@@ -1,10 +1,29 @@import type { Meta, StoryObj } from "@storybook/react-vite";+import { useAuth } from "@app/auth";+import { AuthContext } from "@app/auth/context";+import { http, HttpResponse } from "msw";import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";const meta: Meta<typeof LinkAccountModal> = {title: "Portal/AccountLink/LinkAccountModal",component: LinkAccountModal,parameters: { layout: "fullscreen" },+ decorators: [+ function Viewer(Story, context) {+ const auth = useAuth();+ return (+ <AuthContext.Provider+ value={{+ ...auth,+ isAdmin: context.parameters.accountLinkAdmin !== false,+ loading: false,+ }}+ >+ <Story />+ </AuthContext.Provider>+ );+ },+ ],args: {open: true,onClose: () => {},@@ -24,3 +43,30 @@ export const Default: Story = {};export const Reauth: Story = {args: { mode: "reauth" },};++export const Exhausted: Story = {+ args: { mode: "exhausted" },+ parameters: {+ msw: {+ handlers: [+ http.get("/api/v1/config/app-config", () =>+ HttpResponse.json({ accountLinkAvailable: true }),+ ),+ http.get("/api/v1/account-link/free-tier", () =>+ HttpResponse.json({+ grantUnits: 500,+ usedUnits: 500,+ remainingUnits: 0,+ periodStart: "2026-09-01T00:00:00",+ periodEnd: "2026-10-01T00:00:00",+ }),+ ),+ ],+ },+ },+};++export const TeamMember: Story = {+ args: { mode: "exhausted" },+ parameters: { accountLinkAdmin: false },+};diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsxindex 1f7b305f4a..853998647c 100644--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx@@ -16,6 +16,23 @@ const { startConnect, startReauth, fetchWallet, EMAIL } = vi.hoisted(() => ({EMAIL: "[email protected]",}));+vi.mock("@portal/hooks/useFreeTierBalance", () => ({+ useFreeTierBalance: () => ({+ data: {+ grantUnits: 500,+ remainingUnits: 0,+ periodEnd: "2026-10-01T00:00:00",+ },+ }),+}));+vi.mock("@app/ui", async () => ({+ ...(await import("@app/ui/Button")),+ ...(await import("@app/ui/Banner")),+ ...(await import("@app/ui/Modal")),+ ...(await import("@app/ui/Skeleton")),+ ...(await import("@app/ui/Spinner")),+}));+vi.mock("@app/portal/api/link", () => ({ startConnect, startReauth }));vi.mock("@app/portal/api/billing", () => ({ fetchWallet }));vi.mock("@app/portal/auth/saasSupabase", () => ({@@ -32,6 +49,10 @@ vi.mock("@app/portal/auth/saasSupabase", () => ({}),}));+import {+ clearAccountLinkBlock,+ reportFreeTierExhausted,+} from "@app/services/accountLinkBlock";import {LinkAccountModal,LinkAccountModalHost,@@ -67,7 +88,7 @@ vi.mock("@app/constants/app", async (importOriginal) => ({withBasePath: (path: string) => `${deployment.basePath}${path}`,}));-const BENEFITS = "Pipelines, policies, sources and audit";+const BENEFITS = "Add more users with a paid Team plan";const GHOST = /Opening Stirling sign-in/;const CONNECT = /Connect Stirling account/;@@ -105,6 +126,31 @@ function filledSteps(): number {describe("LinkAccountModal", () => {let assign: ReturnType<typeof vi.fn>;+ it("omits pipeline controls for a banner prompt even after a pipeline failure", () => {+ clearAccountLinkBlock();+ reportFreeTierExhausted({+ pipelineId: "rotate",+ trigger: "upload",+ });+ renderModal("exhausted");+ expect(screen.getByRole("dialog")).toBeTruthy();+ expect(screen.queryByText("Active pipelines")).toBeNull();+ expect(+ screen.queryByRole("button", { name: "Open pipeline settings" }),+ ).toBeNull();+ clearAccountLinkBlock();+ });++ it("returns keyboard focus to the trigger when the dialog unmounts", () => {+ const trigger = document.createElement("button");+ document.body.append(trigger);+ trigger.focus();+ const view = renderModal("exhausted");+ view.unmount();+ expect(document.activeElement).toBe(trigger);+ trigger.remove();+ });+beforeEach(() => {vi.clearAllMocks();ownership.isAdmin = true;@@ -131,6 +177,7 @@ describe("LinkAccountModal", () => {value: {origin: "http://localhost:5173",hostname: "localhost",+ pathname: "/processor/pipelines",href: "http://localhost:5173/app",search: "",assign,@@ -522,4 +569,34 @@ describe("LinkAccountModal", () => {expect(screen.queryByRole("button", { name: /Try again/ })).toBeNull();});});++ it("leads with credits and explains which benefits need a paid plan", async () => {+ renderModal("exhausted");+ expect(screen.getByText("Keep your workflows running")).toBeTruthy();+ expect(screen.getByText(BENEFITS)).toBeTruthy();+ expect(screen.queryByText(/Linking does not start a paid plan/)).toBeNull();+ expect(+ screen.queryByText(/Manual PDF tools are still available/),+ ).toBeNull();+ expect(screen.queryByText("500 free per month")).toBeNull();+ expect(filledSteps()).toBe(0);+ click("Link account for more credits");+ await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));+ });++ it.each([+ { isAdmin: false, orgOwner: false },+ { isAdmin: true, orgOwner: false },+ ])("offers non-owners guidance without a handshake: %j", (roles) => {+ Object.assign(ownership, roles);+ renderModal("exhausted");+ expect(screen.getByText(/open Usage & billing/)).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Copy message for administrator" }),+ ).toBeTruthy();+ expect(+ screen.queryByRole("button", { name: "Link account for more credits" }),+ ).toBeNull();+ expect(startConnect).not.toHaveBeenCalled();+ });});diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsxindex 41e50524e8..5da0a98233 100644--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx@@ -1,4 +1,9 @@import { useTranslation } from "react-i18next";+import { useEffect, useRef, type ReactNode } from "react";+import { useNavigate } from "react-router-dom";+import { PORTAL_BASENAME } from "@app/routes/portalBasename";+import { ExhaustedAccountLinkModal } from "@app/components/account-link/ExhaustedAccountLinkModal";+import type { AccountLinkBlockContext } from "@app/services/accountLinkBlock";import { Button } from "@app/ui";import { FlowModal } from "@app/portal/components/shared/FlowModal";import { StepModalHeader } from "@app/portal/components/shared/StepModalHeader";@@ -23,6 +28,8 @@ const STEP_ORDER = ["ask", "handoff", "outcome"] as const;type StepId = (typeof STEP_ORDER)[number];interface Props {+ failureContext?: AccountLinkBlockContext;+ summary?: ReactNode;open: boolean;onClose: () => void;/** "reauth" only re-establishes the browser session, so it stays one step with no pitch. */@@ -33,14 +40,21 @@ interface Props {/** Unmounting on close discards an interrupted handoff before the next attempt. */export function LinkAccountModalHost() {- const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =- useUI();+ const {+ linkModalOpen,+ linkModalMode,+ linkModalFailureContext,+ closeLinkModal,+ connectOutcome,+ } = useUI();const isOwner = useAccountLinkOwner();- if (!isOwner || !linkModalOpen) return null;+ if (!linkModalOpen || (!isOwner && linkModalMode !== "exhausted"))+ return null;return (<LinkAccountModalopenmode={linkModalMode}+ failureContext={linkModalFailureContext}onClose={closeLinkModal}outcome={connectOutcome}/>@@ -56,8 +70,24 @@ export function LinkAccountModal({onClose,mode = "link",outcome = null,+ summary,+ failureContext,}: Props) {const { t } = useTranslation();+ const isOwner = useAccountLinkOwner();+ const navigate = useNavigate();+ const trigger = useRef(document.activeElement);+ useEffect(+ () => () => {+ if (+ trigger.current instanceof HTMLElement &&+ trigger.current.isConnected+ ) {+ trigger.current.focus({ preventScroll: true });+ }+ },+ [],+ );const reauth =mode === "reauth" ||(outcome?.state === "linked" && !outcome.sessionRestored);@@ -88,6 +118,30 @@ export function LinkAccountModal({),};+ if (exhausted && !reauth && step === "ask") {+ return (+ <ExhaustedAccountLinkModal+ open={open}+ onClose={onClose}+ canLink={isOwner}+ failureContext={failureContext}+ onStart={isOwner ? handoff.begin : undefined}+ onManagePipeline={(id) =>+ navigate(+ `${PORTAL_BASENAME}/pipelines${id ? `/${encodeURIComponent(id)}` : ""}`,+ )+ }+ >+ <ConnectAskStep+ reauth={false}+ exhausted+ error={handoff.error}+ summary={summary}+ />+ </ExhaustedAccountLinkModal>+ );+ }+return (<FlowModalopen={open}diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsxindex feacd71e6e..41f37b37c8 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx@@ -1,8 +1,11 @@+import type { ReactNode } from "react";import { useTranslation } from "react-i18next";import { Banner } from "@app/ui";import { isSaasSupabaseConfigured } from "@app/portal/auth/saasSupabase";import { ConnectBenefitsSlide } from "@app/portal/components/account-link/connect/ConnectBenefitsSlide";-import "@app/portal/components/account-link/connect/connect.css";+import { FreeTierExhaustedSummary } from "@app/portal/components/account-link/connect/FreeTierExhaustedSummary";+import { ExhaustedAccountLinkContent } from "@app/components/account-link/ExhaustedAccountLinkModal";+import "@app/components/account-link/connect.css";interface Props {/** Re-auth says why it is being asked; a first link is pitched instead. */@@ -14,9 +17,16 @@ interface Props {exhausted?: boolean;/** A hand-off that failed to start drops back here, so this is where its reason belongs. */error?: string | null;+ /** Undefined uses the Processor ledger; null deliberately omits unavailable figures. */+ summary?: ReactNode;}-export function ConnectAskStep({ reauth, exhausted = false, error }: Props) {+export function ConnectAskStep({+ reauth,+ exhausted = false,+ error,+ summary,+}: Props) {const { t } = useTranslation();return (@@ -28,18 +38,14 @@ export function ConnectAskStep({ reauth, exhausted = false, error }: Props) {"Your Stirling session expired. Signing in again keeps usage and billing visible. This server stays connected either way.",)}</p>+ ) : exhausted ? (+ <ExhaustedAccountLinkContent+ summary={+ summary === undefined ? <FreeTierExhaustedSummary /> : summary+ }+ />) : (- <>- {exhausted && (- <p className="portal-connect__lede">- {t(- "portal.accountLink.connect.exhaustedLede",- "This server has used its free credits for the month. They reset when the period rolls over. Connecting a Stirling account adds a further monthly allowance on top.",- )}- </p>- )}- <ConnectBenefitsSlide />- </>+ <ConnectBenefitsSlide />)}{!isSaasSupabaseConfigured && (diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectBenefitsSlide.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectBenefitsSlide.tsxindex 95b122369b..521d968e8a 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectBenefitsSlide.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectBenefitsSlide.tsx@@ -1,51 +1 @@-import { useTranslation } from "react-i18next";-import "@portal/components/account-link/connect/connect.css";--/**- * Processor is one row naming its parts rather than four competing ones, and credits come last:- * first, and the screen reads as a price list.- */-export function ConnectBenefitsSlide() {- const { t } = useTranslation();-- const unlocks: { key: string; label: string; detail: string }[] = [- {- key: "processor",- label: t(- "portal.accountLink.connect.benefits.processorLabel",- "Processor",- ),- detail: t(- "portal.accountLink.connect.benefits.processorDetail",- "Pipelines, policies, sources and audit",- ),- },- {- key: "teams",- label: t("portal.accountLink.connect.benefits.teamsLabel", "Teams"),- detail: t(- "portal.accountLink.connect.benefits.teamsDetail",- "Free for up to 5 users",- ),- },- {- key: "credits",- label: t("portal.accountLink.connect.benefits.creditsLabel", "Credits"),- detail: t(- "portal.accountLink.connect.benefits.creditsDetailMonthly",- "Free monthly allowance",- ),- },- ];-- return (- <dl className="portal-connect__list">- {unlocks.map((unlock) => (- <div className="portal-connect__row" key={unlock.key}>- <dt className="portal-connect__row-label">{unlock.label}</dt>- <dd className="portal-connect__row-detail">{unlock.detail}</dd>- </div>- ))}- </dl>- );-}+export { ConnectBenefitsSlide } from "@app/components/account-link/ConnectBenefitsSlide";diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsxindex 603f7ade25..341cf1905b 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsx@@ -6,7 +6,7 @@ import { fetchWallet, type Wallet } from "@portal/api/billing";import { useLinkedAccountEmail } from "@portal/hooks/useLinkedAccountEmail";import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";import "@portal/components/billing/billing.css";-import "@portal/components/account-link/connect/connect.css";+import "@app/components/account-link/connect.css";interface Props {/** Closes the dialog first, so a next step does not land behind the overlay. */diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsxindex ec44fe7281..1b5cdee0d3 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsx@@ -1,6 +1,6 @@import { useTranslation } from "react-i18next";import { Spinner } from "@app/ui";-import "@app/portal/components/account-link/connect/connect.css";+import "@app/components/account-link/connect.css";export function ConnectHandoffGhost() {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/account-link/connect/FreeTierExhaustedSummary.tsx b/frontend/editor/src/portal/components/account-link/connect/FreeTierExhaustedSummary.tsxnew file mode 100644index 0000000000..ccd1dcf60b--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/connect/FreeTierExhaustedSummary.tsx@@ -0,0 +1,8 @@+import { useFreeTierBalance } from "@portal/hooks/useFreeTierBalance";+import { FreeTierBalanceSummary } from "@app/components/account-link/FreeTierBalanceSummary";++/** Reads the Processor ledger and omits unavailable figures. */+export function FreeTierExhaustedSummary() {+ const { data: balance } = useFreeTierBalance();+ return <FreeTierBalanceSummary balance={balance} />;+}diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsxindex ae3ad1aa07..e442f28934 100644--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx@@ -1,22 +1,29 @@import { beforeEach, describe, expect, it, vi } from "vitest";import type { ReactNode } from "react";-import { render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MantineProvider } from "@mantine/core";import { MemoryRouter } from "react-router-dom";import { PortalTestProviders } from "@portal/test/TestQueryProvider";+import type { ServerPlan } from "@app/billing/serverPlan";+import { qk } from "@portal/queries/keys";/*** The unlinked usage page renders the shared billing screen from the instance's own ledger and* nothing else — no wallet, so no claim about linkage — and it has to survive its endpoints being* admin-only, since a non-admin can hold a portal grant and reach this page.*/-const { fetchFreeTier, fetchFleetStats, fetchUsers, openLinkModal } =+const { fetchFreeTier, fetchFleetStats, fetchUsers, openLinkModal, auth } =vi.hoisted(() => ({fetchFreeTier: vi.fn(),fetchFleetStats: vi.fn(),fetchUsers: vi.fn(),openLinkModal: vi.fn(),+ auth: { isAdmin: true },}));+vi.mock("@app/auth", () => ({ useAuth: () => auth }));+vi.mock("@portal/api/link", () => ({ fetchFreeTier }));vi.mock("@portal/queries/infrastructure", () => ({useFleetStats: () => ({ data: null, loading: false, error: null }),@@ -47,17 +54,21 @@ const BALANCE = {periodEnd: "2026-10-01T00:00:00",};-const renderView = (licenseSection?: ReactNode) =>+const renderView = (serverPlan?: ServerPlan, licenseSection?: ReactNode) =>render(<PortalTestProviders><MemoryRouter>- <FreeTierPlanView licenseSection={licenseSection} />+ <FreeTierPlanView+ serverPlan={serverPlan}+ licenseSection={licenseSection}+ /></MemoryRouter></PortalTestProviders>,);describe("FreeTierPlanView", () => {beforeEach(() => {+ auth.isAdmin = true;fetchFreeTier.mockReset();fetchFleetStats.mockReset().mockRejectedValue(new Error("no stats"));fetchUsers.mockReset().mockRejectedValue(new Error("not admin"));@@ -72,7 +83,7 @@ describe("FreeTierPlanView", () => {fetchFreeTier.mockRejectedValue(new HttpError(500, "Server Error", null),);- renderView(<button>Manage local license</button>);+ renderView(undefined, <button>Manage local license</button>);await screen.findByText(state === "ready" ? "120 of 500 used" : "Couldn't load credit usage",);@@ -101,6 +112,28 @@ describe("FreeTierPlanView", () => {expect(fetchFreeTier).toHaveBeenCalledTimes(1);});+ it("keeps cached usage visible when a background refetch fails", async () => {+ fetchFreeTier.mockResolvedValue(BALANCE);+ const client = new QueryClient();+ render(+ <QueryClientProvider client={client}>+ <MantineProvider>+ <MemoryRouter>+ <FreeTierPlanView />+ </MemoryRouter>+ </MantineProvider>+ </QueryClientProvider>,+ );+ await screen.findByText("120 of 500 used");+ fetchFreeTier.mockRejectedValue(new HttpError(500, "Server Error", null));+ await act(async () => {+ await client.refetchQueries({ queryKey: qk.freeTier() });+ });+ expect(client.getQueryState(qk.freeTier())?.status).toBe("error");+ expect(screen.getByText("120 of 500 used")).toBeInTheDocument();+ expect(screen.queryByText("Couldn't load credit usage")).toBeNull();+ });+it("shows the users this server may have when the admin endpoint answers", async () => {fetchFreeTier.mockResolvedValue(BALANCE);fetchUsers.mockResolvedValue({ summary: { seatsUsed: 3, seatLimit: 5 } });@@ -145,4 +178,55 @@ describe("FreeTierPlanView", () => {await screen.findByText("Couldn't load credit usage"),).toBeInTheDocument();});++ it("does not offer linking or fetch admin figures for a member", async () => {+ auth.isAdmin = false;+ renderView();++ expect(+ await screen.findByText(/only an administrator/),+ ).toBeInTheDocument();+ expect(fetchFreeTier).not.toHaveBeenCalled();+ expect(fetchUsers).not.toHaveBeenCalled();+ expect(+ screen.queryByRole("button", {+ name: /Connect a Stirling account|Link account for more credits/,+ }),+ ).toBeNull();+ });++ it("puts a recovery CTA beside an exhausted meter", async () => {+ fetchFreeTier.mockResolvedValue({+ ...BALANCE,+ remainingUnits: 0,+ usedUnits: 500,+ });+ renderView();+ fireEvent.click(+ await screen.findByRole("button", {+ name: "Link account for more credits",+ }),+ );+ expect(openLinkModal).toHaveBeenCalledWith("exhausted");+ });++ it("keeps Enterprise linking optional when the local ledger is empty", async () => {+ fetchFreeTier.mockResolvedValue({+ ...BALANCE,+ remainingUnits: 0,+ usedUnits: 500,+ });+ renderView({ licenseType: "ENTERPRISE", maxUsers: 10, usersInUse: 3 });++ expect(+ await screen.findByText(/Your Enterprise license includes processing/),+ ).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Connect a Stirling account" }),+ );+ expect(openLinkModal).toHaveBeenCalledWith("link");+ expect(+ screen.queryByRole("button", { name: "Link account for more credits" }),+ ).toBeNull();+ });});diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsxindex 7637b52977..1e3587451f 100644--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx@@ -1,6 +1,9 @@import type { ReactNode } from "react";import type { ServerPlan } from "@app/billing/serverPlan";import { useEffect, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { useAuth } from "@app/auth";+import { qk } from "@portal/queries/keys";import { useTranslation } from "react-i18next";import { Banner, Button, Card } from "@app/ui";import { BillingScreen } from "@app/billing";@@ -87,26 +90,31 @@ export function FreeTierPlanView({serverPlanAction?: ReactNode;}) {const { t } = useTranslation();+ const { isAdmin } = useAuth();const { openLinkModal } = useUI();- // An outcome, not a rendered message: the effect must not depend on `t`, whose identity is- // not stable across renders.- const [load, setLoad] = useState<Load>({ state: "loading" });+ const query = useQuery({+ queryKey: qk.freeTier(),+ queryFn: fetchFreeTier,+ enabled: isAdmin,+ refetchInterval: 60_000,+ retry: false,+ });+ let load: Load = { state: "loading" };+ if (!isAdmin) load = { state: "forbidden" };+ else if (query.data) load = { state: "ready", balance: query.data };+ else if (query.isError) {+ const denied =+ query.error instanceof HttpError &&+ (query.error.status === 401 || query.error.status === 403);+ load = { state: denied ? "forbidden" : "failed" };+ }const [seats, setSeats] = useState<Seats | null>(null);const { data: fleetStats } = useFleetStats();const editorsDeployed = fleetStats?.editorsDeployed ?? null;useEffect(() => {+ if (!isAdmin) return;let cancelled = false;- fetchFreeTier()- .then((balance) => {- if (!cancelled) setLoad({ state: "ready", balance });- })- .catch((e: unknown) => {- if (cancelled) return;- const denied =- e instanceof HttpError && (e.status === 401 || e.status === 403);- setLoad({ state: denied ? "forbidden" : "failed" });- });// User counts are best-effort: this page is the credit meter, and a row is dropped rather than// guessed at when its source cannot answer.usersBackend@@ -120,10 +128,17 @@ export function FreeTierPlanView({return () => {cancelled = true;};- }, []);+ }, [isAdmin]);const wallet =load.state === "ready" ? localWallet(load.balance, seats) : null;+ const exhausted =+ serverPlan?.licenseType !== "ENTERPRISE" &&+ load.state === "ready" &&+ load.balance.remainingUnits === 0;+ const onLink = isAdmin+ ? () => openLinkModal(exhausted ? "exhausted" : "link")+ : undefined;return (<BillingScreen@@ -135,8 +150,8 @@ export function FreeTierPlanView({serverPlanAction={serverPlanAction}editorsDeployed={editorsDeployed}pdfsProcessed={fleetStats?.pdfsProcessed ?? null}- onAddCapacity={() => openLinkModal()}- onActivateProcessor={() => openLinkModal()}+ onAddCapacity={onLink}+ onActivateProcessor={onLink}notices={<><Banner@@ -147,12 +162,19 @@ export function FreeTierPlanView({"This server has no Stirling account",)}action={- <Button size="sm" onClick={() => openLinkModal()}>- {t(- "portal.usage.freeTier.connect",- "Connect a Stirling account",- )}- </Button>+ isAdmin ? (+ <Button size="sm" onClick={onLink}>+ {exhausted+ ? t(+ "portal.accountLink.rail.exhaustedCta",+ "Link account for more credits",+ )+ : t(+ "portal.usage.freeTier.connect",+ "Connect a Stirling account",+ )}+ </Button>+ ) : undefined}>{serverPlan?.licenseType === "ENTERPRISE"diff --git a/frontend/editor/src/portal/components/billing/billing.css b/frontend/editor/src/portal/components/billing/billing.cssindex e33f8953e1..93bd5268d8 100644--- a/frontend/editor/src/portal/components/billing/billing.css+++ b/frontend/editor/src/portal/components/billing/billing.css@@ -1,3 +1,5 @@+@import "../../../proprietary/billing/MeterBar.css";+/* Portal billing page — paired with views/Usage.tsx (.portal-billing root). */.portal-billing__stack {@@ -208,45 +210,6 @@lands these can be deduped via a shared stylesheet. *//* Flat by default — the meter sits directly on its card, no inner panel box(shared by the free trial meter and the subscribed spend meter). */-.paygf-meter {- margin-top: 0.6rem;-}-.paygf-meter__top {- display: flex;- align-items: center;- justify-content: space-between;- gap: 10px;-}-.paygf-meter__figure {- display: flex;- align-items: baseline;- gap: 7px;-}-.paygf-meter__num {- font-size: 1.7rem;- font-weight: 750;- line-height: 1;- letter-spacing: -0.02em;- color: var(--c-text);- font-variant-numeric: tabular-nums;-}-.paygf-meter__cap {- font-size: 0.85rem;- color: var(--c-text-subtle);- font-variant-numeric: tabular-nums;-}-.paygf-meter .payg-bar {- margin-top: 11px;-}-.paygf-meter__meta {- margin-top: 10px;- display: flex;- flex-wrap: wrap;- align-items: center;- gap: 6px 10px;- font-size: 0.78rem;- color: var(--c-text-muted);-}/* Status chip (Healthy / Approaching / Cap reached). Solid hex coloursintentionally — the chip palette is semantic, not theme-bound. */@@ -291,28 +254,6 @@}/* Segmented usage bar */-.payg-bar {- margin-top: 18px;- height: 10px;- border-radius: 999px;- background: var(--color-bg-subtle, var(--c-surface-sunken));- overflow: hidden;- position: relative;-}-.payg-bar__fill {- height: 100%;- border-radius: 999px;- transition: width 0.5s cubic-bezier(0.16, 1, 0.3, 1);-}-.payg-bar__fill[data-state="FULL"] {- background: var(--c-primary);-}-.payg-bar__fill[data-state="WARNED"] {- background: var(--color-amber);-}-.payg-bar__fill[data-state="DEGRADED"] {- background: var(--color-red);-}/* ── Plan card (free state) ─────────────────────────────────────────────── */.portal-billing__plan-card {diff --git a/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsx b/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsxindex e5da2c60d4..81b869d967 100644--- a/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsx+++ b/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsx@@ -1,4 +1,5 @@import { useState } from "react";+import { MemoryRouter } from "react-router-dom";import { render, screen, fireEvent, waitFor } from "@testing-library/react";import { it, expect, vi } from "vitest";import { MantineProvider } from "@mantine/core";@@ -47,7 +48,9 @@ it("suspends procurement while connecting and returns to its next action on dism><LinkProvider initialState="unlinked"><UIProvider>- <Flow />+ <MemoryRouter>+ <Flow />+ </MemoryRouter></UIProvider></LinkProvider></QueryClientProvider>diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsxindex 477c248adf..d6bbe8beb1 100644--- a/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx+++ b/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx@@ -1,4 +1,6 @@import type { ReactNode } from "react";+import { useLocation } from "react-router-dom";+import { useFreeTierExhaustedPrompt } from "@app/portal/hooks/useFreeTierExhaustedPrompt";import { LinkProvider } from "@app/portal/contexts/LinkContext";import { TierProvider } from "@app/portal/contexts/TierContext";import { UIProvider } from "@app/portal/contexts/UIContext";@@ -8,6 +10,14 @@ import { ConnectCallbackHost } from "@app/portal/components/account-link/Connectimport { AccountConnectionRefresh } from "@app/portal/components/account-link/AccountConnectionNotice";import { LinkAccountModalHost } from "@app/portal/components/account-link/LinkAccountModal";+function SettingsLinkModalHost() {+ const { pathname } = useLocation();+ useFreeTierExhaustedPrompt(+ pathname === "/settings/billing" || pathname === "/settings/account-link",+ );+ return <LinkAccountModalHost />;+}+/** The instance link starts unknown; checkout and license are inherited from AppProviders. */export function PortalSettingsProviders({ children }: { children: ReactNode }) {return (@@ -18,7 +28,7 @@ export function PortalSettingsProviders({ children }: { children: ReactNode }) {<AccountLinkProvider><AccountConnectionRefresh />{children}- <LinkAccountModalHost />+ <SettingsLinkModalHost /><ConnectCallbackHost /></AccountLinkProvider></AccountLinkSessionBoundary>diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsxindex 0367e8ff5e..be0d5c124d 100644--- a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx@@ -1,8 +1,14 @@import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";-import { PortalSettingsSectionHost } from "@app/portal/components/settings/PortalSettingsSectionHost";-import { useLinkOptional } from "@app/portal/contexts/LinkContext";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { PortalSettingsSectionHost } from "@portal/components/settings/PortalSettingsSectionHost";+import { useLinkOptional } from "@portal/contexts/LinkContext";+import {+ clearAccountLinkBlock,+ reportFreeTierExhausted,+} from "@app/services/accountLinkBlock";+import { useUI } from "@app/portal/contexts/UIContext";vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({useAccountLinkOwner: () => true,@@ -14,7 +20,14 @@ vi.mock("@app/portal/auth/saasSupabase", () => ({isSaasSupabaseConfigured: true,}));vi.mock("@app/portal/components/account-link/LinkAccountModal", () => ({- LinkAccountModalHost: () => null,+ LinkAccountModalHost: () => {+ const { linkModalOpen, linkModalMode, closeLinkModal } = useUI();+ return linkModalOpen ? (+ <div role="dialog" aria-label={linkModalMode}>+ <button onClick={closeLinkModal}>Not now</button>+ </div>+ ) : null;+ },}));vi.mock(@@ -40,8 +53,22 @@ function LinkState() {);}+function renderHost(path = "/settings/billing") {+ return render(+ <MemoryRouter initialEntries={[path]}>+ <PortalSettingsSectionHost>+ <LinkState />+ </PortalSettingsSectionHost>+ </MemoryRouter>,+ );+}+describe("settings link status", () => {- beforeEach(() => fetchStatus.mockReset());+ beforeEach(() => {+ fetchStatus.mockReset();+ sessionStorage.clear();+ clearAccountLinkBlock();+ });it("does not claim an unlinked server while its status is still loading", async () => {let resolve!: (value: { linked: boolean }) => void;@@ -50,11 +77,7 @@ describe("settings link status", () => {resolve = done;}),);- render(- <PortalSettingsSectionHost>- <LinkState />- </PortalSettingsSectionHost>,- );+ renderHost();expect(screen.getByText("checking")).toBeInTheDocument();resolve({ linked: true });expect(await screen.findByText("linked")).toBeInTheDocument();@@ -62,11 +85,47 @@ describe("settings link status", () => {it("uses a confirmed unlinked status for local billing", async () => {fetchStatus.mockResolvedValue({ linked: false });- render(- <PortalSettingsSectionHost>- <LinkState />- </PortalSettingsSectionHost>,- );+ renderHost();expect(await screen.findByText("unlinked")).toBeInTheDocument();});++ it.each(["/settings/billing", "/settings/account-link"])(+ "shows a foreground exhaustion prompt only once at %s",+ async (path) => {+ fetchStatus.mockResolvedValue({ linked: false });+ renderHost(path);+ await screen.findByText("unlinked");++ act(() => reportFreeTierExhausted());+ expect(+ screen.getByRole("dialog", { name: "exhausted" }),+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ act(() => reportFreeTierExhausted());+ expect(screen.queryByRole("dialog")).toBeNull();+ },+ );++ it("leaves foreground prompts to the editor on unrelated routes", async () => {+ fetchStatus.mockResolvedValue({ linked: false });+ renderHost("/editor");+ await screen.findByText("unlinked");++ act(() => reportFreeTierExhausted());+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("opens a billing modal once for background policy exhaustion", async () => {+ fetchStatus.mockResolvedValue({ linked: false });+ renderHost();+ await screen.findByText("unlinked");++ act(() => reportFreeTierExhausted());+ expect(+ screen.getByRole("dialog", { name: "exhausted" }),+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ act(() => reportFreeTierExhausted());+ expect(screen.queryByRole("dialog")).toBeNull();+ });});diff --git a/frontend/editor/src/portal/components/shared/FlowModal.tsx b/frontend/editor/src/portal/components/shared/FlowModal.tsxindex b240980b7f..a9aaf86a72 100644--- a/frontend/editor/src/portal/components/shared/FlowModal.tsx+++ b/frontend/editor/src/portal/components/shared/FlowModal.tsx@@ -1,52 +1 @@-import type { ReactNode } from "react";-import { Modal } from "@app/ui";-import "@portal/components/shared/FlowModal.css";--/**- * The one dialog shell for the portal's flows — procurement's takeover, the trial/licence/schedule- * dialogs, the legal reader.- *- * A thin wrapper over the shared {@link Modal}, which already owns the portal, focus trap, scroll- * lock, Escape and backdrop dismissal, and the close button. This used to reimplement all of it,- * which is precisely how the procurement dialogs drifted from the billing ones that were already on- * the shared Modal. What is left here is only what the flows genuinely add: a stacked body, a- * space-between footer for Back/Continue, and the takeover width.- *- * `header` is the shared Modal's title slot, so a flow can seat its own stepped header (see- * StepModalHeader) in the band. Omit it and the band goes entirely, close included — the convention- * the prepay checkout already follows for a step that draws its own heading and close. Escape and- * the backdrop still dismiss, so such a dialog is never inescapable.- */-export function FlowModal({- open,- onClose,- label,- header,- footer,- size = "md",- children,-}: {- open: boolean;- onClose: () => void;- /** Accessible name, used when `header` supplies no visible heading of its own. */- label: string;- header?: ReactNode;- footer?: ReactNode;- /** `md` for the task dialogs, `lg` for the procurement takeover and Calendly. */- size?: "md" | "lg";- children: ReactNode;-}) {- return (- <Modal- open={open}- onClose={onClose}- ariaLabel={label}- width={size}- className={`portal-flowmodal portal-flowmodal--${size}`}- title={header}- footer={footer}- >- {children}- </Modal>- );-}+export { FlowModal } from "@app/components/shared/FlowModal";diff --git a/frontend/editor/src/portal/components/shared/StepModalHeader.tsx b/frontend/editor/src/portal/components/shared/StepModalHeader.tsxindex b1e83fe23a..3f1ebcb0d0 100644--- a/frontend/editor/src/portal/components/shared/StepModalHeader.tsx+++ b/frontend/editor/src/portal/components/shared/StepModalHeader.tsx@@ -1,6 +1 @@-/**- * Moved to {@code @app/components/shared/StepModalHeader} when the editor's checkout flow needed- * the same stepped-modal chrome the portal flows wear. Re-exported here because eight portal and- * SaaS flows import this path and the move is not worth churning them for.- */export { StepModalHeader } from "@app/components/shared/StepModalHeader";diff --git a/frontend/editor/src/portal/contexts/UIContext.test.tsx b/frontend/editor/src/portal/contexts/UIContext.test.tsxindex b832a0ec79..829b573e94 100644--- a/frontend/editor/src/portal/contexts/UIContext.test.tsx+++ b/frontend/editor/src/portal/contexts/UIContext.test.tsx@@ -33,6 +33,16 @@ function probe() {}describe("UIContext — the trial-setup signal reaches consumers", () => {+ it("opens banner prompts without a previous pipeline failure context", () => {+ const p = probe();+ const cause = { pipelineId: "rotate", trigger: "upload" as const };+ act(() => p.api.openLinkModal("exhausted", cause));+ expect(p.api.linkModalFailureContext).toEqual(cause);+ act(() => p.api.closeLinkModal());+ act(() => p.api.openLinkModal("exhausted"));+ expect(p.api.linkModalOpen).toBe(true);+ expect(p.api.linkModalFailureContext).toBeUndefined();+ });it("re-renders consumers when the request is raised and cleared", () => {const p = probe();expect(p.api.trialSetupRequested).toBe(false);diff --git a/frontend/editor/src/portal/contexts/UIContext.tsx b/frontend/editor/src/portal/contexts/UIContext.tsxindex ded6de8df2..5d936594d2 100644--- a/frontend/editor/src/portal/contexts/UIContext.tsx+++ b/frontend/editor/src/portal/contexts/UIContext.tsx@@ -8,6 +8,7 @@ import {} from "react";import { navigateToSettings } from "@app/utils/settingsNavigation";import type { NavKey } from "@app/components/shared/config/types";+import type { AccountLinkBlockContext } from "@app/services/accountLinkBlock";import type { ConnectOutcome } from "@app/portal/components/account-link/ConnectCallbackView";import { clearPendingConnect } from "@app/portal/auth/pendingConnect";@@ -42,7 +43,11 @@ interface UIContextValue {/** The account-link login modal. A single top-level instance. */linkModalOpen: boolean;linkModalMode: LinkModalMode;- openLinkModal: (mode?: LinkModalMode) => void;+ linkModalFailureContext?: AccountLinkBlockContext;+ openLinkModal: (+ mode?: LinkModalMode,+ failureContext?: AccountLinkBlockContext,+ ) => void;closeLinkModal: () => void;/*** A one-shot signal like {@link UIContextValue.trialSetupRequested}: the callback route and the@@ -87,6 +92,8 @@ export function UIProvider({ children }: { children: ReactNode }) {const [assistantOpen, setAssistantOpen] = useState(false);const linkModalActive = useRef(false);const [linkModalOpen, setLinkModalOpen] = useState(false);+ const [linkModalFailureContext, setLinkModalFailureContext] =+ useState<AccountLinkBlockContext>();const [trialSetupRequested, setTrialSetupRequested] = useState(false);const [linkModalMode, setLinkModalMode] = useState<LinkModalMode>("link");const [connectOutcome, setConnectOutcome] = useState<ConnectOutcome | null>(@@ -121,10 +128,15 @@ export function UIProvider({ children }: { children: ReactNode }) {linkModalOpen,linkModalMode,- openLinkModal: (mode: LinkModalMode = "link") => {+ linkModalFailureContext,+ openLinkModal: (+ mode: LinkModalMode = "link",+ failureContext?: AccountLinkBlockContext,+ ) => {// Background failures must not replace a handoff or callback already in progress.if (linkModalActive.current) return;linkModalActive.current = true;+ setLinkModalFailureContext(failureContext);setMobileNavOpen(false);setLinkModalMode(mode);setConnectOutcome(null);@@ -146,6 +158,7 @@ export function UIProvider({ children }: { children: ReactNode }) {},clearConnectOutcome: () => setConnectOutcome(null),closeLinkModal: () => {+ setLinkModalFailureContext(undefined);linkModalActive.current = false;connectOutcome?.cancel?.();clearPendingConnect();@@ -161,6 +174,7 @@ export function UIProvider({ children }: { children: ReactNode }) {assistantOpen,linkModalOpen,linkModalMode,+ linkModalFailureContext,trialSetupRequested,connectOutcome,],diff --git a/frontend/editor/src/portal/hooks/useAccountLink.ts b/frontend/editor/src/portal/hooks/useAccountLink.tsindex a68b931e66..10726096d7 100644--- a/frontend/editor/src/portal/hooks/useAccountLink.ts+++ b/frontend/editor/src/portal/hooks/useAccountLink.ts@@ -1,4 +1,5 @@import { useCallback, useEffect, useState, useRef } from "react";+import { clearAccountLinkBlock } from "@app/services/accountLinkBlock";import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";import { errorMessage } from "@app/portal/api/http";import { isSaasSupabaseConfigured } from "@app/portal/auth/saasSupabase";@@ -53,6 +54,7 @@ export function useAccountLink(): UseAccountLink {const s = await fetchStatus(force);if (request !== statusRequest.current) return;setStatus(s);+ if (s.linked) clearAccountLinkBlock();// A linked instance is at least linked-free; subscription comes from the wallet.if (s.linked && previousLinked.current !== true)applyLinkFacts(true, false);diff --git a/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsx b/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsxnew file mode 100644index 0000000000..788de03d35--- /dev/null+++ b/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsx@@ -0,0 +1,107 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { TestQueryProvider } from "@portal/test/TestQueryProvider";+import { useFreeTierBalance } from "@portal/hooks/useFreeTierBalance";+import {+ clearAccountLinkBlock,+ reportFreeTierExhausted,+ useAccountLinkBlock,+} from "@app/services/accountLinkBlock";++const mocks = vi.hoisted(() => ({+ isAdmin: true,+ gated: true,+ fetchFreeTier: vi.fn(),+}));+vi.mock("@app/auth", () => ({ useAuth: () => ({ isAdmin: mocks.isAdmin }) }));+vi.mock("@portal/hooks/useConnectGate", () => ({+ useConnectGate: () => ({ gated: mocks.gated, loading: false }),+}));+vi.mock("@portal/api/link", () => ({ fetchFreeTier: mocks.fetchFreeTier }));+const balance = (remainingUnits: number) => ({+ grantUnits: 500,+ remainingUnits,+ usedUnits: 500 - remainingUnits,+ periodStart: "2026-09-01T00:00:00",+ periodEnd: "2026-10-01T00:00:00",+});++describe("local allowance refresh", () => {+ beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ mocks.isAdmin = true;+ mocks.gated = true;+ mocks.fetchFreeTier.mockReset().mockResolvedValue(balance(500));+ });++ it("does not request server-wide figures for members or linked accounts", () => {+ mocks.isAdmin = false;+ const probe = renderHook(() => useFreeTierBalance(), {+ wrapper: TestQueryProvider,+ });+ expect(mocks.fetchFreeTier).not.toHaveBeenCalled();+ mocks.isAdmin = true;+ mocks.gated = false;+ probe.rerender();+ expect(mocks.fetchFreeTier).not.toHaveBeenCalled();+ expect(probe.result.current.data).toBeUndefined();+ });++ it("refreshes on exhaustion and clears the notice when the allowance renews", async () => {+ const probe = renderHook(+ () => ({ ledger: useFreeTierBalance(), block: useAccountLinkBlock() }),+ { wrapper: TestQueryProvider },+ );+ await waitFor(() =>+ expect(probe.result.current.ledger.data?.remainingUnits).toBe(500),+ );+ mocks.fetchFreeTier.mockResolvedValue(balance(0));+ act(() => reportFreeTierExhausted());+ await waitFor(() =>+ expect(probe.result.current.ledger.data?.remainingUnits).toBe(0),+ );+ expect(probe.result.current.block.exhausted).toBe(true);+ expect(probe.result.current.block.promptPending).toBe(true);+ mocks.fetchFreeTier.mockResolvedValue(balance(500));+ await act(async () => {+ await probe.result.current.ledger.refetch();+ });+ await waitFor(() =>+ expect(probe.result.current.block.exhausted).toBe(false),+ );+ });++ it("keeps an authoritative block when refreshing an older positive balance fails", async () => {+ const probe = renderHook(+ () => ({ ledger: useFreeTierBalance(), block: useAccountLinkBlock() }),+ { wrapper: TestQueryProvider },+ );+ await waitFor(() =>+ expect(probe.result.current.ledger.data?.remainingUnits).toBe(500),+ );+ mocks.fetchFreeTier.mockRejectedValue(new Error("offline"));+ act(() => reportFreeTierExhausted());+ await waitFor(() => expect(probe.result.current.ledger.isError).toBe(true));+ expect(probe.result.current.block.exhausted).toBe(true);+ expect(probe.result.current.ledger.data).toEqual(balance(500));+ });++ it("retains an exhausted balance and reset date after a failed refetch", async () => {+ mocks.fetchFreeTier.mockResolvedValue(balance(0));+ const probe = renderHook(() => useFreeTierBalance(), {+ wrapper: TestQueryProvider,+ });+ await waitFor(() => expect(probe.result.current.data).toEqual(balance(0)));+ mocks.fetchFreeTier.mockRejectedValue(new Error("offline"));+ await act(async () => {+ await probe.result.current.refetch();+ });+ await waitFor(() => expect(probe.result.current.isError).toBe(true));+ expect(probe.result.current.data).toEqual(balance(0));++ mocks.isAdmin = false;+ probe.rerender();+ expect(probe.result.current.data).toBeUndefined();+ });+});diff --git a/frontend/editor/src/portal/hooks/useFreeTierBalance.ts b/frontend/editor/src/portal/hooks/useFreeTierBalance.tsnew file mode 100644index 0000000000..ace9a6ac19--- /dev/null+++ b/frontend/editor/src/portal/hooks/useFreeTierBalance.ts@@ -0,0 +1,57 @@+import { useEffect } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useAuth } from "@app/auth";+import { fetchFreeTier } from "@portal/api/link";+import { useConnectGate } from "@portal/hooks/useConnectGate";+import { qk } from "@portal/queries/keys";+import {+ FREE_TIER_EXHAUSTED_EVENT,+ clearAccountLinkBlock,+} from "@app/services/accountLinkBlock";++/** Admin-only local ledger; refreshes after a block and at rollover without reading a cloud wallet. */+export function useFreeTierBalance() {+ const { isAdmin } = useAuth();+ const { gated, loading } = useConnectGate();+ const client = useQueryClient();+ const enabled = isAdmin && gated && !loading;+ const query = useQuery({+ queryKey: qk.freeTier(),+ queryFn: fetchFreeTier,+ enabled,+ refetchInterval: 60_000,+ retry: false,+ });++ useEffect(() => {+ if (!enabled) return;+ const refresh = () => {+ void client.invalidateQueries({ queryKey: qk.freeTier() });+ };+ window.addEventListener(FREE_TIER_EXHAUSTED_EVENT, refresh);+ return () => window.removeEventListener(FREE_TIER_EXHAUSTED_EVENT, refresh);+ }, [client, enabled]);++ useEffect(() => {+ if (+ enabled &&+ query.isSuccess &&+ query.data &&+ !query.isFetching &&+ query.data.remainingUnits > 0+ ) {+ clearAccountLinkBlock();+ }+ }, [+ enabled,+ query.data,+ query.dataUpdatedAt,+ query.isFetching,+ query.isSuccess,+ ]);++ return {+ ...query,+ data: enabled ? query.data : undefined,+ };+}diff --git a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsxindex 692e2da091..5b154dff3b 100644--- a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx+++ b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { render } from "@testing-library/react";+import { act, render } from "@testing-library/react";/*** The cadence decision, reversed from what it was: being unlinked is not a reason to ask anything.@@ -20,12 +20,16 @@ vi.mock("@app/portal/contexts/UIContext", () => ({useUI: () => ({ openLinkModal }),}));+import {+ clearAccountLinkBlock,+ reportFreeTierExhausted,+} from "@app/services/accountLinkBlock";import { HttpError } from "@app/portal/api/http";import { reportAccountLinkBlock } from "@app/portal/services/accountLinkBlock";import { useFreeTierExhaustedPrompt } from "@app/portal/hooks/useFreeTierExhaustedPrompt";-function Probe() {- useFreeTierExhaustedPrompt();+function Probe({ enabled = true }: { enabled?: boolean }) {+ useFreeTierExhaustedPrompt(enabled);return null;}@@ -37,6 +41,8 @@ const blocked = (reason: string) =>describe("the account-link prompt", () => {beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();openLinkModal.mockReset();flags.isAdmin = true;flags.orgOwner = true;@@ -48,10 +54,32 @@ describe("the account-link prompt", () => {expect(openLinkModal).not.toHaveBeenCalled();});+ it("leaves pending failures for the active dialog host", () => {+ const view = render(<Probe enabled={false} />);+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });+ expect(openLinkModal).not.toHaveBeenCalled();+ view.rerender(<Probe />);+ expect(openLinkModal).toHaveBeenCalledExactlyOnceWith(+ "exhausted",+ undefined,+ );+ });+it("opens on the allowance pitch when the grant is reported spent", () => {render(<Probe />);- reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));- expect(openLinkModal).toHaveBeenCalledWith("exhausted");+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });+ expect(openLinkModal).toHaveBeenCalledWith("exhausted", undefined);+ });++ it("passes the triggering pipeline to the automatic modal", () => {+ render(<Probe />);+ const cause = { pipelineId: "rotate", trigger: "upload" as const };+ act(() => reportFreeTierExhausted(cause));+ expect(openLinkModal).toHaveBeenCalledWith("exhausted", cause);});it("does not reopen for later responses from the same exhausted batch", () => {@@ -70,7 +98,7 @@ describe("the account-link prompt", () => {expect(openLinkModal).not.toHaveBeenCalled();});- it.each(["non-owner", "already linked"])(+ it.each(["already linked"])("does not offer initial linking to %s",(state) => {flags.isAdmin = state !== "non-owner";@@ -90,17 +118,49 @@ describe("the account-link prompt", () => {it("stops listening once unmounted", () => {render(<Probe />).unmount();- reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });expect(openLinkModal).not.toHaveBeenCalled();});++ it("coalesces concurrent failures and stays quiet after dismissal and remount", () => {+ const first = render(<Probe />);+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });+ first.unmount();+ render(<Probe />);+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });+ expect(openLinkModal).toHaveBeenCalledTimes(1);+ });++ it("keeps the session suppression after credits recover", () => {+ render(<Probe />);+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });+ act(() => {+ clearAccountLinkBlock();+ });+ act(() => {+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ });+ expect(openLinkModal).toHaveBeenCalledTimes(1);+ });});-it("does not prompt an ordinary admin when the local allowance is exhausted", () => {+it("routes an ordinary admin to the role-aware exhaustion dialog", () => {+ sessionStorage.clear();+ clearAccountLinkBlock();flags.isAdmin = true;flags.orgOwner = false;flags.isLinked = false;openLinkModal.mockReset();render(<Probe />);- window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted"));- expect(openLinkModal).not.toHaveBeenCalled();+ act(() => reportFreeTierExhausted());+ expect(openLinkModal).toHaveBeenCalledWith("exhausted", undefined);});diff --git a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.tsindex f4cd25863e..98201cef49 100644--- a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts+++ b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts@@ -1,30 +1,20 @@-import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";-import { useLink } from "@app/portal/contexts/LinkContext";-import { useEffect, useRef } from "react";+import { useEffect } from "react";import { useUI } from "@app/portal/contexts/UIContext";-import { FREE_TIER_EXHAUSTED_EVENT } from "@app/portal/services/accountLinkBlock";+import { useLink } from "@app/portal/contexts/LinkContext";+import {+ acknowledgeAccountLinkPrompt,+ useAccountLinkBlock,+} from "@app/services/accountLinkBlock";-/**- * Opens the account-link dialog on the "allowance spent" pitch when the instance reports a spent- * free grant. Mount once, alongside the dialog it opens.- *- * <p>The bridge is a window event rather than a call, because the reporter is the API client and has- * no React context to reach: same shape as the cloud build's usage-limit modals.- */-export function useFreeTierExhaustedPrompt(): void {- const prompted = useRef(false);- const isOwner = useAccountLinkOwner();+/** Mount alongside the single link dialog; repeat failures leave the persistent rail in place. */+export function useFreeTierExhaustedPrompt(enabled = true): void {const { isLinked } = useLink();- const { openLinkModal } = useUI();+ const { openLinkModal, linkModalOpen } = useUI();+ const { promptPending, context } = useAccountLinkBlock();useEffect(() => {- const onExhausted = () => {- if (!isOwner || isLinked || prompted.current) return;- prompted.current = true;- openLinkModal("exhausted");- };- window.addEventListener(FREE_TIER_EXHAUSTED_EVENT, onExhausted);- return () =>- window.removeEventListener(FREE_TIER_EXHAUSTED_EVENT, onExhausted);- }, [isOwner, isLinked, openLinkModal]);+ if (!enabled || isLinked || !promptPending) return;+ acknowledgeAccountLinkPrompt();+ if (!linkModalOpen) openLinkModal("exhausted", context);+ }, [enabled, isLinked, promptPending, context, linkModalOpen, openLinkModal]);}diff --git a/frontend/editor/src/portal/queries/keys.ts b/frontend/editor/src/portal/queries/keys.tsindex 66f92ebf31..9448aa7dd4 100644--- a/frontend/editor/src/portal/queries/keys.ts+++ b/frontend/editor/src/portal/queries/keys.ts@@ -1,5 +1,6 @@import type { Tier } from "@portal/contexts/TierContext";import type { FileRunEventScope } from "@portal/api/fileRunEvents";+import { pipelineQueryKeys } from "@app/policies/queryKeys";/*** The portal's TanStack Query keys, in one place. Convention:@@ -11,13 +12,13 @@ import type { FileRunEventScope } from "@portal/api/fileRunEvents";*/export const qk = {// Tier-independent- policiesList: () => ["portal", "policies", "list"] as const,+ ...pipelineQueryKeys,policyRuns: () => ["portal", "policies", "runs"] as const,sources: () => ["portal", "sources"] as const,- pipelines: () => ["portal", "pipelines"] as const,policyPermissions: () => ["portal", "policies", "permissions"] as const,fleetStats: () => ["portal", "fleetStats"] as const,appConfig: () => ["portal", "appConfig"] as const,+ freeTier: () => ["portal", "freeTier"] as const,/** Storage-encryption migration progress, polled while a run is active. */encryptionMigration: () => ["portal", "encryptionMigration"] as const,/** Usage accrued on this instance since the last sync; self-hosted only. */diff --git a/frontend/editor/src/portal/services/accountLinkBlock.ts b/frontend/editor/src/portal/services/accountLinkBlock.tsindex 2c8bfc9039..dffa9e41fc 100644--- a/frontend/editor/src/portal/services/accountLinkBlock.ts+++ b/frontend/editor/src/portal/services/accountLinkBlock.ts@@ -1,64 +1,6 @@-/**- * The `402 ACCOUNT_LINK_REQUIRED` sentinel, turned into a prompt.- *- * <p>Reactive, not predictive: the free tier needs no account, so the UI cannot know whether an- * action is affordable, and the balance endpoint is admin-only anyway. It runs the action and lets- * the answer raise the dialog.- *- * <p>Only {@code FREE_TIER_EXHAUSTED} is acted on. The others mean a linked team's cloud wallet is- * the problem, where offering to link would be nonsense, so they fall through to the caller.- */--/** Bridge to the always-mounted host in PortalProviders. */-export const FREE_TIER_EXHAUSTED_EVENT = "stirling:portal-free-tier-exhausted";--/** Mirrors the backend {@code GateDecision.Reason} blocking arm. */-export type AccountLinkBlockReason =- | "FREE_TIER_EXHAUSTED"- | "OVER_LIMIT"- | "REVOKED"- | "GRACE_EXPIRED";--const BLOCK_REASONS: readonly string[] = [- "FREE_TIER_EXHAUSTED",- "OVER_LIMIT",- "REVOKED",- "GRACE_EXPIRED",-];--/**- * The gate's block reason, or null when this is not the account-link sentinel.- *- * <p>Strict on the status and the sentinel both, so an incidental 402 is not hijacked. Reads- * {@link HttpError} structurally to stay off the import cycle with the client that throws it.- */-export function classifyAccountLinkBlock(- error: unknown,-): AccountLinkBlockReason | null {- if (!error || typeof error !== "object") return null;- if ((error as { status?: unknown }).status !== 402) return null;- const body = (error as { body?: unknown }).body;- if (!body || typeof body !== "object") return null;- const sentinel = (body as { error?: unknown }).error;- if (sentinel !== "ACCOUNT_LINK_REQUIRED") return null;- const reason = (body as { reason?: unknown }).reason;- if (typeof reason !== "string" || !BLOCK_REASONS.includes(reason)) {- return null;- }- return reason as AccountLinkBlockReason;-}--/**- * Raises the prompt if {@code error} is a spent free grant, returning whether it did so a caller- * can leave its own error surface alone. Safe on any error, any number of times.- */-export function reportAccountLinkBlock(error: unknown): boolean {- if (classifyAccountLinkBlock(error) !== "FREE_TIER_EXHAUSTED") return false;- try {- window.dispatchEvent(new Event(FREE_TIER_EXHAUSTED_EVENT));- } catch {- // Non-browser env (tests / SSR) — the throw must not replace the caller's own error.- return false;- }- return true;-}+export {+ FREE_TIER_EXHAUSTED_EVENT,+ classifyAccountLinkBlock,+ reportAccountLinkBlock,+ type AccountLinkBlockReason,+} from "@app/services/accountLinkBlock";diff --git a/frontend/editor/src/proprietary/billing/MeterBar.css b/frontend/editor/src/proprietary/billing/MeterBar.cssnew file mode 100644index 0000000000..7a65498dcd--- /dev/null+++ b/frontend/editor/src/proprietary/billing/MeterBar.css@@ -0,0 +1,62 @@+.paygf-meter {+ margin-top: 0.6rem;+}+.paygf-meter__top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+}+.paygf-meter__figure {+ display: flex;+ align-items: baseline;+ gap: 7px;+}+.paygf-meter__num {+ font-size: 1.7rem;+ font-weight: 750;+ line-height: 1;+ letter-spacing: -0.02em;+ color: var(--c-text);+ font-variant-numeric: tabular-nums;+}+.paygf-meter__cap {+ font-size: 0.85rem;+ color: var(--c-text-subtle);+ font-variant-numeric: tabular-nums;+}+.paygf-meter .payg-bar {+ margin-top: 11px;+}+.paygf-meter__meta {+ margin-top: 10px;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px 10px;+ font-size: 0.78rem;+ color: var(--c-text-muted);+}++.payg-bar {+ margin-top: 18px;+ height: 10px;+ border-radius: 999px;+ background: var(--color-bg-subtle, var(--c-surface-sunken));+ overflow: hidden;+ position: relative;+}+.payg-bar__fill {+ height: 100%;+ border-radius: 999px;+ transition: width 0.5s cubic-bezier(0.16, 1, 0.3, 1);+}+.payg-bar__fill[data-state="FULL"] {+ background: var(--c-primary);+}+.payg-bar__fill[data-state="WARNED"] {+ background: var(--color-amber);+}+.payg-bar__fill[data-state="DEGRADED"] {+ background: var(--color-red);+}diff --git a/frontend/editor/src/proprietary/billing/MeterBar.tsx b/frontend/editor/src/proprietary/billing/MeterBar.tsxindex 5049b91294..aa05cec85c 100644--- a/frontend/editor/src/proprietary/billing/MeterBar.tsx+++ b/frontend/editor/src/proprietary/billing/MeterBar.tsx@@ -1,3 +1,4 @@+import "@app/billing/MeterBar.css";import type { ReactNode } from "react";import type { MeterState } from "@app/billing/format";import { StatusBadge, type StatusTone } from "@app/ui/StatusBadge";diff --git a/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx b/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsxnew file mode 100644index 0000000000..5222f7ee36--- /dev/null+++ b/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx@@ -0,0 +1,192 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter, useLocation } from "react-router-dom";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MantineProvider } from "@mantine/core";+import { AccountLinkNotice } from "@app/components/AccountLinkNotice";+import {+ clearAccountLinkBlock,+ reportFreeTierExhausted,+} from "@app/services/accountLinkBlock";++const { alert, begin, auth, get } = vi.hoisted(() => ({+ alert: vi.fn(),+ begin: vi.fn(),+ get: vi.fn(),+ auth: { isAdmin: true, loading: false },+}));+vi.mock("@app/auth", () => ({+ useAuth: () => ({+ ...auth,+ user: { orgOwner: auth.isAdmin },+ loading: false,+ }),+}));+vi.mock("@app/components/toast", () => ({ alert }));+vi.mock("@app/services/apiClient", () => ({ default: { get } }));+vi.mock("@portal/hooks/useConnectHandoff", () => ({+ useConnectHandoff: () => ({ begin, busy: false, error: null }),+}));+vi.mock("@portal/auth/saasSupabase", () => ({+ isSaasSupabaseConfigured: true,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string, values?: Record<string, string>) =>+ (fallback ?? key).replace(+ /{{(\w+)}}/g,+ (match, name: string) => values?.[name] ?? match,+ ),+ }),+}));+vi.mock("@app/ui", async () => ({+ ...(await import("@app/ui/Button")),+ ...(await import("@app/ui/Modal")),+ ...(await import("@app/ui/Banner")),+}));++function LocationProbe() {+ return <output>{useLocation().pathname}</output>;+}+function mount(path: string) {+ return render(+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <MantineProvider>+ <MemoryRouter initialEntries={[path]}>+ <AccountLinkNotice />+ <LocationProbe />+ </MemoryRouter>+ </MantineProvider>+ </QueryClientProvider>,+ );+}++describe("editor shared account-link modal", () => {+ beforeEach(() => {+ sessionStorage.clear();+ clearAccountLinkBlock();+ vi.clearAllMocks();+ auth.isAdmin = true;+ get.mockResolvedValue({+ data: {+ grantUnits: 500,+ remainingUnits: 0,+ periodEnd: "2026-10-01T00:00:00",+ },+ });+ });+ it.each(["/processor", "/settings/billing", "/settings/account-link"])(+ "leaves %s to its existing link dialog",+ (path) => {+ mount(path);+ act(() => reportFreeTierExhausted());+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(alert).not.toHaveBeenCalled();+ },+ );+ it("opens the administrator modal in the editor and invokes the existing handoff", async () => {+ mount("/editor");+ await act(async () => reportFreeTierExhausted());+ expect(+ screen.getByRole("dialog", { name: "Keep your workflows running" }),+ ).toBeTruthy();+ expect(+ screen.getByText("Add more users with a paid Team plan"),+ ).toBeTruthy();+ expect(screen.queryByText("Active pipelines")).toBeNull();+ expect(get.mock.calls.every(([url]) => !url.includes("/policies"))).toBe(+ true,+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Link account for more credits" }),+ );+ expect(begin).toHaveBeenCalledOnce();+ expect(screen.getByRole("status").textContent).toBe("/editor");+ });+ it("opens once for automatic policy failures", async () => {+ mount("/editor");+ await act(async () => {+ reportFreeTierExhausted();+ reportFreeTierExhausted();+ });+ expect(screen.getAllByRole("dialog")).toHaveLength(1);+ expect(alert).not.toHaveBeenCalled();+ });+ it.each(["upload", "export", "manual"] as const)(+ "explains the %s failure and opens that pipeline's settings",+ async (trigger) => {+ mount("/editor");+ await act(async () =>+ reportFreeTierExhausted({+ pipelineId: "rotate-id",+ pipelineName: "Quarterly rotation",++ trigger,+ }),+ );+ expect(screen.queryByText(/report\.pdf/)).toBeNull();+ fireEvent.click(screen.getByText("Active pipelines"));+ await screen.findByRole("button", { name: "Open pipeline settings" });+ fireEvent.click(+ screen.getByRole("button", { name: "Open pipeline settings" }),+ );+ expect(screen.getByRole("status").textContent).toBe(+ "/processor/pipelines/rotate-id",+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ },+ );+ it("gives members the failed pipeline details without an administrator settings action", async () => {+ auth.isAdmin = false;+ mount("/editor");+ await act(async () =>+ reportFreeTierExhausted({+ pipelineId: "rotate-id",+ pipelineName: "Quarterly rotation",++ trigger: "upload",+ }),+ );+ expect(+ screen.getByText(/Pipeline “Quarterly rotation” stopped after upload/),+ ).toBeTruthy();+ expect(+ screen.getByRole("dialog", { name: "Ask your server administrator" }),+ ).toBeTruthy();+ expect(+ screen.queryByRole("button", { name: "Open pipeline settings" }),+ ).toBeNull();+ });+ it("does not replace a dismissed modal with a toast or reopen it on subsequent failures", async () => {+ const view = mount("/editor");+ await act(async () => reportFreeTierExhausted());+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ await act(async () => {+ reportFreeTierExhausted();+ reportFreeTierExhausted();+ });+ view.unmount();+ mount("/editor");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(alert).not.toHaveBeenCalled();+ });+ it("uses the same member modal and never reads the administrator balance", async () => {+ auth.isAdmin = false;+ mount("/editor");+ await act(async () => reportFreeTierExhausted());+ expect(+ screen.getByRole("dialog", { name: "Ask your server administrator" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Copy message for administrator" }),+ ).toBeTruthy();+ expect(+ screen.queryByRole("button", { name: "Link account for more credits" }),+ ).toBeNull();+ expect(get).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx b/frontend/editor/src/proprietary/components/AccountLinkNotice.tsxnew file mode 100644index 0000000000..a4d0f018d4--- /dev/null+++ b/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx@@ -0,0 +1,95 @@+import { useEffect, useState } from "react";+import { useLocation } from "react-router-dom";+import { useQuery } from "@tanstack/react-query";+import { useAuth } from "@app/auth";+import apiClient from "@app/services/apiClient";+import { PORTAL_BASENAME } from "@app/routes/portalBasename";+import { EditorLinkModal } from "@app/components/account-link/EditorLinkModal";+import { FreeTierBalanceSummary } from "@app/components/account-link/FreeTierBalanceSummary";+import type { FreeTierBalance } from "@app/components/account-link/FreeTierBalanceSummary";++import {+ acknowledgeAccountLinkPrompt,+ clearAccountLinkBlock,+ useAccountLinkBlock,+} from "@app/services/accountLinkBlock";++interface Props {+ /** Hosts without a Processor route open the connected server's billing page externally. */+ onShowOptions?: () => void;+ onManagePipeline?: (pipelineId?: string) => void;+ /** Native hosts fetch the connected server's ledger through their own HTTP client. */+ balance?: FreeTierBalance;+}++/** File failures share one explanatory linking prompt per tab session. */+export function AccountLinkNotice({+ onShowOptions,+ onManagePipeline,+ balance,+}: Props = {}) {+ const { isAdmin, loading } = useAuth();+ const { pathname } = useLocation();+ const { exhausted, promptPending, context } = useAccountLinkBlock();+ const [open, setOpen] = useState(false);+ const hasLinkDialog =+ !onShowOptions &&+ (pathname === PORTAL_BASENAME ||+ pathname.startsWith(`${PORTAL_BASENAME}/`) ||+ pathname === "/settings/billing" ||+ pathname === "/settings/account-link");+ const readsBalance =+ !onShowOptions && !hasLinkDialog && isAdmin && !loading && exhausted;+ const ledger = useQuery({+ queryKey: ["accountLink", "editorFreeTier"],+ queryFn: async () =>+ (+ await apiClient.get<FreeTierBalance>("/api/v1/account-link/free-tier", {+ suppressErrorToast: true,+ skipAuthRedirect: true,+ })+ ).data,+ enabled: readsBalance,+ retry: false,+ refetchInterval: 60_000,+ });++ useEffect(() => {+ if (+ readsBalance &&+ ledger.isSuccess &&+ !ledger.isFetching &&+ ledger.data.remainingUnits > 0+ ) {+ clearAccountLinkBlock();+ }+ }, [readsBalance, ledger.isSuccess, ledger.isFetching, ledger.data]);++ useEffect(() => {+ if (!exhausted || hasLinkDialog) setOpen(false);+ }, [exhausted, hasLinkDialog]);++ useEffect(() => {+ if (hasLinkDialog || loading || !promptPending) return;+ acknowledgeAccountLinkPrompt();+ setOpen(true);+ }, [hasLinkDialog, loading, promptPending]);++ if (!open || !exhausted || hasLinkDialog) return null;+ return (+ <EditorLinkModal+ open+ failureContext={context}+ onClose={() => setOpen(false)}+ onStart={onShowOptions}+ onManagePipeline={onManagePipeline}+ summary={+ <FreeTierBalanceSummary+ balance={+ onShowOptions ? balance : ledger.isSuccess ? ledger.data : undefined+ }+ />+ }+ />+ );+}diff --git a/frontend/editor/src/proprietary/components/AppProviders.tsx b/frontend/editor/src/proprietary/components/AppProviders.tsxindex f937d3cfe4..7a19373412 100644--- a/frontend/editor/src/proprietary/components/AppProviders.tsx+++ b/frontend/editor/src/proprietary/components/AppProviders.tsx@@ -9,6 +9,7 @@ import { UpgradeBannerInitializer } from "@app/components/shared/UpgradeBannerInimport { ServerExperienceProvider } from "@app/contexts/ServerExperienceContext";import { UpdateSeatsProvider } from "@app/contexts/UpdateSeatsContext";import { ChatProvider } from "@app/components/chat/ChatContext";+import { AccountLinkNotice } from "@app/components/AccountLinkNotice";export function AppProviders({children,@@ -26,6 +27,7 @@ export function AppProviders({<ServerExperienceProvider><CheckoutProvider><UpgradeBannerInitializer />+ <AccountLinkNotice /><ChatProvider>{children}</ChatProvider></CheckoutProvider></ServerExperienceProvider>diff --git a/frontend/editor/src/proprietary/components/account-link/ConnectBenefitsSlide.tsx b/frontend/editor/src/proprietary/components/account-link/ConnectBenefitsSlide.tsxnew file mode 100644index 0000000000..5281bb47f9--- /dev/null+++ b/frontend/editor/src/proprietary/components/account-link/ConnectBenefitsSlide.tsx@@ -0,0 +1,64 @@+import { useTranslation } from "react-i18next";+import "@app/components/account-link/connect.css";++/** Linking benefits distinguish the free team allowance from optional paid capacity. */+export function ConnectBenefitsSlide() {+ const { t } = useTranslation();+ const benefits = [+ {+ key: "credits",+ label: t(+ "portal.accountLink.connect.benefits.creditsLabel",+ "Monthly credits",+ ),+ detail: t(+ "portal.accountLink.connect.benefits.creditsDetail",+ "Access your team’s free monthly allowance",+ ),+ },+ {+ key: "teams",+ label: t(+ "portal.accountLink.connect.benefits.teamsLabel",+ "Larger teams",+ ),+ detail: t(+ "portal.accountLink.connect.benefits.teamsDetail",+ "Add more users with a paid Team plan",+ ),+ },+ {+ key: "processing",+ label: t(+ "portal.accountLink.connect.benefits.processingLabel",+ "More processing",+ ),+ detail: t(+ "portal.accountLink.connect.benefits.processingDetail",+ "Buy more credits for API, AI and automation as you grow",+ ),+ },+ {+ key: "billing",+ label: t(+ "portal.accountLink.connect.benefits.billingLabel",+ "One account",+ ),+ detail: t(+ "portal.accountLink.connect.benefits.billingDetail",+ "Manage usage, billing and linked servers together",+ ),+ },+ ];++ return (+ <dl className="portal-connect__list">+ {benefits.map((benefit) => (+ <div className="portal-connect__row" key={benefit.key}>+ <dt className="portal-connect__row-label">{benefit.label}</dt>+ <dd className="portal-connect__row-detail">{benefit.detail}</dd>+ </div>+ ))}+ </dl>+ );+}diff --git a/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.test.tsx b/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.test.tsxnew file mode 100644index 0000000000..0c5596c15e--- /dev/null+++ b/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.test.tsx@@ -0,0 +1,149 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MantineProvider } from "@mantine/core";+import { CreditPromptPipelines } from "@app/components/account-link/CreditPromptPipelines";++const { fetchPipelines, setEnabled } = vi.hoisted(() => ({+ fetchPipelines: vi.fn(),+ setEnabled: vi.fn(),+}));+vi.mock("@app/services/creditPromptPipelines", () => ({+ fetchCreditPromptPipelines: fetchPipelines,+ setCreditPromptPipelineEnabled: setEnabled,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));+vi.mock("@app/ui", async () => ({+ ...(await import("@app/ui/Button")),+ ...(await import("@app/ui/ToggleSwitch")),+}));++const optional = {+ id: "rotate",+ name: "Rotate",+ enabled: true,+ required: false,+ trigger: "editor-upload",+ sources: [],+};+const required = {+ id: "redact",+ name: "Redact",+ enabled: true,+ required: true,+ trigger: "schedule",+ sources: [{ name: "Finance inbox" }],+ editor: { allowed: true, runOn: "export" },+};+function mount(onManagePipeline?: (id?: string) => void) {+ render(+ <MantineProvider>+ <QueryClientProvider client={new QueryClient()}>+ <CreditPromptPipelines+ affectedPipelineId="rotate"+ onManagePipeline={onManagePipeline}+ />+ </QueryClientProvider>+ </MantineProvider>,+ );+}+async function expand() {+ fireEvent.click(screen.getByText("Active pipelines"));+ await screen.findByRole("switch", { name: "Rotate" });+}++describe("active pipelines in the credit prompt", () => {+ beforeEach(() => {+ vi.resetAllMocks();+ fetchPipelines.mockResolvedValue({+ pipelines: [optional, required],+ canManage: true,+ });+ setEnabled.mockResolvedValue(undefined);+ });+ it("keeps controls secondary until expanded and identifies the source of the prompt", async () => {+ mount();+ expect(fetchPipelines).toHaveBeenCalledOnce();+ expect(screen.queryByRole("switch")).toBeNull();+ await expand();+ expect(screen.getByText("Editor · on upload")).toBeTruthy();+ expect(+ screen.getByText("Editor · before download, Finance inbox"),+ ).toBeTruthy();+ expect(screen.queryByRole("tooltip")).toBeNull();+ fireEvent.focus(+ screen.getByRole("button", { name: "Triggered this prompt" }),+ );+ expect(await screen.findByRole("tooltip")).toHaveTextContent(+ "Triggered this prompt",+ );+ expect(setEnabled).not.toHaveBeenCalled();+ });+ it("pauses an optional pipeline and keeps the row available to re-enable", async () => {+ mount();+ await expand();+ fireEvent.click(screen.getByRole("switch", { name: "Rotate" }));+ await screen.findByText("Paused");+ expect(+ screen.getByRole("button", { name: /^Active pipelines\s*1$/ }),+ ).toBeTruthy();+ expect(setEnabled).toHaveBeenCalledWith("rotate", false);+ expect(screen.getByRole("switch", { name: "Rotate" })).not.toBeChecked();+ fireEvent.click(screen.getByRole("switch", { name: "Rotate" }));+ await waitFor(() =>+ expect(screen.getByRole("switch", { name: "Rotate" })).toBeChecked(),+ );+ expect(setEnabled).toHaveBeenLastCalledWith("rotate", true);+ });+ it("protects required policies", async () => {+ mount();+ await expand();+ expect(screen.getByRole("switch", { name: "Redact" })).toBeDisabled();+ expect(+ screen.getByText("Required policy · manage in pipeline settings"),+ ).toBeTruthy();+ });+ it("leaves enablement unchanged and shows an error when the save fails", async () => {+ setEnabled.mockRejectedValue(new Error("offline"));+ mount();+ await expand();+ fireEvent.click(screen.getByRole("switch", { name: "Rotate" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Could not change this pipeline",+ );+ expect(screen.getByRole("switch", { name: "Rotate" })).toBeChecked();+ });+ it("does not offer mutations without server management permission", async () => {+ fetchPipelines.mockResolvedValue({+ pipelines: [optional],+ canManage: false,+ });+ mount();+ await expand();+ expect(screen.getByRole("switch", { name: "Rotate" })).toBeDisabled();+ });+ it("limits the list to five rows and sends larger lists to Pipelines", async () => {+ fetchPipelines.mockResolvedValue({+ pipelines: [+ ...Array.from({ length: 6 }, (_, index) => ({+ ...optional,+ id: `pipeline-${index}`,+ name: `Pipeline ${index}`,+ })),+ optional,+ ],+ canManage: true,+ });+ const manage = vi.fn();+ mount(manage);+ await expand();+ expect(screen.getAllByRole("switch")).toHaveLength(5);+ expect(screen.getAllByRole("switch")[0]).toHaveAccessibleName("Rotate");+ fireEvent.click(screen.getByRole("button", { name: "View all pipelines" }));+ expect(manage).toHaveBeenCalledWith(undefined);+ });+});diff --git a/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsx b/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsxnew file mode 100644index 0000000000..1f0b64c1f3--- /dev/null+++ b/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsx@@ -0,0 +1,238 @@+import { useEffect, useId, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { Button, ToggleSwitch } from "@app/ui";+import { Icon } from "@app/ui/Icon";+import { Tooltip } from "@app/ui/Tooltip";+import {+ fetchCreditPromptPipelines,+ setCreditPromptPipelineEnabled,+ type CreditPromptPipeline,+} from "@app/services/creditPromptPipelines";+import { pipelineQueryKeys } from "@app/policies/queryKeys";++interface Props {+ onManagePipeline?: (id?: string) => void;+ affectedPipelineId?: string;+}++/** Secondary controls for optional automation; opening the disclosure never changes a pipeline. */+export function CreditPromptPipelines({+ onManagePipeline,+ affectedPipelineId,+}: Props) {+ const [expanded, setExpanded] = useState(false);+ const listId = useId();+ const { t } = useTranslation();+ const queryClient = useQueryClient();+ const [pipelines, setPipelines] = useState<CreditPromptPipeline[]>([]);+ const [canManage, setCanManage] = useState(false);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<"load" | "save" | null>(null);+ useEffect(() => {+ let active = true;+ fetchCreditPromptPipelines()+ .then((result) => {+ if (!active) return;+ setPipelines(+ [...result.pipelines].sort(+ (a, b) =>+ Number(b.id === affectedPipelineId) -+ Number(a.id === affectedPipelineId),+ ),+ );+ setCanManage(result.canManage);+ })+ .catch(() => {+ if (active) setError("load");+ })+ .finally(() => {+ if (active) setLoading(false);+ });+ return () => {+ active = false;+ };+ }, [affectedPipelineId]);++ async function changeEnabled(+ pipeline: CreditPromptPipeline,+ enabled: boolean,+ ) {+ setBusy(pipeline.id);+ setError(null);+ try {+ await setCreditPromptPipelineEnabled(pipeline.id, enabled);+ setPipelines((rows) =>+ rows.map((row) => (row.id === pipeline.id ? { ...row, enabled } : row)),+ );+ void queryClient.invalidateQueries({+ queryKey: pipelineQueryKeys.pipelines(),+ });+ void queryClient.invalidateQueries({+ queryKey: pipelineQueryKeys.policiesList(),+ });+ } catch {+ setError("save");+ } finally {+ setBusy(null);+ }+ }++ function sourceLabel(pipeline: CreditPromptPipeline) {+ const labels = pipeline.sources.map((source) => source.name);+ if (pipeline.editor?.allowed || pipeline.trigger.startsWith("editor-")) {+ labels.unshift(+ pipeline.editor?.runOn === "export" ||+ pipeline.trigger === "editor-export"+ ? t(+ "portal.accountLink.pipelines.editorExport",+ "Editor · before download",+ )+ : t(+ "portal.accountLink.pipelines.editorUpload",+ "Editor · on upload",+ ),+ );+ }+ return (+ labels.join(", ") ||+ t("portal.accountLink.pipelines.manual", "Manual runs")+ );+ }++ return (+ <section className="portal-connect__pipelines">+ <div className="portal-connect__pipeline-header">+ <button+ type="button"+ className="portal-connect__pipeline-disclosure"+ aria-expanded={expanded}+ aria-controls={listId}+ onClick={() => setExpanded((value) => !value)}+ >+ <Icon name={expanded ? "chevron-down" : "chevron-right"} size={14} />+ <span>+ {t("portal.accountLink.pipelines.title", "Active pipelines")}+ </span>+ {!loading && error !== "load" && (+ <span className="portal-connect__pipeline-count">+ {" "}+ {pipelines.filter((pipeline) => pipeline.enabled).length}+ </span>+ )}+ </button>+ {onManagePipeline && (+ <Button+ size="sm"+ px="none"+ variant="quiet"+ accent="neutral"+ onClick={() =>+ onManagePipeline(+ pipelines.length > 5 ? undefined : affectedPipelineId,+ )+ }+ >+ {pipelines.length > 5+ ? t("portal.accountLink.pipelines.viewAll", "View all pipelines")+ : t(+ "portal.accountLink.failure.manage",+ "Open pipeline settings",+ )}+ </Button>+ )}+ </div>+ {expanded && (+ <div id={listId} className="portal-connect__pipeline-choices">+ {loading ? (+ <p className="portal-connect__lede">+ {t("portal.accountLink.pipelines.loading", "Loading pipelines…")}+ </p>+ ) : (+ <>+ {!error && pipelines.length === 0 && (+ <p className="portal-connect__lede">+ {t(+ "portal.accountLink.pipelines.empty",+ "No active pipelines.",+ )}+ </p>+ )}+ <ul className="portal-connect__pipeline-list">+ {pipelines.slice(0, 5).map((pipeline) => (+ <li key={pipeline.id}>+ <div className="portal-connect__pipeline-details">+ <span className="portal-connect__row-label">+ {pipeline.name}+ {pipeline.id === affectedPipelineId && (+ <Tooltip+ content={t(+ "portal.accountLink.pipelines.triggered",+ "Triggered this prompt",+ )}+ >+ <button+ type="button"+ className="portal-connect__trigger-info"+ aria-label={t(+ "portal.accountLink.pipelines.triggered",+ "Triggered this prompt",+ )}+ >+ <Icon name="info" size={14} />+ </button>+ </Tooltip>+ )}+ </span>+ <span className="portal-connect__pipeline-source">+ {sourceLabel(pipeline)}++ {pipeline.required && (+ <span className="portal-connect__pipeline-note">+ {t(+ "portal.accountLink.pipelines.required",+ "Required policy · manage in pipeline settings",+ )}+ </span>+ )}+ {!pipeline.enabled && (+ <span className="portal-connect__pipeline-note">+ {t("portal.accountLink.pipelines.paused", "Paused")}+ </span>+ )}+ </span>+ </div>+ <ToggleSwitch+ aria-label={pipeline.name}+ checked={pipeline.enabled}+ disabled={+ !canManage || pipeline.required || busy !== null+ }+ onChange={(enabled) =>+ void changeEnabled(pipeline, enabled)+ }+ />+ </li>+ ))}+ </ul>+ </>+ )}+ {error && (+ <p role="alert" className="portal-connect__lede">+ {error === "load"+ ? t(+ "portal.accountLink.pipelines.loadFailed",+ "Could not load pipelines. Open pipeline settings to try again.",+ )+ : t(+ "portal.accountLink.pipelines.saveFailed",+ "Could not change this pipeline. Open pipeline settings to review it.",+ )}+ </p>+ )}+ </div>+ )}+ </section>+ );+}diff --git a/frontend/editor/src/proprietary/components/account-link/EditorLinkModal.tsx b/frontend/editor/src/proprietary/components/account-link/EditorLinkModal.tsxnew file mode 100644index 0000000000..606879b818--- /dev/null+++ b/frontend/editor/src/proprietary/components/account-link/EditorLinkModal.tsx@@ -0,0 +1,20 @@+import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";+import type { ExhaustedAccountLinkModalProps } from "@app/components/account-link/ExhaustedAccountLinkModal";++/** The browser editor starts the existing account-link flow without leaving the document. */+export function EditorLinkModal({+ open,+ onClose,+ summary,+ failureContext,+}: ExhaustedAccountLinkModalProps) {+ return (+ <LinkAccountModal+ open={open}+ onClose={onClose}+ summary={summary}+ failureContext={failureContext}+ mode="exhausted"+ />+ );+}diff --git a/frontend/editor/src/proprietary/components/account-link/ExhaustedAccountLinkModal.tsx b/frontend/editor/src/proprietary/components/account-link/ExhaustedAccountLinkModal.tsxnew file mode 100644index 0000000000..bbdb0ce82d--- /dev/null+++ b/frontend/editor/src/proprietary/components/account-link/ExhaustedAccountLinkModal.tsx@@ -0,0 +1,189 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { useClipboard } from "@mantine/hooks";+import { useAuth } from "@app/auth";+import { Button } from "@app/ui";+import { FlowModal } from "@app/components/shared/FlowModal";+import { StepModalHeader } from "@app/components/shared/StepModalHeader";+import { CreditPromptPipelines } from "@app/components/account-link/CreditPromptPipelines";+import { ConnectBenefitsSlide } from "@app/components/account-link/ConnectBenefitsSlide";+import {+ acknowledgeAccountLinkPrompt,+ type AccountLinkBlockContext,+} from "@app/services/accountLinkBlock";++export interface ExhaustedAccountLinkModalProps {+ /** Browser linking requires the server owner; native hosts supply their own action. */+ canLink?: boolean;+ /** Only the operation that opened this instance may supply pipeline controls. */+ failureContext?: AccountLinkBlockContext;+ open: boolean;+ onClose: () => void;+ onStart?: () => void;+ /** Hosts open the affected pipeline in their own routing environment. */+ onManagePipeline?: (pipelineId?: string) => void;+ /** The host reads the ledger; unavailable figures are omitted. */+ summary?: ReactNode;+ /** Web hosts supply content with connection configuration and handoff errors. */+ children?: ReactNode;+}++/** Shared content for the Processor, browser editor and native self-hosted connections. */+export function ExhaustedAccountLinkContent({+ summary,+}: {+ summary?: ReactNode;+}) {+ const { t } = useTranslation();+ return (+ <>+ <p className="portal-connect__lede">+ {t(+ "portal.accountLink.connect.exhaustedLede",+ "This server has used its free credits for the month. Link a new or existing Stirling account to access your team’s monthly allowance.",+ )}+ </p>+ {summary}+ <ConnectBenefitsSlide />+ </>+ );+}++/** One exhaustion prompt, with administrator actions and member guidance determined by the host's auth. */+export function ExhaustedAccountLinkModal({+ open,+ onClose,+ onStart,+ onManagePipeline,+ summary,+ children,+ failureContext: context,+ canLink,+}: ExhaustedAccountLinkModalProps) {+ const { t } = useTranslation();+ const { isAdmin, loading } = useAuth();+ const canManageAccount = canLink ?? isAdmin;+ const clipboard = useClipboard();+ const dismiss = () => {+ acknowledgeAccountLinkPrompt();+ onClose();+ };+ const details = {+ pipeline:+ context?.pipelineName ||+ t("portal.accountLink.failure.pipeline", "Pipeline"),+ };+ const causes = context+ ? {+ upload: t(+ "portal.accountLink.failure.upload",+ "Pipeline “{{pipeline}}” stopped after upload because this server is out of credits.",+ details,+ ),+ export: t(+ "portal.accountLink.failure.export",+ "Pipeline “{{pipeline}}” stopped before download because this server is out of credits.",+ details,+ ),+ manual: t(+ "portal.accountLink.failure.manual",+ "Pipeline “{{pipeline}}” stopped when you ran it because this server is out of credits.",+ details,+ ),+ automatic: t(+ "portal.accountLink.failure.automatic",+ "Pipeline “{{pipeline}}” stopped during an automatic run because this server is out of credits.",+ details,+ ),+ }+ : null;+ const cause = context && causes ? causes[context.trigger] : "";+ const title = canManageAccount+ ? t(+ "portal.accountLink.modal.exhaustedTitle",+ "Keep your workflows running",+ )+ : t(+ "portal.accountLink.connect.adminTitle",+ "Ask your server administrator",+ );+ const adminMessage = t(+ "portal.accountLink.connect.adminRequired",+ "Ask your server administrator to open Usage & billing and link a Stirling account for more monthly credits. Manual PDF tools are still available.",+ );+ return (+ <FlowModal+ open={open}+ onClose={dismiss}+ label={title}+ footer={+ canManageAccount ? (+ <>+ <Button variant="quiet" accent="neutral" onClick={dismiss}>+ {t("portal.accountLink.connect.notNow", "Not now")}+ </Button>+ <Button+ variant="primary"+ onClick={onStart}+ disabled={loading || !onStart}+ >+ {t(+ "portal.accountLink.rail.exhaustedCta",+ "Link account for more credits",+ )}+ </Button>+ </>+ ) : (+ <>+ <Button variant="quiet" accent="neutral" onClick={dismiss}>+ {t("portal.accountLink.connect.close", "Close")}+ </Button>+ <Button+ variant="secondary"+ onClick={() =>+ clipboard.copy(+ [cause, adminMessage].filter(Boolean).join("\n\n"),+ )+ }+ >+ {clipboard.copied+ ? t("portal.accountLink.connect.copied", "Copied")+ : t(+ "portal.accountLink.connect.copyAdminMessage",+ "Copy message for administrator",+ )}+ </Button>+ </>+ )+ }+ >+ <StepModalHeader+ brand+ title={title}+ closeLabel={t("portal.accountLink.connect.close", "Close")}+ onClose={dismiss}+ />+ {!canManageAccount && cause && (+ <p className="portal-connect__lede">{cause}</p>+ )}+ {canManageAccount ? (+ (children ?? <ExhaustedAccountLinkContent summary={summary} />)+ ) : (+ <p className="portal-connect__lede">{adminMessage}</p>+ )}+ {canManageAccount && context?.pipelineId && (+ <CreditPromptPipelines+ affectedPipelineId={context?.pipelineId}+ onManagePipeline={+ onManagePipeline+ ? (id) => {+ dismiss();+ onManagePipeline(id);+ }+ : undefined+ }+ />+ )}+ </FlowModal>+ );+}diff --git a/frontend/editor/src/proprietary/components/account-link/FreeTierBalanceSummary.tsx b/frontend/editor/src/proprietary/components/account-link/FreeTierBalanceSummary.tsxnew file mode 100644index 0000000000..19537c4aae--- /dev/null+++ b/frontend/editor/src/proprietary/components/account-link/FreeTierBalanceSummary.tsx@@ -0,0 +1,50 @@+import { useTranslation } from "react-i18next";+import { formatPeriodDate, MeterBar, remainingMeter } from "@app/billing";++/** Local server allowance; figures are never inferred from an exhausted response. */+export interface FreeTierBalance {+ grantUnits: number;+ usedUnits: number;+ remainingUnits: number;+ periodStart: string;+ periodEnd: string;+}+/** Renders only authoritative figures, including outside the Processor provider tree. */+export function FreeTierBalanceSummary({+ balance,+}: {+ balance?: FreeTierBalance;+}) {+ const { t } = useTranslation();+ if (!balance) return null;+ const { state, pct } = remainingMeter(+ balance.remainingUnits,+ balance.grantUnits,+ );+ const resets = formatPeriodDate(balance.periodEnd);+ return (+ <div className="portal-connect__meter">+ <MeterBar+ state={state}+ pct={pct}+ figure={balance.remainingUnits.toLocaleString()}+ barLabel={t("portal.usage.freeTier.barAria", "Free credits remaining")}+ capSuffix={t(+ "portal.usage.freeTier.capSuffix",+ "of {{allowance}} free credits left this month",+ {+ allowance: balance.grantUnits.toLocaleString(),+ count: balance.grantUnits,+ },+ )}+ meta={+ resets+ ? t("portal.usage.freeTier.resets", "Resets {{date}}", {+ date: resets,+ })+ : null+ }+ />+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/account-link/connect/connect.css b/frontend/editor/src/proprietary/components/account-link/connect.csssimilarity index 55%rename from frontend/editor/src/portal/components/account-link/connect/connect.cssrename to frontend/editor/src/proprietary/components/account-link/connect.cssindex c22bbb62a1..361c762c20 100644--- a/frontend/editor/src/portal/components/account-link/connect/connect.css+++ b/frontend/editor/src/proprietary/components/account-link/connect.css@@ -11,6 +11,91 @@color: var(--c-text-muted);}+.portal-connect__pipeline-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ flex-wrap: wrap;+}++.portal-connect__pipeline-disclosure {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ padding: 0;+ border: 0;+ background: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text);+}++.portal-connect__pipeline-count {+ color: var(--c-text-muted);+ font-weight: 400;+ font-variant-numeric: tabular-nums;+}++.portal-connect__pipeline-details > .portal-connect__row-label {+ display: flex;+ align-items: center;+ gap: 0.375rem;+}++.portal-connect__trigger-info {+ display: inline-flex;+ padding: 0;+ border: 0;+ background: none;+ color: var(--c-text-subtle);+ cursor: help;+}++.portal-connect__pipeline-choices {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ padding-top: 0.75rem;+}++.portal-connect__pipeline-list {+ list-style: none;+ padding: 0;+ margin: 0;+}++.portal-connect__pipeline-list li {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ padding: 0.5rem 0;+ border-bottom: 1px solid var(--c-border);+ overflow-wrap: anywhere;+}++.portal-connect__pipeline-details {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr);+ align-items: center;+ gap: 1rem;+ flex: 1;+ min-width: 0;+}++.portal-connect__pipeline-source {+ display: block;+ font-size: 0.75rem;+ color: var(--c-text-muted);+}++.portal-connect__pipeline-note {+ display: block;+}+.portal-connect__list {margin: 0;border-top: 1px solid var(--c-border);@@ -26,6 +111,7 @@}.portal-connect__row-label {+ flex-shrink: 0;font-size: 0.8125rem;font-weight: 600;color: var(--c-text);@@ -38,6 +124,24 @@text-align: right;}+@media (max-width: 30rem) {+ .portal-connect__pipeline-details {+ grid-template-columns: minmax(0, 1fr);+ gap: 0.125rem;+ }++ .portal-connect__row {+ flex-direction: column;+ gap: 0.25rem;+ }++ .portal-connect__row-detail {+ text-align: left;+ }+}++/* ── Step 2: the ghost ──────────────────────────────────────────────────── */+.portal-connect__ghost {display: flex;align-items: center;diff --git a/frontend/editor/src/proprietary/components/chat/ChatContext.tsx b/frontend/editor/src/proprietary/components/chat/ChatContext.tsxindex b1b7b44f4f..cc3fa3d06a 100644--- a/frontend/editor/src/proprietary/components/chat/ChatContext.tsx+++ b/frontend/editor/src/proprietary/components/chat/ChatContext.tsx@@ -14,6 +14,10 @@ import apiClient from "@app/services/apiClient";import { getAiBaseUrl } from "@app/services/aiBaseUrl";import { getAuthHeaders } from "@app/services/apiClientSetup";import { dispatchPaygLimitReached } from "@app/services/usageLimitBridge";+import {+ reportAccountLinkBlock,+ reportFreeTierExhausted,+} from "@app/services/accountLinkBlock";import { createChildStub } from "@app/contexts/file/fileActions";import {createNewStirlingFileStub,@@ -581,7 +585,9 @@ export function ChatProvider({ children }: { children: ReactNode }) {// A 402 carrying a usage-limit sentinel means the agent call itself was gated.// Fire the usage-limit modal (free → subscribe, subscribed → raise cap) and show a// brief line below — not a generic "engine failed" error.- if (response.status === 402 && isPaygLimitCode(code)) {+ if (reportAccountLinkBlock({ status: response.status, body })) {+ limitHandled = true;+ } else if (response.status === 402 && isPaygLimitCode(code)) {dispatchPaygLimitReached(typeof body?.subscribed === "boolean" ? body.subscribed : null,);@@ -647,8 +653,11 @@ export function ChatProvider({ children }: { children: ReactNode }) {// result (not via the apiClient interceptor that pops the modal for direct calls).// Fire the matching modal and replace the raw "tool failed: 402…" reason with a// brief, non-alarming line.- const isLimit = isPaygLimitCode(data.errorCode);- if (isLimit) {+ const localLimit = data.errorCode === "FREE_TIER_EXHAUSTED";+ const isLimit = localLimit || isPaygLimitCode(data.errorCode);+ if (localLimit) {+ reportFreeTierExhausted();+ } else if (isLimit) {dispatchPaygLimitReached(data.errorSubscribed ?? null);}const replyContent = isLimitdiff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsxindex 49a44865e4..278ddaf6ea 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx@@ -171,6 +171,7 @@ describe("auto-run ordered chaining", () => {"backend-comp",expect.anything(),"unlocked",+ "background",);expect(getFile).not.toHaveBeenCalledWith("locked");});@@ -198,6 +199,7 @@ describe("auto-run ordered chaining", () => {"backend-comp",expect.anything(),"pdf",+ "background",);});@@ -216,6 +218,7 @@ describe("auto-run ordered chaining", () => {"backend-comp",expect.anything(),"pdf",+ "background",);});@@ -235,6 +238,7 @@ describe("auto-run ordered chaining", () => {"backend-archive",expect.anything(),"image",+ "background",);});it("dispatches only matching files from a mixed upload", async () => {@@ -259,6 +263,7 @@ describe("auto-run ordered chaining", () => {"backend-sec",expect.anything(),"pdf",+ "background",);expect(getFile).not.toHaveBeenCalledWith("image");expect(getFile).not.toHaveBeenCalledWith("word");@@ -323,6 +328,7 @@ describe("auto-run ordered chaining", () => {"backend-comp",expect.anything(),"image",+ "background",);expect(getRun("run-image")?.fileName).toBe("page.png");});@@ -343,6 +349,7 @@ describe("auto-run ordered chaining", () => {"backend-sec",[{ size: 100 }],"file-1",+ "background",);});@@ -361,6 +368,7 @@ describe("auto-run ordered chaining", () => {"backend-comp",[{ size: 100 }],"file-1-v2",+ "background",);});@@ -379,6 +387,7 @@ describe("auto-run ordered chaining", () => {"backend-cls",expect.anything(),expect.anything(),+ "background",);});diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsxindex 5f10ef5966..15410c3889 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx@@ -107,6 +107,7 @@ describe("an upload waiting on its unlock prompt", () => {"backend-sec",expect.anything(),"file-locked",+ "background",);});diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsxindex 137ad13f1c..5ac717ef2d 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx@@ -123,6 +123,7 @@ describe("auto-run queue-rejection retry", () => {"backend-1",[{ size: 1234 }],"file-1",+ "background",);expect(getRun("run-1")).toBeUndefined();expect(getRun("run-2")?.status).toBe("RUNNING");diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.tsindex 8c4f2a548a..b3eccff768 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts@@ -34,6 +34,7 @@ import type {PolicyRunView,} from "@app/services/policyPipeline";import { dispatchPaygLimitReached } from "@app/services/usageLimitBridge";+import { reportFreeTierExhausted } from "@app/services/accountLinkBlock";import {dispatchableFileId,type DispatchableFileId,@@ -46,6 +47,7 @@ import {policyDeliversOutputFiles,} from "@app/data/classificationPolicy";import { runPolicyOnFile } from "@app/services/policyDispatch";+import { policyCreditContext } from "@app/services/policyCreditContext";import { policyAcceptsFile } from "@app/services/policyInput";import { splitFileName } from "@app/utils/fileUtils";import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";@@ -236,6 +238,13 @@ export function usePolicyAutoRun(): void {// Read now rather than leaving them a poll interval to hear about their own upload.if (view.status === "FAILED") refreshNotificationsNow();const code = view.errorCode;+ if (code === "FREE_TIER_EXHAUSTED") {+ if (!firedLimitModal.current.has(view.runId)) {+ firedLimitModal.current.add(view.runId);+ reportFreeTierExhausted(policyCreditContext(view.policyId));+ }+ return;+ }if (code !== "PAYG_LIMIT_REACHED" && code !== "FEATURE_DEGRADED") return;if (firedLimitModal.current.has(view.runId)) return;firedLimitModal.current.add(view.runId);@@ -391,7 +400,10 @@ export function usePolicyAutoRun(): void {run,() =>classificationLabelTargetStubs(run.fileId, fileStubsRef.current),- { updateStirlingFileStub, bumpRevision },+ {+ updateStirlingFileStub,+ bumpRevision,+ },).finally(() => importing.current.delete(run.runId));continue;}diff --git a/frontend/editor/src/portal/components/shared/FlowModal.css b/frontend/editor/src/proprietary/components/shared/FlowModal.csssimilarity index 100%rename from frontend/editor/src/portal/components/shared/FlowModal.cssrename to frontend/editor/src/proprietary/components/shared/FlowModal.cssdiff --git a/frontend/editor/src/proprietary/components/shared/FlowModal.tsx b/frontend/editor/src/proprietary/components/shared/FlowModal.tsxnew file mode 100644index 0000000000..3e7e56eab5--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/FlowModal.tsx@@ -0,0 +1,42 @@+import type { ReactNode } from "react";+import { Modal } from "@app/ui";+import "@app/components/shared/FlowModal.css";++/**+ * The shared Modal owns focus trapping, scroll locking and dismissal. This wrapper adds the+ * flow's stacked body, footer spacing and takeover width. Omitting `header` removes the title+ * band; hosts then supply their own heading and close button inside the body.+ */+export function FlowModal({+ open,+ onClose,+ label,+ header,+ footer,+ size = "md",+ children,+}: {+ open: boolean;+ onClose: () => void;+ /** Accessible name, used when `header` supplies no visible heading of its own. */+ label: string;+ header?: ReactNode;+ footer?: ReactNode;+ /** `md` for the task dialogs, `lg` for the procurement takeover and Calendly. */+ size?: "md" | "lg";+ children: ReactNode;+}) {+ return (+ <Modal+ open={open}+ onClose={onClose}+ ariaLabel={label}+ width={size}+ className={`portal-flowmodal portal-flowmodal--${size}`}+ title={header}+ footer={footer}+ >+ {children}+ </Modal>+ );+}diff --git a/frontend/editor/src/proprietary/policies/queryKeys.ts b/frontend/editor/src/proprietary/policies/queryKeys.tsnew file mode 100644index 0000000000..01fc1862fc--- /dev/null+++ b/frontend/editor/src/proprietary/policies/queryKeys.ts@@ -0,0 +1,5 @@+/** Shared cache identities keep editor-side changes reflected in the Processor. */+export const pipelineQueryKeys = {+ pipelines: () => ["portal", "pipelines"] as const,+ policiesList: () => ["portal", "policies", "list"] as const,+};diff --git a/frontend/editor/src/proprietary/services/creditPromptPipelines.test.ts b/frontend/editor/src/proprietary/services/creditPromptPipelines.test.tsnew file mode 100644index 0000000000..d88d0ac7df--- /dev/null+++ b/frontend/editor/src/proprietary/services/creditPromptPipelines.test.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ fetchCreditPromptPipelines,+ setCreditPromptPipelineEnabled,+} from "@app/services/creditPromptPipelines";++const { get, post, updatePolicy } = vi.hoisted(() => ({+ get: vi.fn(),+ post: vi.fn(),+ updatePolicy: vi.fn(),+}));+vi.mock("@app/services/apiClient", () => ({ default: { get, post } }));+vi.mock("@app/services/policyStorage", () => ({+ loadPolicies: () => ({ rotate: { backendId: "rotate-id" } }),+ updatePolicy,+}));++describe("credit prompt pipeline controls", () => {+ beforeEach(() => vi.resetAllMocks());+ it("lists active pipelines with their saved sources and editor participation", async () => {+ get.mockImplementation(async (path: string) => ({+ data: path.endsWith("overview")+ ? {+ pipelines: [+ {+ id: "rotate-id",+ enabled: true,+ sources: [{ id: "inbox", name: "Shared inbox" }],+ },+ { id: "paused", enabled: false },+ ],+ }+ : path.endsWith("permissions")+ ? { canManagePolicies: true }+ : [{ id: "rotate-id", editor: { allowed: true, runOn: "export" } }],+ }));+ expect(await fetchCreditPromptPipelines()).toEqual({+ canManage: true,+ pipelines: [+ {+ id: "rotate-id",+ enabled: true,+ sources: [{ id: "inbox", name: "Shared inbox" }],+ editor: { allowed: true, runOn: "export" },+ },+ ],+ });+ });+ it("preserves the latest policy definition and updates the editor only after a successful save", async () => {+ const policy = {+ id: "rotate-id",+ name: "New name",+ enabled: true,+ required: false,+ inputs: [{ sourceId: "shared" }],+ routingRules: [{ condition: { type: "and" }, outputId: "archive" }],+ steps: [{ operation: "rotate", parameters: { angle: 90 } }],+ };+ get.mockResolvedValue({ data: policy });+ post.mockResolvedValue({ data: { ...policy, enabled: false } });+ await setCreditPromptPipelineEnabled("rotate-id", false);+ expect(post).toHaveBeenCalledWith(+ "/api/v1/policies",+ { ...policy, enabled: false },+ { suppressErrorToast: true },+ );+ expect(updatePolicy).toHaveBeenCalledWith("rotate", { enabled: false });+ });+ it("refuses to disable a policy made required since the list was loaded", async () => {+ get.mockResolvedValue({ data: { id: "rotate-id", required: true } });+ await expect(+ setCreditPromptPipelineEnabled("rotate-id", false),+ ).rejects.toThrow("Required policies");+ expect(post).not.toHaveBeenCalled();+ expect(updatePolicy).not.toHaveBeenCalled();+ });+ it("does not change the editor cache when a save fails", async () => {+ get.mockResolvedValue({+ data: { id: "rotate-id", enabled: true, required: false },+ });+ post.mockRejectedValue(new Error("offline"));+ await expect(+ setCreditPromptPipelineEnabled("rotate-id", false),+ ).rejects.toThrow("offline");+ expect(updatePolicy).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/proprietary/services/creditPromptPipelines.ts b/frontend/editor/src/proprietary/services/creditPromptPipelines.tsnew file mode 100644index 0000000000..de303cda72--- /dev/null+++ b/frontend/editor/src/proprietary/services/creditPromptPipelines.ts@@ -0,0 +1,59 @@+import apiClient from "@app/services/apiClient";+import { loadPolicies, updatePolicy } from "@app/services/policyStorage";+import type { WirePolicy, WireEditorConfig } from "@app/policies/types";++/** The overview fields needed to explain and manage active automation in a credit prompt. */+export interface CreditPromptPipeline {+ id: string;+ name: string;+ enabled: boolean;+ required: boolean;+ trigger: string;+ sources: { id: string; name: string }[];+ editor?: WireEditorConfig;+}++/** Reads active pipelines and their sources from the connected server, including editor inputs. */+export async function fetchCreditPromptPipelines() {+ const options = { suppressErrorToast: true };+ const [overview, policies, permissions] = await Promise.all([+ apiClient.get<{ pipelines: CreditPromptPipeline[] }>(+ "/api/v1/policies/overview",+ options,+ ),+ apiClient.get<WirePolicy[]>("/api/v1/policies", options),+ apiClient.get<{ canManagePolicies: boolean }>(+ "/api/v1/policies/permissions",+ options,+ ),+ ]);+ const pipelines: CreditPromptPipeline[] = overview.data.pipelines+ .filter((pipeline) => pipeline.enabled)+ .map((pipeline) => ({+ ...pipeline,+ editor: policies.data.find((policy) => policy.id === pipeline.id)?.editor,+ }));+ return { pipelines, canManage: permissions.data.canManagePolicies };+}++/** Updates only enablement on a fresh server record; required policies must be managed in settings. */+export async function setCreditPromptPipelineEnabled(+ id: string,+ enabled: boolean,+): Promise<void> {+ const options = { suppressErrorToast: true };+ const { data: current } = await apiClient.get<WirePolicy>(+ `/api/v1/policies/${encodeURIComponent(id)}`,+ options,+ );+ if (current.required)+ throw new Error("Required policies must be managed in pipeline settings");+ const { data: saved } = await apiClient.post<WirePolicy>(+ "/api/v1/policies",+ { ...current, enabled },+ options,+ );+ for (const [key, policy] of Object.entries(loadPolicies())) {+ if (policy.backendId === id) updatePolicy(key, { enabled: saved.enabled });+ }+}diff --git a/frontend/editor/src/proprietary/services/policyApi.test.ts b/frontend/editor/src/proprietary/services/policyApi.test.tsindex de3d7bb2e5..0d8445e9a8 100644--- a/frontend/editor/src/proprietary/services/policyApi.test.ts+++ b/frontend/editor/src/proprietary/services/policyApi.test.ts@@ -64,4 +64,17 @@ describe("runStoredPolicy", () => {expect(sent.name).toBe(source.name);expect(await textOf(sent)).toBe(await textOf(source));});++ it("includes the pipeline and distinguishes automatic dispatches from manual retries", async () => {+ await runStoredPolicy("policy-1", [document()], "file-1", "background");+ expect(post.mock.calls.at(-1)?.[2]).toMatchObject({+ suppressErrorToast: true,+ accountLinkBlockContext: { pipelineId: "policy-1", trigger: "automatic" },+ });+ await runStoredPolicy("policy-1", [document()], "file-1");+ expect(post.mock.calls.at(-1)?.[2]).toMatchObject({+ suppressErrorToast: true,+ accountLinkBlockContext: { pipelineId: "policy-1", trigger: "manual" },+ });+ });});diff --git a/frontend/editor/src/proprietary/services/policyApi.ts b/frontend/editor/src/proprietary/services/policyApi.tsindex 365645ce4f..3fefcbc0b8 100644--- a/frontend/editor/src/proprietary/services/policyApi.ts+++ b/frontend/editor/src/proprietary/services/policyApi.ts@@ -8,6 +8,8 @@import apiClient from "@app/services/apiClient";import { uploadableFile } from "@app/utils/uploadableFile";import { getPolicyOutputBaseUrl } from "@app/services/policyOutputBaseUrl";+import type { AccountLinkBlockSource } from "@app/services/accountLinkBlock";+import { policyCreditContext } from "@app/services/policyCreditContext";import type {BackendPolicy,PolicyExecutionTarget,@@ -36,6 +38,7 @@ export async function runStoredPolicy(id: string,files: File[],fileId?: string,+ source: AccountLinkBlockSource = "foreground",): Promise<string> {const form = new FormData();for (const file of files) form.append("fileInput", uploadableFile(file));@@ -46,7 +49,10 @@ export async function runStoredPolicy(const res = await apiClient.post<JobResponse>(`/api/v1/policies/${encodeURIComponent(id)}/run`,form,- { suppressErrorToast: true },+ {+ suppressErrorToast: true,+ accountLinkBlockContext: policyCreditContext(id, source),+ },);return res.data.jobId;}@@ -70,7 +76,9 @@ export async function downloadPolicyOutput(const base = await getPolicyOutputBaseUrl(target);const res = await apiClient.get<Blob>(`${base}/api/v1/general/files/${encodeURIComponent(fileId)}`,- { responseType: "blob" },+ {+ responseType: "blob",+ },);return res.data;}diff --git a/frontend/editor/src/proprietary/services/policyCreditContext.test.ts b/frontend/editor/src/proprietary/services/policyCreditContext.test.tsnew file mode 100644index 0000000000..39d56666a7--- /dev/null+++ b/frontend/editor/src/proprietary/services/policyCreditContext.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from "vitest";+import { policyCreditContext } from "@app/services/policyCreditContext";++vi.mock("@app/services/policyStorage", () => ({+ loadPolicies: () => ({+ rotate: {+ backendId: "rotate-id",+ name: "Quarterly rotation",+ configured: true,+ enabled: true,+ runsOnEditor: true,+ runOn: "upload",+ },+ watermark: {+ backendId: "watermark-id",+ name: "Confidential watermark",+ configured: true,+ enabled: true,+ runsOnEditor: true,+ runOn: "export",+ },+ }),+}));+vi.mock("@app/services/policyCatalog", () => ({+ loadPolicyCatalog: () => ({ categories: [] }),+}));++describe("credit failure pipeline context", () => {+ it("identifies upload and export pipelines by saved name", () => {+ expect(policyCreditContext("rotate-id")).toEqual({+ pipelineId: "rotate-id",+ pipelineName: "Quarterly rotation",++ trigger: "upload",+ });+ expect(policyCreditContext("watermark-id").trigger).toBe("export");+ });+ it("identifies an explicit retry independently of the configured automatic trigger", () => {+ expect(policyCreditContext("rotate-id", "foreground").trigger).toBe(+ "manual",+ );+ });+ it("keeps an uncached pipeline navigable without displaying its internal id as a name", () => {+ expect(policyCreditContext("unknown")).toEqual({+ pipelineId: "unknown",+ pipelineName: undefined,++ trigger: "automatic",+ });+ });+ it("handles failures without a policy identifier", () => {+ expect(policyCreditContext(null).pipelineId).toBeUndefined();+ expect(policyCreditContext(null).trigger).toBe("automatic");+ });+});diff --git a/frontend/editor/src/proprietary/services/policyCreditContext.ts b/frontend/editor/src/proprietary/services/policyCreditContext.tsnew file mode 100644index 0000000000..8b2cd0605a--- /dev/null+++ b/frontend/editor/src/proprietary/services/policyCreditContext.ts@@ -0,0 +1,28 @@+import { loadPolicies } from "@app/services/policyStorage";+import { loadPolicyCatalog } from "@app/services/policyCatalog";+import { editorTriggerOf } from "@app/policies/runOn";+import type {+ AccountLinkBlockContext,+ AccountLinkBlockSource,+} from "@app/services/accountLinkBlock";++/** Resolves user-facing pipeline details from the editor cache without delaying a failed request. */+export function policyCreditContext(+ pipelineId: string | null,+ source: AccountLinkBlockSource = "background",+): AccountLinkBlockContext {+ const entry = Object.entries(loadPolicies()).find(+ ([, policy]) => Boolean(pipelineId) && policy.backendId === pipelineId,+ );+ const category =+ entry &&+ loadPolicyCatalog().categories.find((item) => item.id === entry[0]);+ return {+ pipelineId: pipelineId ?? undefined,+ pipelineName: entry?.[1].name || category?.label,+ trigger:+ source === "foreground"+ ? "manual"+ : (entry && editorTriggerOf(entry[1])) || "automatic",+ };+}diff --git a/frontend/editor/src/proprietary/services/policyDispatch.ts b/frontend/editor/src/proprietary/services/policyDispatch.tsindex d414712d52..102cbad91e 100644--- a/frontend/editor/src/proprietary/services/policyDispatch.ts+++ b/frontend/editor/src/proprietary/services/policyDispatch.ts@@ -102,7 +102,12 @@ export async function dispatchPolicyFile(try {// Recorded against a document this browser can resolve. One file per run, which is the only// shape the server keeps a reference for.- const runId = await runStoredPolicy(backendId, [file], fileId);+ const runId = await runStoredPolicy(+ backendId,+ [file],+ fileId,+ "background",+ );// recordRunStart marks this (policy, file) dispatched as it records the run.recordRunStart({runId,diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.tsindex a3f676f3f5..69d0528c05 100644--- a/frontend/editor/src/proprietary/services/policyExport.test.ts+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts@@ -8,14 +8,18 @@ vi.mock("@app/services/policyStorage", () => ({loadPolicies: () => loadPolicies(),}));-const runStoredPolicy = vi.fn(async (_id: string, _files: File[]) => "run-1");+const runStoredPolicy = vi.fn(+ async (_id: string, _files: File[], _fileId?: string, _source?: string) =>+ "run-1",+);const output = { name: "doc.pdf", type: "application/pdf" };let serverExternalOutput = false;const downloadPolicyOutput = vi.fn(async () => new Blob([], { type: output.type }),);vi.mock("@app/services/policyApi", () => ({- runStoredPolicy: (id: string, files: File[]) => runStoredPolicy(id, files),+ runStoredPolicy: (...args: Parameters<typeof runStoredPolicy>) =>+ runStoredPolicy(...args),// One output, so a run completes rather than throwing "produced no output" - which would abort// the per-file policy loop after the first policy and hide the order under test.getPolicyRun: async () => ({@@ -37,9 +41,10 @@ vi.mock("@app/components/policies/policyRunStore", () => ({vi.mock("@app/components/policies/enforcementQueue", () => ({runQueued: <T>(_meta: unknown, task: () => Promise<T>) => task(),}));+const { updateToast } = vi.hoisted(() => ({ updateToast: vi.fn() }));vi.mock("@app/components/toast", () => ({alert: () => "toast-1",- updateToast: vi.fn(),+ updateToast,dismissToast: vi.fn(),}));vi.mock("@app/i18n", () => ({ default: { t: (key: string) => key } }));@@ -78,6 +83,7 @@ describe("export-time policy selection", () => {beforeEach(() => {vi.useFakeTimers();runStoredPolicy.mockClear();+ updateToast.mockClear();output.name = "doc.pdf";output.type = "application/pdf";serverExternalOutput = false;@@ -86,6 +92,32 @@ describe("export-time policy selection", () => {});afterEach(() => vi.useRealTimers());+ it("retains the failure warning for an optional export policy with insufficient credits", async () => {+ loadPolicies.mockReturnValue({+ security: exportPolicy({ runsOnEditor: true, required: false }),+ });+ runStoredPolicy.mockRejectedValueOnce({+ response: {+ status: 402,+ data: { error: "ACCOUNT_LINK_REQUIRED", reason: "FREE_TIER_EXHAUSTED" },+ },+ });+ await enforceExportPolicies([pdf()], ["file-1"]);+ expect(runStoredPolicy).toHaveBeenCalledWith(+ "backend-1",+ expect.any(Array),+ undefined,+ "background",+ );+ expect(updateToast).toHaveBeenCalledWith(+ "toast-1",+ expect.objectContaining({+ alertType: "warning",+ title: "policies.enforcement.failureTitle",+ }),+ );+ });+it("records server-reported external delivery when cached metadata says internal", async () => {loadPolicies.mockReturnValue({ingestion: exportPolicy({ runsOnEditor: true, externalOutput: false }),@@ -106,6 +138,27 @@ describe("export-time policy selection", () => {);});+ it("blocks export when a required policy has insufficient credits", async () => {+ loadPolicies.mockReturnValue({+ security: exportPolicy({ runsOnEditor: true, required: true }),+ });+ runStoredPolicy.mockRejectedValueOnce({+ response: {+ status: 402,+ data: { error: "ACCOUNT_LINK_REQUIRED", reason: "FREE_TIER_EXHAUSTED" },+ },+ });+ await expect(enforceExportPolicies([pdf()], ["file-1"])).rejects.toThrow(+ "policy.exportBlocked",+ );+ expect(runStoredPolicy).toHaveBeenCalledWith(+ "backend-1",+ expect.any(Array),+ undefined,+ "background",+ );+ });+it("selects each pipeline by its first input and rechecks converted outputs", async () => {const image = new File(["image"], "scan.PNG", { type: "image/png" });const word = new File(["word"], "letter.docx");@@ -243,6 +296,8 @@ describe("export-time policy selection", () => {expect(runStoredPolicy).toHaveBeenCalledWith("backend-editor",expect.anything(),+ undefined,+ "background",);});@@ -279,6 +334,8 @@ describe("export-time policy selection", () => {expect(runStoredPolicy).toHaveBeenCalledWith("backend-security",expect.anything(),+ undefined,+ "background",);});diff --git a/frontend/editor/src/proprietary/services/policyExport.ts b/frontend/editor/src/proprietary/services/policyExport.tsindex 3c8949c74c..c3913accab 100644--- a/frontend/editor/src/proprietary/services/policyExport.ts+++ b/frontend/editor/src/proprietary/services/policyExport.ts@@ -12,6 +12,8 @@import { dispatchPolicyFile } from "@app/services/policyDispatch";import { loadPolicies } from "@app/services/policyStorage";+import { reportFreeTierExhausted } from "@app/services/accountLinkBlock";+import { policyCreditContext } from "@app/services/policyCreditContext";import { assertFilesNotBlocked } from "@app/services/policyFileGuard";import { loadPolicyCatalog } from "@app/services/policyCatalog";import { editorTriggerOf } from "@app/policies/runOn";@@ -106,7 +108,12 @@ async function runToCompletion(file: File,): Promise<PolicyRunResult> {const target = resolvePolicyRunTarget();- const runId = await runStoredPolicy(backendId, [file]);+ const runId = await runStoredPolicy(+ backendId,+ [file],+ undefined,+ "background",+ );for (let i = 0; i < MAX_POLLS; i++) {await delay(POLL_MS);let view;@@ -134,6 +141,9 @@ async function runToCompletion(return { file: enforced, runId, target, outputs: view.outputs ?? [] };}if (view.status === "FAILED" || view.status === "CANCELLED") {+ if (view.errorCode === "FREE_TIER_EXHAUSTED") {+ reportFreeTierExhausted(policyCreditContext(backendId));+ }throw new Error(view.error || `policy run ${view.status.toLowerCase()}`);}if (view.status === "WAITING_FOR_INPUT") {diff --git a/frontend/editor/src/prototypes/components/AccountLinkNotice.tsx b/frontend/editor/src/prototypes/components/AccountLinkNotice.tsxnew file mode 100644index 0000000000..6a653f968c--- /dev/null+++ b/frontend/editor/src/prototypes/components/AccountLinkNotice.tsx@@ -0,0 +1,4 @@+/** The prototypes sandbox has no portal or account-link flow. */+export function AccountLinkNotice() {+ return null;+}