#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
Fix Create/Edit Pipeline button going to a blank page (#7926)
James Brunton86be4676099a
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 6eea40aec6..40cb0d47fc 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -7168,6 +7168,11 @@ going = "Taking you to stirling.com"reauthLede = "Your Stirling session expired. Signing in again keeps usage and billing visible. This server stays connected either way."title = "Connecting"+[portal.accountLink.gate]+error = "Couldn't check the Stirling account connection"+loading = "Checking the Stirling account connection..."+retry = "Try again"+[portal.accountLink.instances]active = "Active"revoke = "Revoke"diff --git a/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsx b/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsxindex e5bd45eff9..7fbc2348ff 100644--- a/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsx+++ b/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsx@@ -1,4 +1,6 @@import { useEffect, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button, Spinner } from "@app/ui";import { Navigate } from "react-router-dom";import { useConnectGate } from "@portal/hooks/useConnectGate";@@ -13,14 +15,25 @@ interface Props {* remember each time someone adds a link.*/export function ConnectGuardedRoute({ children, fallback }: Props) {- const { gated, loading, connect } = useConnectGate();+ const { t } = useTranslation();+ const { gated, loading, error, retry, connect } = useConnectGate();useEffect(() => {if (gated) connect();}, [gated, connect]);- // Unknown is not gated: bouncing first would throw a linked admin off a page they are entitled to.- if (loading) return null;+ if (error)+ return (+ <Banner+ tone="danger"+ title={t("portal.accountLink.gate.error")}+ description={error}+ action={+ <Button onClick={retry}>{t("portal.accountLink.gate.retry")}</Button>+ }+ />+ );+ if (loading) return <Spinner label={t("portal.accountLink.gate.loading")} />;if (gated) return <Navigate to={fallback} replace />;return <>{children}</>;}diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsxindex f20f777280..04992e30df 100644--- a/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx+++ b/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx@@ -9,6 +9,7 @@ const base: UseAccountLink = {status: { linked: false, name: null },phase: "idle",error: null,+ statusError: null,unlink: async () => {},refresh: async () => {},diff --git a/frontend/editor/src/portal/contexts/AccountLinkContext.tsx b/frontend/editor/src/portal/contexts/AccountLinkContext.tsxindex 0ab5fc4da7..87ec68aa4d 100644--- a/frontend/editor/src/portal/contexts/AccountLinkContext.tsx+++ b/frontend/editor/src/portal/contexts/AccountLinkContext.tsx@@ -27,3 +27,8 @@ export function useAccountLinkContext(): UseAccountLink {}return v;}++/** No status reader on SaaS, where instance linking does not apply. */+export function useAccountLinkOptional(): UseAccountLink | null {+ return useContext(AccountLinkContext);+}diff --git a/frontend/editor/src/portal/hooks/connectGateStatus.test.tsx b/frontend/editor/src/portal/hooks/connectGateStatus.test.tsxindex 299748fea4..c3f5bc9e05 100644--- a/frontend/editor/src/portal/hooks/connectGateStatus.test.tsx+++ b/frontend/editor/src/portal/hooks/connectGateStatus.test.tsx@@ -1,13 +1,22 @@-import { describe, expect, it, vi } from "vitest";-import { render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { MemoryRouter, Route, Routes } from "react-router-dom";+import { ConnectGuardedRoute } from "@portal/components/account-link/ConnectGuardedRoute";import { PortalTestProviders } from "@portal/test/TestQueryProvider";import { LinkProvider } from "@portal/contexts/LinkContext";import { UIProvider } from "@portal/contexts/UIContext";/** Over the real provider stack: pins apart not-yet-known, never-knowable and truly unlinked. */-const { json, fetchStatus } = vi.hoisted(() => ({+const { json, fetchStatus, guardedAction } = vi.hoisted(() => ({json: vi.fn(),fetchStatus: vi.fn(),+ guardedAction: vi.fn(),}));vi.mock("@portal/api/http", () => ({apiClient: { local: { json } },@@ -25,19 +34,38 @@ import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";import { useConnectGate } from "@portal/hooks/useConnectGate";function Probe() {- const { gated, available } = useConnectGate();+ const { gated, available, guard } = useConnectGate();return (- <span data-testid="g">{`${available ? "avail" : "unavail"}:${gated ? "gated" : "open"}`}</span>+ <>+ <span data-testid="g">{`${available ? "avail" : "unavail"}:${gated ? "gated" : "open"}`}</span>+ <button onClick={guard(guardedAction)}>Guarded action</button>+ </>);}-const renderStack = () =>+const renderStack = (path = "/processor/pipelines/new") =>render(<PortalTestProviders><LinkProvider initialState="unlinked" statusKnown={false}><UIProvider><AccountLinkProvider>- <Probe />+ <MemoryRouter initialEntries={[path]}>+ <Probe />+ <Routes>+ <Route+ path="/processor/pipelines/:id"+ element={+ <ConnectGuardedRoute fallback="/processor/pipelines">+ <h1>Pipeline builder</h1>+ </ConnectGuardedRoute>+ }+ />+ <Route+ path="/processor/pipelines"+ element={<h1>Pipelines list</h1>}+ />+ </Routes>+ </MemoryRouter></AccountLinkProvider></UIProvider></LinkProvider>@@ -48,40 +76,117 @@ const state = () => screen.getByTestId("g").textContent;const configSaysAvailable = () =>json.mockResolvedValue({ accountLinkAvailable: true });+beforeEach(() => {+ vi.clearAllMocks();+ json.mockReset();+ fetchStatus.mockReset();+});+afterEach(() => {+ sessionStorage.clear();+ window.history.replaceState({}, "", "/");+});++const builder = () =>+ screen.queryByRole("heading", { name: "Pipeline builder" });+const assertActionBlocked = () => {+ fireEvent.click(screen.getByRole("button", { name: "Guarded action" }));+ expect(guardedAction).not.toHaveBeenCalled();+};+const retry = () =>+ fireEvent.click(+ screen.getByRole("button", { name: "portal.accountLink.gate.retry" }),+ );+describe("connect gate and the link status", () => {- it("stays open while the status is still in flight", async () => {+ it("waits visibly for status without opening the builder or guarded actions", async () => {configSaysAvailable();let resolve!: (v: unknown) => void;fetchStatus.mockReturnValue(new Promise((r) => (resolve = r)));renderStack();- await waitFor(() => expect(state()).toContain("avail"));- expect(state()).toContain("open");- resolve({ linked: true, name: "acme" });+ await waitFor(() => expect(state()).toBe("avail:open"));+ expect(+ screen.getByRole("status", { name: "portal.accountLink.gate.loading" }),+ ).toBeInTheDocument();+ expect(builder()).not.toBeInTheDocument();+ assertActionBlocked();+ await act(async () => resolve({ linked: true, name: "acme" }));+ expect(builder()).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Guarded action" }));+ expect(guardedAction).toHaveBeenCalledTimes(1);});- it("stays open once a linked status arrives", async () => {- configSaysAvailable();- fetchStatus.mockResolvedValue({ linked: true, name: "acme" });- renderStack();- await waitFor(() => expect(state()).toContain("avail"));- expect(state()).toContain("open");- });+ it.each([true, false])(+ "retries a failed status check and respects linked=%s",+ async (linked) => {+ configSaysAvailable();+ fetchStatus+ .mockRejectedValueOnce(new Error("Status unavailable"))+ .mockResolvedValue({ linked, name: linked ? "acme" : null });+ renderStack();+ await screen.findByText("portal.accountLink.gate.error");+ expect(builder()).not.toBeInTheDocument();+ assertActionBlocked();+ retry();+ await screen.findByRole("heading", {+ name: linked ? "Pipeline builder" : "Pipelines list",+ });+ expect(fetchStatus).toHaveBeenCalledTimes(2);+ expect(+ screen.queryByText("portal.accountLink.gate.error"),+ ).not.toBeInTheDocument();+ },+ );- it("stays open when the status call fails, rather than assuming unlinked", async () => {+ it("does not honor the old dev bypass URL or stored flag for an unlinked instance", async () => {+ window.history.replaceState({}, "", "/processor?bypassConnect=true");+ sessionStorage.setItem("accountLink::dev-bypass", "true");configSaysAvailable();- fetchStatus.mockRejectedValue(- new Error("401 once the admin session lapsed"),- );+ fetchStatus.mockResolvedValue({ linked: false, name: null });renderStack();- await waitFor(() => expect(state()).toContain("avail"));- await new Promise((r) => setTimeout(r, 10));- expect(state()).toContain("open");+ await screen.findByRole("heading", { name: "Pipelines list" });+ expect(builder()).not.toBeInTheDocument();+ assertActionBlocked();});- it("still gates once the status says the instance really is unlinked", async () => {- configSaysAvailable();- fetchStatus.mockResolvedValue({ linked: false, name: null });+ it("blocks when app configuration fails and retries without assuming linking is disabled", async () => {+ json+ .mockRejectedValueOnce(new Error("Configuration unavailable"))+ .mockResolvedValue({ accountLinkAvailable: false });+ fetchStatus.mockRejectedValue(new Error("No status endpoint"));renderStack();- await waitFor(() => expect(state()).toBe("avail:gated"));+ await screen.findByText("portal.accountLink.gate.error");+ expect(builder()).not.toBeInTheDocument();+ assertActionBlocked();+ retry();+ await screen.findByRole("heading", { name: "Pipeline builder" });+ expect(json).toHaveBeenCalledTimes(2);});});++describe("pipeline routes with unknown link status", () => {+ it.each([+ ["/processor/pipelines/new", false],+ ["/processor/pipelines/plc-1", false],+ ["/processor/pipelines/new", true],+ ["/processor/pipelines/plc-1", true],+ ])(+ "requires status for %s only when linking is available (%s)",+ async (path, accountLinkAvailable) => {+ json.mockResolvedValue({ accountLinkAvailable });+ fetchStatus.mockRejectedValue(new Error("Link status unavailable"));+ renderStack(path);+ if (accountLinkAvailable) {+ await screen.findByText("portal.accountLink.gate.error");+ expect(builder()).not.toBeInTheDocument();+ } else {+ await screen.findByRole("heading", { name: "Pipeline builder" });+ expect(+ screen.queryByText("portal.accountLink.gate.error"),+ ).not.toBeInTheDocument();+ }+ expect(+ screen.queryByRole("heading", { name: "Pipelines list" }),+ ).not.toBeInTheDocument();+ },+ );+});diff --git a/frontend/editor/src/portal/hooks/useAccountLink.ts b/frontend/editor/src/portal/hooks/useAccountLink.tsindex 0ff6584604..781c23ef34 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 } from "react";+import { errorMessage } from "@portal/api/http";import { isSaasSupabaseConfigured } from "@portal/auth/saasSupabase";import { fetchStatus, unlinkInstance, type LinkStatus } from "@portal/api/link";import { useApplyLinkFacts, useLink } from "@portal/contexts/LinkContext";@@ -12,6 +13,8 @@ export interface UseAccountLink {loginConfigured: boolean;/** Linked / Not-linked status for this instance; null while first loading. */status: LinkStatus | null;+ /** Failure to read status, separate from an unlink failure. */+ statusError: string | null;phase: LinkPhase;error: string | null;/** Unlink this instance. */@@ -24,10 +27,12 @@ export function useAccountLink(): UseAccountLink {const applyLinkFacts = useApplyLinkFacts();const { markStatusKnown } = useLink();const [status, setStatus] = useState<LinkStatus | null>(null);+ const [statusError, setStatusError] = useState<string | null>(null);const [phase, setPhase] = useState<LinkPhase>("idle");const [error, setError] = useState<string | null>(null);const refresh = useCallback(async () => {+ setStatusError(null);try {const s = await fetchStatus();setStatus(s);@@ -35,8 +40,8 @@ export function useAccountLink(): UseAccountLink {if (s.linked) applyLinkFacts(true, false);// Success only: marking this in the catch would read "could not ask" as "not linked".markStatusKnown();- } catch {- setStatus({ linked: false, name: null });+ } catch (e) {+ setStatusError(errorMessage(e));}}, [applyLinkFacts, markStatusKnown]);@@ -61,6 +66,7 @@ export function useAccountLink(): UseAccountLink {return {loginConfigured: isSaasSupabaseConfigured,status,+ statusError,phase,error,unlink,diff --git a/frontend/editor/src/portal/hooks/useConnectGate.test.tsx b/frontend/editor/src/portal/hooks/useConnectGate.test.tsxindex 00cd34d643..c9d3731f17 100644--- a/frontend/editor/src/portal/hooks/useConnectGate.test.tsx+++ b/frontend/editor/src/portal/hooks/useConnectGate.test.tsx@@ -44,7 +44,22 @@ const settled = async (expected: string) =>waitFor(() => expect(screen.getByTestId("state").textContent).toBe(expected));describe("useConnectGate", () => {- beforeEach(() => json.mockReset());+ beforeEach(() => {+ json.mockReset();+ });++ it("does not require an instance status or configuration check on SaaS", async () => {+ json.mockRejectedValue(new Error("No local instance"));+ render(+ <PortalTestProviders>+ <UIProvider>+ <Probe />+ </UIProvider>+ </PortalTestProviders>,+ );+ await settled("unavailable:open");+ expect(json).not.toHaveBeenCalled();+ });it("gates an unlinked instance that can link", async () => {json.mockResolvedValue({ accountLinkAvailable: true });diff --git a/frontend/editor/src/portal/hooks/useConnectGate.ts b/frontend/editor/src/portal/hooks/useConnectGate.tsindex f0c87d6689..486488f91f 100644--- a/frontend/editor/src/portal/hooks/useConnectGate.ts+++ b/frontend/editor/src/portal/hooks/useConnectGate.ts@@ -1,10 +1,10 @@import { useCallback } from "react";import { useQuery } from "@tanstack/react-query";-import { apiClient } from "@portal/api/http";+import { apiClient, errorMessage } from "@portal/api/http";import { qk } from "@portal/queries/keys";import { useLinkOptional } from "@portal/contexts/LinkContext";import { useUI } from "@portal/contexts/UIContext";-import { useDevConnectBypass } from "@portal/hooks/useDevConnectBypass";+import { useAccountLinkOptional } from "@portal/contexts/AccountLinkContext";interface AppConfigShape {accountLinkAvailable?: boolean;@@ -13,12 +13,15 @@ interface AppConfigShape {interface ConnectGate {/** Can link but has not, so gated features must ask first. */gated: boolean;- /** Capability still unknown; hold the decision rather than flash a gate. */+ /** A required capability or link-status check has not settled yet. */loading: boolean;+ /** A required check failed; guarded actions remain blocked until it succeeds. */+ error: string | null;+ retry: () => void;/** Whether linking is possible here at all, i.e. the feature flag is on. */available: boolean;connect: () => void;- /** Wraps a create or edit handler so the click asks for a connection instead. */+ /** Blocks create/edit while checks are unresolved; asks to connect when confirmed unlinked. */guard: <A extends unknown[]>(action: (...args: A) => void,) => (...args: A) => void;@@ -33,33 +36,46 @@ export function useConnectGate(): ConnectGate {// Optional: the SaaS portal mounts no LinkProvider, and no provider means nothing to gate.const link = useLinkOptional();const { openLinkModal } = useUI();- const devBypass = useDevConnectBypass();+ const accountLink = useAccountLinkOptional();const query = useQuery({+ enabled: link != null,queryKey: qk.appConfig(),queryFn: () =>apiClient.local.json<AppConfigShape>("/api/v1/config/app-config"),});const available = Boolean(query.data?.accountLinkAvailable) && link != null;- // A status call that never succeeds leaves the gate open rather than blocking on an unknown.const statusKnown = link?.statusKnown ?? false;- const loading = query.isPending || (link != null && !statusKnown);- const gated = available && statusKnown && !link?.isLinked && !devBypass;+ const error =+ link != null && query.isError+ ? errorMessage(query.error)+ : available && !statusKnown+ ? (accountLink?.statusError ?? null)+ : null;+ // A disabled capability has no status endpoint. Only wait for link status when linking applies.+ const loading =+ link != null && (query.isPending || (available && !statusKnown && !error));+ const gated = !error && available && statusKnown && !link?.isLinked;+ const retry = () => {+ if (query.isError) void query.refetch();+ else void accountLink?.refresh();+ };const connect = useCallback(() => openLinkModal(), [openLinkModal]);const guard = useCallback(<A extends unknown[]>(action: (...args: A) => void) =>(...args: A) => {+ if (loading || error) return;if (gated) {openLinkModal();return;}action(...args);},- [gated, openLinkModal],+ [gated, loading, error, openLinkModal],);- return { gated, loading, available, connect, guard };+ return { gated, loading, error, retry, available, connect, guard };}diff --git a/frontend/editor/src/portal/hooks/useDevConnectBypass.test.tsx b/frontend/editor/src/portal/hooks/useDevConnectBypass.test.tsxdeleted file mode 100644index f4d28f5515..0000000000--- a/frontend/editor/src/portal/hooks/useDevConnectBypass.test.tsx+++ /dev/null@@ -1,53 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, render, screen } from "@testing-library/react";--/**- * The gate is the only thing making these features need a link, so a switch a customer could reach- * would hand them over. The last test is the one that matters: with DEV folded off, the parameter- * does nothing at all.- */-import { useDevConnectBypass } from "@portal/hooks/useDevConnectBypass";--function Probe() {- return <span data-testid="bypass">{String(useDevConnectBypass())}</span>;-}--/** Mounts fresh at the given URL, so a second call models a later visit rather than a re-render. */-const at = (search: string) => {- cleanup();- window.history.replaceState({}, "", `/processor${search}`);- render(<Probe />);- return screen.getByTestId("bypass").textContent;-};--describe("useDevConnectBypass", () => {- beforeEach(() => sessionStorage.clear());- afterEach(() => {- vi.unstubAllEnvs();- window.history.replaceState({}, "", "/");- });-- it("is off by default, so dev still sees what customers see", () => {- expect(at("")).toBe("false");- });-- it("turns on with the parameter", () => {- expect(at("?bypassConnect=true")).toBe("true");- });-- it("survives the navigation the gate itself performs", () => {- at("?bypassConnect=true");- expect(at("")).toBe("true");- });-- it("ignores any other value", () => {- expect(at("?bypassConnect=1")).toBe("false");- });-- it("does nothing in a build, which is what ships to customers", () => {- vi.stubEnv("DEV", false);- expect(at("?bypassConnect=true")).toBe("false");- // And nothing was left behind for a later dev session to pick up.- expect(sessionStorage.getItem("accountLink::dev-bypass")).toBeNull();- });-});diff --git a/frontend/editor/src/portal/hooks/useDevConnectBypass.ts b/frontend/editor/src/portal/hooks/useDevConnectBypass.tsdeleted file mode 100644index b201ac7d80..0000000000--- a/frontend/editor/src/portal/hooks/useDevConnectBypass.ts+++ /dev/null@@ -1,39 +0,0 @@-import { useEffect, useState } from "react";--const PARAM = "bypassConnect";-const SESSION_KEY = "accountLink::dev-bypass";--function stored(): boolean {- try {- return sessionStorage.getItem(SESSION_KEY) === "true";- } catch {- return false;- }-}--/**- * Dev-only escape from the connect gate, fenced behind {@code import.meta.env.DEV} so Vite folds- * the branch away entirely: in a shipped build there is no param and no key that does anything.- * It cannot be a setting — the gate is the only thing making these features need a link, so any- * switch a customer could reach would hand them over.- */-export function useDevConnectBypass(): boolean {- // Session-scoped so it survives the navigation the gate itself performs.- const [bypassed, setBypassed] = useState(- () => import.meta.env.DEV && stored(),- );-- useEffect(() => {- if (!import.meta.env.DEV) return;- const params = new URLSearchParams(window.location.search);- if (params.get(PARAM) !== "true") return;- try {- sessionStorage.setItem(SESSION_KEY, "true");- } catch {- // Still bypassed for this render.- }- setBypassed(true);- }, []);-- return bypassed;-}diff --git a/frontend/editor/src/portal/views/Pipelines.tsx b/frontend/editor/src/portal/views/Pipelines.tsxindex c49e3c1933..1cd4e04c24 100644--- a/frontend/editor/src/portal/views/Pipelines.tsx+++ b/frontend/editor/src/portal/views/Pipelines.tsx@@ -46,7 +46,7 @@ export function Pipelines() {const queryClient = useQueryClient();const [searchParams, setSearchParams] = useSearchParams();// Building and editing a pipeline both need a linked account, so both ask for one first (#7581).- const { guard } = useConnectGate();+ const { guard, error: connectError, retry: retryConnect } = useConnectGate();const listState = usePipelines();const { data: overview } = listState;@@ -263,6 +263,19 @@ export function Pipelines() {</Button></header>+ {connectError && (+ <Banner+ tone="danger"+ title={t("portal.accountLink.gate.error")}+ description={connectError}+ action={+ <Button onClick={retryConnect}>+ {t("portal.accountLink.gate.retry")}+ </Button>+ }+ />+ )}+{pageError && <Banner tone="danger" description={pageError} />}{permissionsError && (