Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Maintain state in QAB when switching between views (#7998)

James Bruntone231f3316ee0
diff --git a/frontend/editor/src/core/components/docs/DocsPage.tsx b/frontend/editor/src/core/components/docs/DocsPage.tsx
index b68659fb9d..a80f28dba2 100644
--- a/frontend/editor/src/core/components/docs/DocsPage.tsx
+++ b/frontend/editor/src/core/components/docs/DocsPage.tsx
@@ -1,7 +1,6 @@
import { Suspense, lazy } from "react";
import { LoadingFallback } from "@app/components/shared/LoadingFallback";
import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
-import { useOtherAppSwitch } from "@app/hooks/useOtherAppSwitch";
import "@app/components/docs/DocsPage.css";
// Its own chunk: the generated docs manifest is bundled JSON.
@@ -17,12 +16,9 @@ const DeveloperDocs = lazy(async () => {
* likely to need them.
*/
export default function DocsPage() {
- // The rail sits outside every app, so each page tells it what only the
- // signed-in session knows. Null in builds with no processor to switch to.
- const otherApp = useOtherAppSwitch();
return (
<div className="docs-page">
- <QuickNavHostBridge portalAccess={Boolean(otherApp)} />
+ <QuickNavHostBridge />
<Suspense fallback={<LoadingFallback />}>
<DeveloperDocs />
</Suspense>
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx
new file mode 100644
index 0000000000..216ca271f6
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx
@@ -0,0 +1,161 @@
+import { act, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { AppConfigProvider } from "@app/contexts/AppConfigContext";
+import {
+ QuickNavHostProvider,
+ useQuickNavHost,
+} from "@app/contexts/QuickNavHostContext";
+import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
+import { QuickNavRailAccount } from "@app/components/shared/quickNav/QuickNavRailAccount";
+
+const { auth, picture, getAccountData } = vi.hoisted(() => ({
+ auth: {
+ displayName: "Ada" as string | null,
+ loading: false,
+ isAnonymous: false,
+ },
+ picture: { url: "/ada.png" as string | null, loading: false },
+ getAccountData: vi.fn(),
+}));
+
+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => auth }));
+vi.mock("@app/hooks/useProfilePictureUrl", () => ({
+ useProfilePictureUrl: () => picture.url,
+ useProfilePictureLoading: () => picture.loading,
+}));
+vi.mock("@app/services/accountService", () => ({
+ accountService: { getAccountData },
+}));
+vi.mock("@app/services/thumbnailGenerationService", () => ({
+ thumbnailGenerationService: { generateThumbnails: vi.fn(async () => []) },
+}));
+
+function Account() {
+ const host = useQuickNavHost();
+ return (
+ <QuickNavRailAccount identity={host?.identity ?? null} onOpen={() => {}} />
+ );
+}
+
+function setup(enableLogin = false) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const markup = (view: string | null) => (
+ <MemoryRouter>
+ <QueryClientProvider client={client}>
+ <QuickNavHostProvider>
+ <Account />
+ {view && (
+ <AppConfigProvider
+ key={view}
+ autoFetch={false}
+ bootstrapMode="non-blocking"
+ initialConfig={{ enableLogin }}
+ >
+ <QuickNavHostBridge />
+ </AppConfigProvider>
+ )}
+ </QuickNavHostProvider>
+ </QueryClientProvider>
+ </MemoryRouter>
+ );
+ const view = render(markup("editor"));
+ return (name: string | null) => view.rerender(markup(name));
+}
+
+describe("quick-nav identity during view switches", () => {
+ beforeEach(() => {
+ auth.displayName = "Ada";
+ auth.loading = false;
+ picture.url = "/ada.png";
+ picture.loading = false;
+ getAccountData.mockReset();
+ });
+
+ it("keeps the name and avatar through unmount, session loading and picture loading", () => {
+ const switchView = setup();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/ada.png");
+
+ switchView(null);
+ expect(screen.getByRole("button", { name: /Ada/ })).toBeInTheDocument();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/ada.png");
+
+ auth.displayName = null;
+ auth.loading = true;
+ picture.url = null;
+ picture.loading = true;
+ switchView("processor");
+ expect(screen.getByRole("button", { name: /Ada/ })).toBeInTheDocument();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/ada.png");
+
+ auth.displayName = "Grace";
+ auth.loading = false;
+ switchView("processor");
+ expect(screen.getByRole("button", { name: /Ada/ })).toBeInTheDocument();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/ada.png");
+
+ picture.url = "/grace.png";
+ picture.loading = false;
+ switchView("processor");
+ expect(screen.getByRole("button", { name: /Grace/ })).toBeInTheDocument();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/grace.png");
+
+ auth.displayName = null;
+ picture.url = null;
+ auth.loading = true;
+ switchView("editor");
+ expect(screen.getByRole("button", { name: /Grace/ })).toBeInTheDocument();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/grace.png");
+
+ auth.loading = false;
+ switchView("editor");
+ expect(
+ screen.getByRole("button", { name: /auth.displayName.user/ }),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("img")).not.toBeInTheDocument();
+ });
+
+ it("waits for the account endpoint before replacing an identity without an auth name", async () => {
+ let resolveAccount = (_value: { username: string }) => {};
+ getAccountData.mockReturnValue(
+ new Promise<{ username: string }>((resolve) => {
+ resolveAccount = resolve;
+ }),
+ );
+ const switchView = setup(true);
+
+ auth.displayName = null;
+ picture.url = null;
+ switchView("processor");
+ expect(screen.getByRole("button", { name: /Ada/ })).toBeInTheDocument();
+ expect(screen.getByRole("img")).toHaveAttribute("src", "/ada.png");
+
+ await act(async () => resolveAccount({ username: "Grace" }));
+ expect(screen.getByRole("button", { name: /Grace/ })).toBeInTheDocument();
+ expect(screen.queryByRole("img")).not.toBeInTheDocument();
+ });
+
+ it("replaces the cached identity when the account lookup rejects after sign-out", async () => {
+ let rejectAccount = (_reason: Error) => {};
+ getAccountData.mockReturnValue(
+ new Promise<never>((_resolve, reject) => {
+ rejectAccount = reject;
+ }),
+ );
+ const switchView = setup(true);
+
+ auth.displayName = null;
+ picture.url = null;
+ switchView("processor");
+ expect(screen.getByRole("button", { name: /Ada/ })).toBeInTheDocument();
+
+ await act(async () => rejectAccount(new Error("Signed out")));
+ expect(
+ screen.getByRole("button", { name: /auth.displayName.user/ }),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("img")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx
index a5cd864c56..470ea3b722 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx
@@ -31,7 +31,7 @@ function renderInProcessorShape() {
initialConfig={{ enableEasterEggs: true }}
>
<QuickNavHostProvider>
- <QuickNavHostBridge portalAccess />
+ <QuickNavHostBridge />
</QuickNavHostProvider>
</AppConfigProvider>
</QueryClientProvider>
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx
new file mode 100644
index 0000000000..f49018b557
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx
@@ -0,0 +1,215 @@
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { AppConfigProvider } from "@app/contexts/AppConfigContext";
+import {
+ QuickNavHostProvider,
+ useQuickNavHost,
+} from "@app/contexts/QuickNavHostContext";
+import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
+import { fetchSigningSessions, type SigningSessions } from "@app/api/signing";
+import { alert } from "@app/components/toast";
+import { expectConsole } from "@app/tests/failOnConsole";
+
+const { auth, access } = vi.hoisted(() => ({
+ auth: { user: { id: "ada" } as { id: string } | null, loading: false },
+ access: { granted: true, settled: true },
+}));
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({
+ ...auth,
+ displayName: auth.user?.id ?? null,
+ isAnonymous: false,
+ }),
+}));
+vi.mock("@app/hooks/usePortalAccess", () => ({
+ usePortalAccessState: () => access,
+}));
+vi.mock("@app/api/signing", () => ({ fetchSigningSessions: vi.fn() }));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+vi.mock("@app/components/shared/quickNav/useQuickNavToolReasons", () => ({
+ useQuickNavToolReasons: () => null,
+}));
+vi.mock("@app/services/thumbnailGenerationService", () => ({
+ thumbnailGenerationService: { generateThumbnails: vi.fn(async () => []) },
+}));
+
+const mockFetch = vi.mocked(fetchSigningSessions);
+const EMPTY: SigningSessions = { signRequests: [], mySessions: [] };
+const UNREAD: SigningSessions = {
+ signRequests: [],
+ mySessions: [
+ {
+ sessionId: "session-1",
+ documentName: "Document.pdf",
+ createdAt: "2026-09-14T12:00:00Z",
+ participantCount: 2,
+ signedCount: 1,
+ finalized: false,
+ },
+ ],
+};
+
+function RailState() {
+ const host = useQuickNavHost();
+ return (
+ <>
+ <output data-testid="access">{String(host?.portalAccess)}</output>
+ <output data-testid="badge">{host?.signingBadge}</output>
+ </>
+ );
+}
+
+function setup() {
+ const clients = {
+ editor: new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ processor: new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ };
+ const markup = (
+ app: keyof typeof clients | null,
+ configReady = true,
+ signingEnabled = true,
+ ) => (
+ <MemoryRouter>
+ <QuickNavHostProvider>
+ <RailState />
+ {app && (
+ <QueryClientProvider key={app} client={clients[app]}>
+ <AppConfigProvider
+ autoFetch={false}
+ bootstrapMode="non-blocking"
+ initialConfig={
+ configReady
+ ? { storageGroupSigningEnabled: signingEnabled }
+ : null
+ }
+ >
+ <QuickNavHostBridge />
+ </AppConfigProvider>
+ </QueryClientProvider>
+ )}
+ </QuickNavHostProvider>
+ </MemoryRouter>
+ );
+ const view = render(markup("editor"));
+ return (
+ app: keyof typeof clients | null,
+ configReady = true,
+ signingEnabled = true,
+ ) => view.rerender(markup(app, configReady, signingEnabled));
+}
+
+function expectRail(granted: boolean, count: number) {
+ expect(screen.getByTestId("access")).toHaveTextContent(String(granted));
+ expect(screen.getByTestId("badge")).toHaveTextContent(String(count));
+}
+
+describe("quick-nav account data during view switches", () => {
+ beforeEach(() => {
+ auth.user = { id: "ada" };
+ auth.loading = false;
+ access.granted = true;
+ access.settled = true;
+ localStorage.clear();
+ mockFetch.mockReset();
+ vi.mocked(alert).mockClear();
+ mockFetch.mockResolvedValue(UNREAD);
+ });
+
+ it("retains access and the count until each incoming lookup settles", async () => {
+ const switchView = setup();
+ await waitFor(() => expectRail(true, 1));
+ switchView(null);
+ expectRail(true, 1);
+
+ let resolveSessions = (_value: SigningSessions) => {};
+ mockFetch.mockReturnValue(
+ new Promise((resolve) => {
+ resolveSessions = resolve;
+ }),
+ );
+ auth.user = null;
+ auth.loading = true;
+ access.granted = false;
+ access.settled = false;
+ switchView("processor", false);
+ expectRail(true, 1);
+
+ auth.user = { id: "ada" };
+ auth.loading = false;
+ switchView("processor", false);
+ expectRail(true, 1);
+
+ switchView("processor");
+ expectRail(true, 1);
+ access.settled = true;
+ switchView("processor");
+ expectRail(false, 1);
+
+ await act(async () => resolveSessions(EMPTY));
+ await waitFor(() => expectRail(false, 0));
+
+ mockFetch.mockReturnValue(
+ new Promise((resolve) => {
+ resolveSessions = resolve;
+ }),
+ );
+ access.settled = false;
+ switchView("editor", false);
+ expectRail(false, 0);
+ switchView("editor");
+ expectRail(false, 0);
+ await act(async () => resolveSessions(UNREAD));
+ await waitFor(() => expectRail(false, 1));
+ switchView("editor", true, false);
+ expectRail(false, 0);
+ });
+
+ it("keeps the previous count when the incoming signing request fails", async () => {
+ const switchView = setup();
+ await waitFor(() => expectRail(true, 1));
+ expectConsole.error(/Failed to fetch signing data/);
+ let rejectSessions = (_error: Error) => {};
+ mockFetch.mockReturnValue(
+ new Promise((_resolve, reject) => {
+ rejectSessions = reject;
+ }),
+ );
+ switchView("processor");
+ await act(async () => rejectSessions(new Error("Network unavailable")));
+ await waitFor(() => expect(alert).toHaveBeenCalled());
+ expectRail(true, 1);
+ });
+
+ it("drops the previous account's values during an account change and sign-out", async () => {
+ const switchView = setup();
+ await waitFor(() => expectRail(true, 1));
+ let resolveSessions = (_value: SigningSessions) => {};
+ mockFetch.mockReturnValue(
+ new Promise((resolve) => {
+ resolveSessions = resolve;
+ }),
+ );
+
+ auth.user = { id: "grace" };
+ access.settled = false;
+ switchView("editor");
+ expectRail(false, 0);
+
+ access.settled = true;
+ switchView("editor");
+ await act(async () => resolveSessions(UNREAD));
+ await waitFor(() => expectRail(true, 1));
+
+ mockFetch.mockResolvedValue(EMPTY);
+ auth.user = null;
+ access.granted = false;
+ access.settled = true;
+ switchView("editor");
+ expectRail(false, 0);
+ });
+});
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
index 424febf85b..32e1f79198 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
@@ -1,5 +1,4 @@
import { useCallback, useMemo, useState } from "react";
-import { useAccountIdentity } from "@app/hooks/useAccountIdentity";
import {
NotificationPanel,
NOTIFICATIONS_PANEL_ID,
@@ -7,17 +6,16 @@ import {
import { useNotificationActions } from "@app/components/notifications/notificationActions";
import { useNotificationPasswordPrompt } from "@app/components/notifications/useNotificationPasswordPrompt";
import { useQuickNavToolReasons } from "@app/components/shared/quickNav/useQuickNavToolReasons";
+import { useSyncQuickNavAccount } from "@app/components/shared/quickNav/useSyncQuickNavAccount";
import { useBrandFlourish } from "@app/components/easterEgg/useBrandFlourish";
import { useNotificationsAvailable } from "@app/components/notifications/useNotificationsAvailable";
-import { useSigningBadgeCount } from "@app/hooks/signing/useSigningBadgeCount";
import {
- useRegisterQuickNavHost,
+ useRegisterQuickNavView,
type QuickNavToolReasons,
} from "@app/contexts/QuickNavHostContext";
import type { ToolId } from "@app/types/toolId";
export interface QuickNavHostBridgeProps {
- portalAccess?: boolean;
readerMode?: boolean;
fileLibrary?: boolean;
onSetReaderMode?: (on: boolean) => void;
@@ -32,7 +30,6 @@ export interface QuickNavHostBridgeProps {
/** Registers with the rail what only the app can see, and owns the notifications panel. */
export function QuickNavHostBridge({
- portalAccess = false,
readerMode = false,
fileLibrary = false,
onSetReaderMode,
@@ -43,8 +40,7 @@ export function QuickNavHostBridge({
onGoToDefaultState,
toolReasons,
}: QuickNavHostBridgeProps) {
- const { displayName, profilePictureUrl } = useAccountIdentity();
- const signingBadge = useSigningBadgeCount();
+ useSyncQuickNavAccount();
const notificationsAvailable = useNotificationsAvailable();
// Built even when closed: it carries a one-shot document pickup that would sit unclaimed.
const notificationActions = useNotificationActions();
@@ -62,11 +58,8 @@ export function QuickNavHostBridge({
const { requestPassword, promptModal } =
useNotificationPasswordPrompt(closeNotifications);
- useRegisterQuickNavHost(
+ useRegisterQuickNavView(
{
- identity: { displayName, profilePictureUrl },
- signingBadge,
- portalAccess,
readerMode,
fileLibrary,
activeTool,
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx
index 7c89fd0227..5fe7918d6f 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx
@@ -6,7 +6,7 @@ import "@app/components/shared/quickNav/QuickNavRailAccount.css";
export interface QuickNavRailAccountProps {
onOpen: () => void;
- /** Null between apps; the disc still renders, so the bar keeps its shape. */
+ /** Null until an identity is first resolved, or when explicitly cleared. */
identity: QuickNavIdentity | null;
/** Drawn as the current destination while the settings page is open. */
active?: boolean;
diff --git a/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts b/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts
new file mode 100644
index 0000000000..8b3169561d
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts
@@ -0,0 +1,43 @@
+import { useEffect } from "react";
+import { useAuth } from "@app/auth/UseSession";
+import { useQuickNavHost } from "@app/contexts/QuickNavHostContext";
+import { useAccountIdentity } from "@app/hooks/useAccountIdentity";
+import { usePortalAccessState } from "@app/hooks/usePortalAccess";
+import { useSigningBadgeState } from "@app/hooks/signing/useSigningBadgeCount";
+
+/** Publishes resolved account fields from the mounted view into the root cache. */
+export function useSyncQuickNavAccount(): void {
+ const updateAccount = useQuickNavHost()?.updateAccount;
+ const { user, loading: authLoading } = useAuth();
+ const {
+ displayName,
+ profilePictureUrl,
+ loading: identityLoading,
+ } = useAccountIdentity();
+ const { granted, settled: accessSettled } = usePortalAccessState();
+ const { count, settled: signingSettled } = useSigningBadgeState();
+ const accountId = user?.id ?? null;
+
+ useEffect(() => {
+ if (authLoading) return;
+ updateAccount?.({
+ accountId,
+ identity: identityLoading
+ ? undefined
+ : { displayName, profilePictureUrl },
+ signingBadge: signingSettled ? count : undefined,
+ portalAccess: accessSettled ? granted : undefined,
+ });
+ }, [
+ updateAccount,
+ accountId,
+ authLoading,
+ identityLoading,
+ displayName,
+ profilePictureUrl,
+ signingSettled,
+ count,
+ accessSettled,
+ granted,
+ ]);
+}
diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx
index 66b1fee411..e01c746bd0 100644
--- a/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx
+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx
@@ -1,10 +1,12 @@
import { describe, it, expect } from "vitest";
import { render, act } from "@testing-library/react";
+import { useEffect } from "react";
import {
QuickNavHostProvider,
useQuickNavHost,
- useRegisterQuickNavHost,
+ useRegisterQuickNavView,
useSuppressQuickNavRail,
+ type QuickNavIdentity,
} from "@app/contexts/QuickNavHostContext";
function Probe({ onRead }: { onRead: (value: unknown) => void }) {
@@ -20,15 +22,27 @@ function Probe({ onRead }: { onRead: (value: unknown) => void }) {
}
function App() {
- useRegisterQuickNavHost(
- { identity: { displayName: "Ada", profilePictureUrl: null } },
- { goToDefaultState: () => {} },
- );
+ const updateAccount = useQuickNavHost()?.updateAccount;
+ useEffect(() => {
+ updateAccount?.({
+ identity: { displayName: "Ada", profilePictureUrl: null },
+ });
+ }, [updateAccount]);
+ useRegisterQuickNavView({}, { goToDefaultState: () => {} });
return null;
}
function AppWithTool({ tool }: { tool: "automate" | null }) {
- useRegisterQuickNavHost({ activeTool: tool }, {});
+ useRegisterQuickNavView({ activeTool: tool }, {});
+ return null;
+}
+
+function AppWithIdentity({ identity }: { identity?: QuickNavIdentity | null }) {
+ const updateAccount = useQuickNavHost()?.updateAccount;
+ useEffect(() => {
+ updateAccount?.({ identity });
+ }, [updateAccount, identity]);
+ useRegisterQuickNavView({}, {});
return null;
}
@@ -74,9 +88,42 @@ describe("QuickNavHostContext", () => {
</QuickNavHostProvider>,
);
expect(after.appMounted).toBe(true);
+ expect(after.identity).toEqual({
+ displayName: "Ada",
+ profilePictureUrl: null,
+ });
expect(after.goToDefaultState).toBe(false);
});
+ it("keeps the previous identity until the incoming app publishes an answer", () => {
+ const { view } = setup();
+ let latest: Record<string, unknown> = {};
+ const renderIdentity = (identity?: QuickNavIdentity | null) => (
+ <QuickNavHostProvider>
+ <Probe
+ onRead={(value) => (latest = value as Record<string, unknown>)}
+ />
+ <AppWithIdentity identity={identity} />
+ </QuickNavHostProvider>
+ );
+
+ view.rerender(renderIdentity());
+ expect(latest.identity).toEqual({
+ displayName: "Ada",
+ profilePictureUrl: null,
+ });
+
+ const resolved = { displayName: "Grace", profilePictureUrl: "/grace.png" };
+ view.rerender(renderIdentity(resolved));
+ expect(latest.identity).toEqual(resolved);
+
+ view.rerender(renderIdentity());
+ expect(latest.identity).toEqual(resolved);
+
+ view.rerender(renderIdentity(null));
+ expect(latest.identity).toBeNull();
+ });
+
it("clears the open tool when the next app registers without one", () => {
let latest: Record<string, unknown> = {};
const view = render(
diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
index f68dc67ff1..b37f3f9b96 100644
--- a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
@@ -1,10 +1,17 @@
import type { ToolId } from "@app/types/toolId";
+import {
+ EMPTY_QUICK_NAV_ACCOUNT,
+ updateQuickNavAccount,
+ type QuickNavAccount,
+ type QuickNavAccountUpdate,
+} from "@app/contexts/quickNavAccount";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
+ useReducer,
useRef,
useState,
type ReactNode,
@@ -12,17 +19,9 @@ import {
export type QuickNavToolReasons = Partial<Record<ToolId, string>>;
-export interface QuickNavIdentity {
- displayName: string;
- profilePictureUrl: string | null;
-}
+export type { QuickNavIdentity } from "@app/contexts/quickNavAccount";
-export interface QuickNavHostData {
- /** Sticky: one app unmounts before the next one registers. */
- appMounted: boolean;
- identity: QuickNavIdentity | null;
- signingBadge: number;
- portalAccess: boolean;
+export interface QuickNavViewData {
readerMode: boolean;
/** The library is a view of the editor app, and the rail marks it as its own place. */
fileLibrary: boolean;
@@ -49,24 +48,23 @@ export interface QuickNavHostActions {
onBrandFlourish?: (originRect: DOMRect | null) => void;
}
-interface QuickNavHostValue extends QuickNavHostData {
- /** Reset on unmount, unlike the data above. */
+interface QuickNavHostValue extends QuickNavAccount, QuickNavViewData {
+ /** Sticky: one view unmounts before the next one registers. */
+ appMounted: boolean;
+ /** Screens without app chrome suppress the rail only while mounted. */
chromeless: boolean;
setChromeless: (chromeless: boolean) => void;
/** A ref, so a click reaches the app currently mounted. */
actions: React.RefObject<QuickNavHostActions>;
- setData: (data: Partial<QuickNavHostData>) => void;
+ updateAccount: (update: QuickNavAccountUpdate) => void;
+ setViewData: (data: Partial<QuickNavViewData>) => void;
setActions: (actions: QuickNavHostActions) => void;
}
const EMPTY_REASONS: QuickNavToolReasons = {};
-const EMPTY_DATA: QuickNavHostData = {
- appMounted: false,
+const EMPTY_VIEW: QuickNavViewData = {
toolReasons: EMPTY_REASONS,
- identity: null,
- signingBadge: 0,
- portalAccess: false,
readerMode: false,
fileLibrary: false,
activeTool: null,
@@ -86,24 +84,30 @@ const QuickNavHostContext = createContext<QuickNavHostValue | null>(null);
/** Outside both apps' providers, so each app registers what only it knows. */
export function QuickNavHostProvider({ children }: { children: ReactNode }) {
- const [data, setDataState] = useState<QuickNavHostData>(EMPTY_DATA);
+ const [account, updateAccount] = useReducer(
+ updateQuickNavAccount,
+ EMPTY_QUICK_NAV_ACCOUNT,
+ );
+ const [view, setViewState] = useState({ ...EMPTY_VIEW, appMounted: false });
const [chromeless, setChromelessState] = useState(false);
const actions = useRef<QuickNavHostActions>({});
- const setData = useCallback((next: Partial<QuickNavHostData>) => {
- setDataState((prev) => {
- const merged = { ...prev, ...next };
+ const setViewData = useCallback((next: Partial<QuickNavViewData>) => {
+ setViewState((prev) => {
+ const merged = {
+ appMounted: true,
+ readerMode: next.readerMode ?? false,
+ fileLibrary: next.fileLibrary ?? false,
+ activeTool: next.activeTool ?? null,
+ notificationsOpen: next.notificationsOpen ?? false,
+ toolReasons: next.toolReasons ?? prev.toolReasons,
+ };
const unchanged =
merged.appMounted === prev.appMounted &&
- merged.signingBadge === prev.signingBadge &&
- merged.portalAccess === prev.portalAccess &&
merged.readerMode === prev.readerMode &&
merged.fileLibrary === prev.fileLibrary &&
merged.activeTool === prev.activeTool &&
merged.notificationsOpen === prev.notificationsOpen &&
- merged.identity?.displayName === prev.identity?.displayName &&
- merged.identity?.profilePictureUrl ===
- prev.identity?.profilePictureUrl &&
// Compared by value: the object is rebuilt every render.
sameReasons(merged.toolReasons, prev.toolReasons);
return unchanged ? prev : merged;
@@ -120,14 +124,24 @@ export function QuickNavHostProvider({ children }: { children: ReactNode }) {
const value = useMemo<QuickNavHostValue>(
() => ({
- ...data,
+ ...account,
+ ...view,
chromeless,
actions,
- setData,
+ updateAccount,
+ setViewData,
setActions,
setChromeless,
}),
- [data, chromeless, setData, setActions, setChromeless],
+ [
+ account,
+ view,
+ chromeless,
+ updateAccount,
+ setViewData,
+ setActions,
+ setChromeless,
+ ],
);
return (
@@ -141,16 +155,14 @@ export function useQuickNavHost(): QuickNavHostValue | null {
return useContext(QuickNavHostContext);
}
-/** No-ops outside the provider. */
-export function useRegisterQuickNavHost(
- data: Partial<QuickNavHostData>,
+/** Registers the mounted view's controls; handlers are released on unmount. No-ops without a host. */
+export function useRegisterQuickNavView(
+ data: Partial<QuickNavViewData>,
actions: QuickNavHostActions,
): void {
const host = useQuickNavHost();
+ const setViewData = host?.setViewData;
const {
- identity,
- signingBadge,
- portalAccess,
readerMode,
fileLibrary,
activeTool,
@@ -158,26 +170,15 @@ export function useRegisterQuickNavHost(
toolReasons,
} = data;
useEffect(() => {
- host?.setData({
- appMounted: true,
- identity: identity ?? null,
- signingBadge: signingBadge ?? 0,
- portalAccess: portalAccess ?? false,
- readerMode: readerMode ?? false,
- fileLibrary: fileLibrary ?? false,
- // Cleared, not omitted as toolReasons is: a stale tool marks an entry.
- activeTool: activeTool ?? null,
- notificationsOpen: notificationsOpen ?? false,
- // Omitted when unknown, so the last answer survives a re-fetch.
- ...(toolReasons ? { toolReasons } : {}),
+ setViewData?.({
+ readerMode,
+ fileLibrary,
+ activeTool,
+ notificationsOpen,
+ toolReasons,
});
- // By field: identity is rebuilt every render.
}, [
- host,
- identity?.displayName,
- identity?.profilePictureUrl,
- signingBadge,
- portalAccess,
+ setViewData,
readerMode,
fileLibrary,
activeTool,
diff --git a/frontend/editor/src/core/contexts/quickNavAccount.ts b/frontend/editor/src/core/contexts/quickNavAccount.ts
new file mode 100644
index 0000000000..f258e4b2a5
--- /dev/null
+++ b/frontend/editor/src/core/contexts/quickNavAccount.ts
@@ -0,0 +1,48 @@
+export interface QuickNavIdentity {
+ displayName: string;
+ profilePictureUrl: string | null;
+}
+
+/** The last resolved account data, retained across view changes. */
+export interface QuickNavAccount {
+ accountId: string | null;
+ identity: QuickNavIdentity | null;
+ signingBadge: number;
+ portalAccess: boolean;
+}
+
+/** Undefined fields retain their previous value; null, false and zero replace it. */
+export type QuickNavAccountUpdate = Partial<QuickNavAccount>;
+
+export const EMPTY_QUICK_NAV_ACCOUNT: QuickNavAccount = {
+ accountId: null,
+ identity: null,
+ signingBadge: 0,
+ portalAccess: false,
+};
+
+/** Clears the previous account before applying an update for a different account. */
+export function updateQuickNavAccount(
+ previous: QuickNavAccount,
+ update: QuickNavAccountUpdate,
+): QuickNavAccount {
+ const accountId =
+ update.accountId === undefined ? previous.accountId : update.accountId;
+ const current =
+ accountId === previous.accountId ? previous : EMPTY_QUICK_NAV_ACCOUNT;
+ const next: QuickNavAccount = {
+ accountId,
+ identity:
+ update.identity === undefined ? current.identity : update.identity,
+ signingBadge: update.signingBadge ?? current.signingBadge,
+ portalAccess: update.portalAccess ?? current.portalAccess,
+ };
+
+ const unchanged =
+ next.accountId === previous.accountId &&
+ next.signingBadge === previous.signingBadge &&
+ next.portalAccess === previous.portalAccess &&
+ next.identity?.displayName === previous.identity?.displayName &&
+ next.identity?.profilePictureUrl === previous.identity?.profilePictureUrl;
+ return unchanged ? previous : next;
+}
diff --git a/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts b/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts
index 98ee64d81f..86424e5ca8 100644
--- a/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts
+++ b/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts
@@ -1,5 +1,6 @@
import { useSyncExternalStore } from "react";
-import { useGroupSigningEnabled } from "@app/hooks/useGroupSigningEnabled";
+import { useAuth } from "@app/auth/UseSession";
+import { useGroupSigningState } from "@app/hooks/useGroupSigningEnabled";
import { useSigningSessions } from "@app/hooks/signing/useSigningSessions";
import {
getLastSeenSignedCount,
@@ -11,11 +12,13 @@ import {
* Count that drives the Shared Signing badge: sign requests awaiting the user's
* signature, plus the user's own sessions that gained new signatures since they
* last opened them. 0 when group signing is disabled. Polls in the background
- * while enabled.
+ * while enabled. Unsettled while auth, config or sessions load, or the session
+ * lookup fails; consumers may retain their previous count until it settles.
*/
-export function useSigningBadgeCount(): number {
- const enabled = useGroupSigningEnabled();
- const { signRequests, mySessions } = useSigningSessions({
+export function useSigningBadgeState(): { count: number; settled: boolean } {
+ const { loading: authLoading } = useAuth();
+ const { enabled, settled: availabilitySettled } = useGroupSigningState();
+ const { signRequests, mySessions, settled } = useSigningSessions({
enabled,
autoRefreshInterval: enabled ? 60000 : 0,
});
@@ -38,5 +41,13 @@ export function useSigningBadgeCount(): number {
session.signedCount > getLastSeenSignedCount(session.sessionId),
).length;
- return incoming + ownerUpdates;
+ return {
+ count: enabled ? incoming + ownerUpdates : 0,
+ settled: !authLoading && availabilitySettled && (!enabled || settled),
+ };
+}
+
+/** Count without loading status; requests with no cached sessions report zero. */
+export function useSigningBadgeCount(): number {
+ return useSigningBadgeState().count;
}
diff --git a/frontend/editor/src/core/hooks/signing/useSigningSessions.ts b/frontend/editor/src/core/hooks/signing/useSigningSessions.ts
index e001af5441..0f28efe7c5 100644
--- a/frontend/editor/src/core/hooks/signing/useSigningSessions.ts
+++ b/frontend/editor/src/core/hooks/signing/useSigningSessions.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
+import { useAuth } from "@app/auth/UseSession";
import { fetchSigningSessions } from "@app/api/signing";
import { qk } from "@app/query/keys";
import { alert } from "@app/components/toast";
@@ -18,6 +19,8 @@ export interface UseSigningSessionsResult {
signRequests: SignRequestSummary[];
mySessions: SessionSummary[];
loading: boolean;
+ /** A successful snapshot with no replacement request still in flight. */
+ settled: boolean;
error: Error | null;
refetch: () => Promise<void>;
}
@@ -31,18 +34,20 @@ export const useSigningSessions = (
): UseSigningSessionsResult => {
const { enabled = true, autoRefreshInterval = 0 } = options;
const { t } = useTranslation();
+ const { user, loading: authLoading } = useAuth();
- const { data, isLoading, isLoadingError, error, refetch } = useQuery({
- queryKey: qk.signingSessions(),
- queryFn: fetchSigningSessions,
- enabled,
- staleTime: 0,
- refetchInterval: autoRefreshInterval > 0 ? autoRefreshInterval : false,
- refetchIntervalInBackground: false,
- // The interval pauses while unfocused, so returning has to catch up: the
- // client-wide default of false would hold stale data until the next tick.
- refetchOnWindowFocus: autoRefreshInterval > 0,
- });
+ const { data, isLoading, isFetching, isLoadingError, error, refetch } =
+ useQuery({
+ queryKey: qk.signingSessions(user?.id ?? null),
+ queryFn: fetchSigningSessions,
+ enabled: enabled && !authLoading,
+ staleTime: 0,
+ refetchInterval: autoRefreshInterval > 0 ? autoRefreshInterval : false,
+ refetchIntervalInBackground: false,
+ // The interval pauses while unfocused, so returning has to catch up: the
+ // client-wide default of false would hold stale data until the next tick.
+ refetchOnWindowFocus: autoRefreshInterval > 0,
+ });
const notifyFailure = useCallback(() => {
console.error("Failed to fetch signing data");
@@ -89,6 +94,7 @@ export const useSigningSessions = (
signRequests: data?.signRequests ?? EMPTY_REQUESTS,
mySessions: data?.mySessions ?? EMPTY_SESSIONS,
loading: isLoading || refreshing,
+ settled: data !== undefined && !isFetching && error === null,
error: (error as Error | null) ?? null,
refetch: explicitRefetch,
};
diff --git a/frontend/editor/src/core/hooks/useAccountIdentity.ts b/frontend/editor/src/core/hooks/useAccountIdentity.ts
index 026ac08dab..fc6b113d2e 100644
--- a/frontend/editor/src/core/hooks/useAccountIdentity.ts
+++ b/frontend/editor/src/core/hooks/useAccountIdentity.ts
@@ -1,7 +1,10 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAuth } from "@app/auth/UseSession";
-import { useProfilePictureUrl } from "@app/hooks/useProfilePictureUrl";
+import {
+ useProfilePictureLoading,
+ useProfilePictureUrl,
+} from "@app/hooks/useProfilePictureUrl";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { accountService } from "@app/services/accountService";
@@ -10,6 +13,8 @@ export interface AccountIdentity {
displayName: string;
profilePictureUrl: string | null;
isAnonymous: boolean;
+ /** Display values may be placeholders until the session, name and picture resolve. */
+ loading: boolean;
}
/**
@@ -25,40 +30,47 @@ export interface AccountIdentity {
*/
export function useAccountIdentity(): AccountIdentity {
const { t } = useTranslation();
- const { config } = useAppConfig();
- const { displayName: authDisplayName, isAnonymous } = useAuth();
+ const { config, loading: configLoading } = useAppConfig();
+ const {
+ displayName: authDisplayName,
+ isAnonymous,
+ loading: authLoading,
+ } = useAuth();
const profilePictureUrl = useProfilePictureUrl();
- const [accountUsername, setAccountUsername] = useState<string | null>(null);
+ const profilePictureLoading = useProfilePictureLoading();
+ const [accountUsername, setAccountUsername] = useState<
+ string | null | undefined
+ >(undefined);
useEffect(() => {
- if (!config?.enableLogin) {
- setAccountUsername(null);
- return;
- }
- if (authDisplayName) {
- // The auth context has a name; don't bother hitting the REST
- // endpoint, but clear any stale cached value from a prior call.
- setAccountUsername(null);
+ if (authLoading || !config?.enableLogin || authDisplayName) {
+ setAccountUsername(undefined);
return;
}
+ let active = true;
accountService
.getAccountData()
.then((data) => {
- // Always reflect the latest result - including clearing it on
- // sign-out, when the endpoint returns no username (or 401s into
- // the catch branch below). Without this, signing out would leave
- // the old username on screen.
- setAccountUsername(data?.username ?? null);
+ if (active) setAccountUsername(data?.username ?? null);
})
.catch(() => {
- setAccountUsername(null);
+ if (active) setAccountUsername(null);
});
- }, [config?.enableLogin, authDisplayName]);
+ return () => {
+ active = false;
+ };
+ }, [config?.enableLogin, authDisplayName, authLoading]);
return {
displayName:
authDisplayName ?? accountUsername ?? t("auth.displayName.user", "User"),
profilePictureUrl,
isAnonymous,
+ loading:
+ authLoading ||
+ profilePictureLoading ||
+ (!authDisplayName &&
+ (configLoading ||
+ (config?.enableLogin === true && accountUsername === undefined))),
};
}
diff --git a/frontend/editor/src/core/hooks/useGroupSigningEnabled.ts b/frontend/editor/src/core/hooks/useGroupSigningEnabled.ts
index 88a69c5dd9..3871637c4d 100644
--- a/frontend/editor/src/core/hooks/useGroupSigningEnabled.ts
+++ b/frontend/editor/src/core/hooks/useGroupSigningEnabled.ts
@@ -5,6 +5,14 @@ import { useAppConfig } from "@app/contexts/AppConfigContext";
* Core implementation reads directly from server config.
*/
export function useGroupSigningEnabled(): boolean {
- const { config } = useAppConfig();
- return config?.storageGroupSigningEnabled === true;
+ return useGroupSigningState().enabled;
+}
+
+/** Unsettled availability must not replace a previously resolved signing badge. */
+export function useGroupSigningState(): { enabled: boolean; settled: boolean } {
+ const { config, loading } = useAppConfig();
+ return {
+ enabled: config?.storageGroupSigningEnabled === true,
+ settled: !loading,
+ };
}
diff --git a/frontend/editor/src/core/hooks/useProfilePictureUrl.ts b/frontend/editor/src/core/hooks/useProfilePictureUrl.ts
index b43e673c9e..422e9e246c 100644
--- a/frontend/editor/src/core/hooks/useProfilePictureUrl.ts
+++ b/frontend/editor/src/core/hooks/useProfilePictureUrl.ts
@@ -4,3 +4,8 @@
export function useProfilePictureUrl(): string | null {
return null;
}
+
+/** Whether the current user's initial picture lookup is still pending. */
+export function useProfilePictureLoading(): boolean {
+ return false;
+}
diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsx
index 3fbb8b45e4..16a7c6934d 100644
--- a/frontend/editor/src/core/pages/HomePage.tsx
+++ b/frontend/editor/src/core/pages/HomePage.tsx
@@ -44,7 +44,6 @@ import {
getToolDisabledReason,
getDisabledLabel,
} from "@app/components/tools/fullscreen/shared";
-import { useOtherAppSwitch } from "@app/hooks/useOtherAppSwitch";
import { consumeReaderModeRequest } from "@app/utils/pendingReaderMode";
import {
FilesPageProvider,
@@ -126,7 +125,6 @@ export default function HomePage() {
const sliderRef = useRef<HTMLDivElement | null>(null);
const [activeMobileView, setActiveMobileView] = useState<MobileView>("tools");
const isProgrammaticScroll = useRef(false);
- const otherApp = useOtherAppSwitch();
const location = useLocation();
// The user's preference, and the only thing that decides it: reading mode forces
// the sidebar shut without writing, so leaving reading restores this.
@@ -472,7 +470,6 @@ export default function HomePage() {
<div className="h-screen overflow-hidden">
<HomePageExtensions />
<QuickNavHostBridge
- portalAccess={Boolean(otherApp)}
requestNavigation={requestNavigation}
readerMode={readerMode}
fileLibrary={navigationState.workbench === "myFiles"}
diff --git a/frontend/editor/src/core/pages/SettingsPage.tsx b/frontend/editor/src/core/pages/SettingsPage.tsx
index f5df738ca6..e713a9f726 100644
--- a/frontend/editor/src/core/pages/SettingsPage.tsx
+++ b/frontend/editor/src/core/pages/SettingsPage.tsx
@@ -27,7 +27,6 @@ import {
useUnsavedChanges,
} from "@app/contexts/UnsavedChangesContext";
import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
-import { useOtherAppSwitch } from "@app/hooks/useOtherAppSwitch";
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
import { stripBasePath } from "@app/constants/app";
import { takeSettingsOrigin } from "@app/utils/settingsNavigation";
@@ -52,9 +51,6 @@ const SettingsPageInner: React.FC = () => {
const isMobile = useIsMobile();
const licenseAlert = useLicenseAlert();
const { confirmIfDirty } = useUnsavedChanges();
- // The rail sits outside every app, so each page tells it what only the
- // signed-in session knows.
- const otherApp = useOtherAppSwitch();
// The same bar as the editor and the processor, so search is one thing
// everywhere; settings results deep-link straight back into this page.
const searchScopes = useEditorSearchScopes();
@@ -196,10 +192,7 @@ const SettingsPageInner: React.FC = () => {
return (
<div className="settings-page" data-tour="settings-modal">
- <QuickNavHostBridge
- portalAccess={Boolean(otherApp)}
- requestNavigation={requestNavigation}
- />
+ <QuickNavHostBridge requestNavigation={requestNavigation} />
<aside
className={`settings-page__nav modal-nav ${isMobile ? "mobile" : ""}`}
diff --git a/frontend/editor/src/core/query/keys.ts b/frontend/editor/src/core/query/keys.ts
index cae39e74f2..a937f24217 100644
--- a/frontend/editor/src/core/query/keys.ts
+++ b/frontend/editor/src/core/query/keys.ts
@@ -10,7 +10,8 @@ export const qk = {
["editor", "endpointEnabled", endpoint] as const,
footerInfo: () => ["editor", "footerInfo"] as const,
groupEnabled: (group: string) => ["editor", "groupEnabled", group] as const,
- signingSessions: () => ["editor", "signingSessions"] as const,
+ signingSessions: (userId: string | null) =>
+ ["editor", "signingSessions", userId] as const,
/** Keyed on the asking identity: two users must never share one answer. */
portalAccess: (userId: string | null) =>
["editor", "portalAccess", userId] as const,
diff --git a/frontend/editor/src/desktop/hooks/useGroupSigningEnabled.ts b/frontend/editor/src/desktop/hooks/useGroupSigningEnabled.ts
index 1f1a78244b..59d1a08778 100644
--- a/frontend/editor/src/desktop/hooks/useGroupSigningEnabled.ts
+++ b/frontend/editor/src/desktop/hooks/useGroupSigningEnabled.ts
@@ -6,11 +6,18 @@ import { useSelfHostedAuth } from "@app/hooks/useSelfHostedAuth";
* an authenticated session. Returns false in SaaS/local mode or when logged out.
*/
export function useGroupSigningEnabled(): boolean {
- const { config } = useAppConfig();
- const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
- return (
- isSelfHosted &&
- isAuthenticated &&
- config?.storageGroupSigningEnabled === true
- );
+ return useGroupSigningState().enabled;
+}
+
+/** Waits for desktop mode, authentication and config before confirming availability. */
+export function useGroupSigningState(): { enabled: boolean; settled: boolean } {
+ const { config, loading: configLoading } = useAppConfig();
+ const { isSelfHosted, isAuthenticated, loading } = useSelfHostedAuth();
+ return {
+ enabled:
+ isSelfHosted &&
+ isAuthenticated &&
+ config?.storageGroupSigningEnabled === true,
+ settled: !loading && !configLoading,
+ };
}
diff --git a/frontend/editor/src/desktop/hooks/useSelfHostedAuth.ts b/frontend/editor/src/desktop/hooks/useSelfHostedAuth.ts
index a02418f8d0..429b86764c 100644
--- a/frontend/editor/src/desktop/hooks/useSelfHostedAuth.ts
+++ b/frontend/editor/src/desktop/hooks/useSelfHostedAuth.ts
@@ -6,6 +6,8 @@ import { connectionModeService } from "@app/services/connectionModeService";
export interface SelfHostedAuthState {
isSelfHosted: boolean;
isAuthenticated: boolean;
+ /** False only once both desktop checks have resolved. */
+ loading: boolean;
}
/**
@@ -16,32 +18,58 @@ export interface SelfHostedAuthState {
*/
export function useSelfHostedAuth(): SelfHostedAuthState {
const { refetch } = useAppConfig();
- const [isAuthenticated, setIsAuthenticated] = useState(false);
- const [isSelfHosted, setIsSelfHosted] = useState(false);
+ const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
+ const [isSelfHosted, setIsSelfHosted] = useState<boolean | null>(null);
const wasSelfHosted = useRef(false);
useEffect(() => {
- void connectionModeService
- .getCurrentMode()
- .then((mode) => setIsSelfHosted(mode === "selfhosted"));
- return connectionModeService.subscribeToModeChanges((cfg) =>
- setIsSelfHosted(cfg.mode === "selfhosted"),
- );
+ let current = true;
+ void connectionModeService.getCurrentMode().then((mode) => {
+ if (current) setIsSelfHosted(mode === "selfhosted");
+ });
+ const unsubscribe = connectionModeService.subscribeToModeChanges((cfg) => {
+ current = false;
+ setIsSelfHosted(cfg.mode === "selfhosted");
+ });
+ return () => {
+ current = false;
+ unsubscribe();
+ };
}, []);
useEffect(() => {
- void authService.isAuthenticated().then(setIsAuthenticated);
- return authService.subscribeToAuth((status) =>
- setIsAuthenticated(status === "authenticated"),
- );
+ let current = true;
+ let subscribed = false;
+ const unsubscribe = authService.subscribeToAuth((status) => {
+ // The immediate notification can precede restoration from the keyring.
+ if (!subscribed) return;
+ current = false;
+ setIsAuthenticated(
+ status === "refreshing" || status === "oauth_pending"
+ ? null
+ : status === "authenticated",
+ );
+ });
+ subscribed = true;
+ void authService.isAuthenticated().then((authenticated) => {
+ if (current) setIsAuthenticated(authenticated);
+ });
+ return () => {
+ current = false;
+ unsubscribe();
+ };
}, []);
useEffect(() => {
if (isSelfHosted && !wasSelfHosted.current) {
void refetch();
}
- wasSelfHosted.current = isSelfHosted;
+ wasSelfHosted.current = isSelfHosted === true;
}, [isSelfHosted, refetch]);
- return { isSelfHosted, isAuthenticated };
+ return {
+ isSelfHosted: isSelfHosted === true,
+ isAuthenticated: isAuthenticated === true,
+ loading: isSelfHosted === null || isAuthenticated === null,
+ };
}
diff --git a/frontend/editor/src/desktop/hooks/useSigningBadgeState.test.tsx b/frontend/editor/src/desktop/hooks/useSigningBadgeState.test.tsx
new file mode 100644
index 0000000000..c22ef97e93
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useSigningBadgeState.test.tsx
@@ -0,0 +1,167 @@
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useSyncQuickNavAccount } from "@app/components/shared/quickNav/useSyncQuickNavAccount";
+import {
+ QuickNavHostProvider,
+ useQuickNavHost,
+} from "@app/contexts/QuickNavHostContext";
+import { fetchSigningSessions, type SigningSessions } from "@app/api/signing";
+import { authService } from "@app/services/authService";
+import { connectionModeService } from "@app/services/connectionModeService";
+import { alert } from "@app/components/toast";
+import { expectConsole } from "@app/tests/failOnConsole";
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ user: { id: "ada" }, loading: false, displayName: "Ada" }),
+}));
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({
+ config: { storageGroupSigningEnabled: true },
+ loading: false,
+ refetch: vi.fn().mockResolvedValue(undefined),
+ }),
+}));
+vi.mock("@app/services/authService", () => ({
+ authService: { isAuthenticated: vi.fn(), subscribeToAuth: vi.fn() },
+}));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCurrentMode: vi.fn(),
+ subscribeToModeChanges: vi.fn(),
+ },
+}));
+vi.mock("@app/api/signing", () => ({ fetchSigningSessions: vi.fn() }));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+const UNREAD: SigningSessions = {
+ signRequests: [],
+ mySessions: [
+ {
+ sessionId: "session-1",
+ documentName: "Document.pdf",
+ createdAt: "2026-09-14T12:00:00Z",
+ participantCount: 2,
+ signedCount: 1,
+ finalized: false,
+ },
+ ],
+};
+const mockFetch = vi.mocked(fetchSigningSessions);
+
+function SyncAccount() {
+ useSyncQuickNavAccount();
+ return null;
+}
+
+function Badge() {
+ return <output data-testid="badge">{useQuickNavHost()?.signingBadge}</output>;
+}
+
+function setup() {
+ const clients = {
+ editor: new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ settings: new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ docs: new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ };
+ const markup = (view: keyof typeof clients) => (
+ <QuickNavHostProvider>
+ <Badge />
+ <QueryClientProvider key={view} client={clients[view]}>
+ <SyncAccount />
+ </QueryClientProvider>
+ </QuickNavHostProvider>
+ );
+ const view = render(markup("editor"));
+ return (next: keyof typeof clients) => view.rerender(markup(next));
+}
+
+describe("desktop signing badge availability", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(
+ "selfhosted",
+ );
+ vi.mocked(connectionModeService.subscribeToModeChanges).mockReturnValue(
+ () => {},
+ );
+ vi.mocked(authService.isAuthenticated).mockResolvedValue(true);
+ vi.mocked(authService.subscribeToAuth).mockImplementation((listener) => {
+ listener("unauthenticated", null);
+ return () => {};
+ });
+ mockFetch.mockResolvedValue(UNREAD);
+ });
+
+ it.each(["mode", "auth"])(
+ "retains the badge while %s is the last desktop check to resolve, including a failed replacement fetch",
+ async (last) => {
+ const switchView = setup();
+ await waitFor(() =>
+ expect(screen.getByTestId("badge")).toHaveTextContent("1"),
+ );
+ let releaseMode = () => {};
+ let releaseAuth = () => {};
+ const modeBlocked = new Promise<void>((resolve) => {
+ releaseMode = resolve;
+ });
+ const authBlocked = new Promise<void>((resolve) => {
+ releaseAuth = resolve;
+ });
+ vi.mocked(connectionModeService.getCurrentMode).mockImplementationOnce(
+ async () => {
+ await modeBlocked;
+ return "selfhosted";
+ },
+ );
+ vi.mocked(authService.isAuthenticated).mockImplementationOnce(
+ async () => {
+ await authBlocked;
+ return true;
+ },
+ );
+ expectConsole.error(/Failed to fetch signing data/);
+ mockFetch.mockRejectedValueOnce(new Error("Offline"));
+ switchView("settings");
+ expect(screen.getByTestId("badge")).toHaveTextContent("1");
+ await act(async () => (last === "mode" ? releaseAuth() : releaseMode()));
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId("badge")).toHaveTextContent("1");
+ await act(async () => (last === "mode" ? releaseMode() : releaseAuth()));
+ await waitFor(() => expect(alert).toHaveBeenCalled());
+ expect(screen.getByTestId("badge")).toHaveTextContent("1");
+
+ mockFetch.mockResolvedValue({ signRequests: [], mySessions: [] });
+ switchView("docs");
+ await waitFor(() =>
+ expect(screen.getByTestId("badge")).toHaveTextContent("0"),
+ );
+ },
+ );
+
+ it.each(["local", "signed-out"])(
+ "clears the badge after confirming %s availability",
+ async (disabled) => {
+ const switchView = setup();
+ await waitFor(() =>
+ expect(screen.getByTestId("badge")).toHaveTextContent("1"),
+ );
+ if (disabled === "local") {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(
+ "local",
+ );
+ } else {
+ vi.mocked(authService.isAuthenticated).mockResolvedValue(false);
+ }
+ switchView("settings");
+ expect(screen.getByTestId("badge")).toHaveTextContent("1");
+ await waitFor(() =>
+ expect(screen.getByTestId("badge")).toHaveTextContent("0"),
+ );
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ },
+ );
+});
diff --git a/frontend/editor/src/portal/components/AppShell.tsx b/frontend/editor/src/portal/components/AppShell.tsx
index 0c1be174b6..30758725da 100644
--- a/frontend/editor/src/portal/components/AppShell.tsx
+++ b/frontend/editor/src/portal/components/AppShell.tsx
@@ -84,8 +84,7 @@ export function AppShell({ children }: { children: ReactNode }) {
return (
<div className="portal-shell">
- {/* portalAccess: being here is proof the processor is available. */}
- <QuickNavHostBridge portalAccess />
+ <QuickNavHostBridge />
<div className="workspace-frame">
<Sidebar />
</div>
diff --git a/frontend/editor/src/saas/auth/AuthProvider.test.tsx b/frontend/editor/src/saas/auth/AuthProvider.test.tsx
index bfd3bef352..87ecdad45a 100644
--- a/frontend/editor/src/saas/auth/AuthProvider.test.tsx
+++ b/frontend/editor/src/saas/auth/AuthProvider.test.tsx
@@ -1,4 +1,4 @@
-import { act, render, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Session, User } from "@supabase/supabase-js";
import { expectConsole } from "@app/tests/failOnConsole";
@@ -60,8 +60,24 @@ const { writeWorkbenchSession, readWorkbenchSession, resumeWorkbenchSession } =
/** Surfaces `loading` so a test can assert on it rather than on the container. */
function LoadingProbe() {
- const { loading } = useAuth();
- return <span data-testid="loading">{String(loading)}</span>;
+ const {
+ loading,
+ displayName,
+ profilePictureLoading,
+ profilePictureUrl,
+ refreshProfilePicture,
+ } = useAuth();
+ return (
+ <>
+ <span data-testid="loading">{String(loading)}</span>
+ <span data-testid="picture-loading">{String(profilePictureLoading)}</span>
+ <span data-testid="picture">{profilePictureUrl}</span>
+ <span data-testid="name">{displayName}</span>
+ <button onClick={() => void refreshProfilePicture()}>
+ Refresh picture
+ </button>
+ </>
+ );
}
const USER_ID = "11111111-2222-3333-4444-555555555555";
@@ -217,11 +233,143 @@ describe("AuthProvider user-data loading", () => {
);
// The picture read chains behind the sync, so it has not run yet either.
expect(createSignedUrl).not.toHaveBeenCalled();
+ expect(getByTestId("picture-loading").textContent).toBe("true");
await act(async () => {
releaseSync();
await new Promise((resolve) => setTimeout(resolve, 0));
});
+ expect(getByTestId("picture-loading").textContent).toBe("false");
+ expect(getByTestId("picture").textContent).toBe(
+ "https://example.test/avatar",
+ );
+ });
+
+ it("settles the picture lookup when the user has no avatar", async () => {
+ createSignedUrl.mockResolvedValue({
+ data: null,
+ error: { message: "Not found" },
+ });
+ const { getByTestId } = renderProvider();
+
+ await waitFor(() =>
+ expect(getByTestId("picture-loading").textContent).toBe("false"),
+ );
+ expect(getByTestId("picture").textContent).toBe("");
+ });
+
+ it.each(["sync", "read", "fallback"])(
+ "ignores the previous account's late avatar %s after the new picture loads",
+ async (stage) => {
+ let release = () => {};
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ if (stage === "sync") {
+ syncOAuthAvatar.mockImplementationOnce(async () => {
+ await blocked;
+ return false;
+ });
+ } else if (stage === "read") {
+ createSignedUrl.mockImplementationOnce(async () => {
+ await blocked;
+ return {
+ data: { signedUrl: "https://example.test/old-avatar" },
+ error: null,
+ };
+ });
+ } else {
+ createSignedUrl.mockResolvedValueOnce({
+ data: null,
+ error: { message: "Not found" },
+ });
+ getProfilePictureMetadata
+ .mockResolvedValueOnce(null)
+ .mockImplementationOnce(async () => {
+ await blocked;
+ return null;
+ });
+ }
+
+ const { fire, getByTestId } = renderProvider();
+ await waitFor(() =>
+ expect(getByTestId("loading")).toHaveTextContent("false"),
+ );
+ expect(getByTestId("picture-loading")).toHaveTextContent("true");
+ await fire("SIGNED_IN", makeSession({ userId: "account-b" }));
+ expect(getByTestId("picture-loading")).toHaveTextContent("false");
+
+ await act(async () => release());
+ expect(getByTestId("picture")).toHaveTextContent(
+ "https://example.test/avatar",
+ );
+ expect(getByTestId("picture-loading")).toHaveTextContent("false");
+ expect(createSignedUrl).toHaveBeenCalledTimes(stage === "sync" ? 1 : 2);
+
+ const refreshed = makeSession({
+ userId: "account-b",
+ token: "refreshed",
+ });
+ refreshed.user.user_metadata.full_name = "Updated name";
+ await fire("TOKEN_REFRESHED", refreshed);
+ expect(getByTestId("name")).toHaveTextContent("Updated name");
+ expect(getByTestId("picture-loading")).toHaveTextContent("false");
+ },
+ );
+
+ it("keeps the latest picture when refresh requests finish out of order", async () => {
+ const { getByRole, getByTestId } = renderProvider();
+ await waitFor(() =>
+ expect(getByTestId("picture-loading")).toHaveTextContent("false"),
+ );
+ let release = () => {};
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ createSignedUrl.mockImplementationOnce(async () => {
+ await blocked;
+ return {
+ data: { signedUrl: "https://example.test/old-avatar" },
+ error: null,
+ };
+ });
+ fireEvent.click(getByRole("button", { name: "Refresh picture" }));
+ createSignedUrl.mockResolvedValue({
+ data: { signedUrl: "https://example.test/new-avatar" },
+ error: null,
+ });
+ fireEvent.click(getByRole("button", { name: "Refresh picture" }));
+ await waitFor(() =>
+ expect(getByTestId("picture")).toHaveTextContent(
+ "https://example.test/new-avatar",
+ ),
+ );
+
+ await act(async () => release());
+ expect(getByTestId("picture")).toHaveTextContent(
+ "https://example.test/new-avatar",
+ );
+ expect(getByTestId("picture-loading")).toHaveTextContent("false");
+ });
+
+ it("ignores a pending picture after signing out", async () => {
+ let release = () => {};
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ createSignedUrl.mockImplementationOnce(async () => {
+ await blocked;
+ return {
+ data: { signedUrl: "https://example.test/old-avatar" },
+ error: null,
+ };
+ });
+ const { fire, getByTestId } = renderProvider();
+ await waitFor(() => expect(createSignedUrl).toHaveBeenCalled());
+ await fire("SIGNED_OUT", null);
+ await act(async () => release());
+ expect(getByTestId("picture").textContent).toBe("");
+ expect(getByTestId("picture-loading")).toHaveTextContent("false");
});
it("refetches after a guest upgrade, which keeps the same user id", async () => {
diff --git a/frontend/editor/src/saas/auth/UseSession.tsx b/frontend/editor/src/saas/auth/UseSession.tsx
index 4bd3b99346..b713f01b5e 100644
--- a/frontend/editor/src/saas/auth/UseSession.tsx
+++ b/frontend/editor/src/saas/auth/UseSession.tsx
@@ -71,6 +71,8 @@ interface AuthContextType {
error: AuthError | null;
isPro: boolean | null;
profilePictureUrl: string | null;
+ /** Pending until this user's picture lookup resolves, including a missing picture. */
+ profilePictureLoading: boolean;
profilePictureMetadata: ProfilePictureMetadata | null;
signOut: () => Promise<void>;
refreshSession: () => Promise<void>;
@@ -95,6 +97,7 @@ const AuthContext = createContext<AuthContextType>({
error: null,
isPro: null,
profilePictureUrl: null,
+ profilePictureLoading: true,
profilePictureMetadata: null,
signOut: async () => {},
refreshSession: async () => {},
@@ -111,8 +114,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [profilePictureUrl, setProfilePictureUrl] = useState<string | null>(
null,
);
+ const [profilePictureResolvedFor, setProfilePictureResolvedFor] = useState<
+ string | null
+ >(null);
const [profilePictureMetadata, setProfilePictureMetadata] =
useState<ProfilePictureMetadata | null>(null);
+ const sessionRef = useRef<Session | null>(null);
+ const profilePictureRequest = useRef(0);
+
+ const updateSession = useCallback((next: Session | null) => {
+ const previousUser = sessionRef.current?.user;
+ if (previousUser?.id !== next?.user.id) {
+ profilePictureRequest.current += 1;
+ setProfilePictureUrl(null);
+ setProfilePictureResolvedFor(null);
+ }
+ sessionRef.current = next;
+ setSession(next);
+ }, []);
const fetchProStatus = useCallback(
async (sessionToUse?: Session | null) => {
@@ -169,17 +188,29 @@ export function AuthProvider({ children }: { children: ReactNode }) {
);
const fetchProfilePicture = useCallback(
- async (sessionToUse?: Session | null) => {
- const currentSession = sessionToUse ?? session;
+ async (sessionToUse = sessionRef.current, syncProviderAvatar = false) => {
+ const currentSession = sessionToUse;
+ if (currentSession?.user.id !== sessionRef.current?.user.id) return;
+ // Own the whole sync/read chain so an earlier upload cannot start a newer lookup.
+ const request = ++profilePictureRequest.current;
if (!currentSession?.user) {
console.debug(
"[Auth Debug] No user session, skipping profile picture fetch",
);
setProfilePictureUrl(null);
+ setProfilePictureResolvedFor(null);
return;
}
+ if (syncProviderAvatar) {
+ await syncOAuthAvatar(currentSession.user).catch((err) => {
+ console.debug("[Auth Debug] Failed to sync OAuth avatar:", err);
+ });
+ if (request !== profilePictureRequest.current) return;
+ }
+
+ let pictureUrl: string | null;
try {
const PROFILE_BUCKET = "profile-pictures";
const profilePath = `${currentSession.user.id}/avatar`;
@@ -198,21 +229,23 @@ export function AuthProvider({ children }: { children: ReactNode }) {
"[Auth Debug] Profile picture not available:",
error.message,
);
- setProfilePictureUrl(
- await providerAvatarFallback(currentSession.user),
- );
+ pictureUrl = await providerAvatarFallback(currentSession.user);
} else {
- setProfilePictureUrl(data.signedUrl);
+ pictureUrl = data.signedUrl;
console.debug(
"[Auth Debug] Profile picture URL fetched successfully",
);
}
} catch (error: unknown) {
console.debug("[Auth Debug] Failed to fetch profile picture:", error);
- setProfilePictureUrl(await providerAvatarFallback(currentSession.user));
+ pictureUrl = await providerAvatarFallback(currentSession.user);
+ }
+ if (request === profilePictureRequest.current) {
+ setProfilePictureUrl(pictureUrl);
+ setProfilePictureResolvedFor(currentSession.user.id);
}
},
- [session, providerAvatarFallback],
+ [providerAvatarFallback],
);
const refreshProfilePicture = useCallback(async () => {
@@ -299,15 +332,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Off the awaited path: a first login re-uploads the provider avatar.
// The signed-URL read chains behind it because reading first 404s and
// silently falls back to the provider photo.
- const avatarSync = syncOAuthAvatar(user).catch((err) => {
- console.debug("[Auth Debug] Failed to sync OAuth avatar:", err);
- return false;
+ void fetchProfilePicture(sessionToLoad, true).catch((err) => {
+ console.debug("[Auth Debug] Failed to fetch profile picture:", err);
});
- void avatarSync
- .then(() => fetchProfilePicture(sessionToLoad))
- .catch((err) => {
- console.debug("[Auth Debug] Failed to fetch profile picture:", err);
- });
await Promise.all([
fetchProStatus(sessionToLoad),
@@ -340,10 +367,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
if (error) {
console.error("[Auth Debug] Session refresh error:", error);
setError(error);
- setSession(null);
+ updateSession(null);
} else {
console.debug("[Auth Debug] Session refreshed successfully");
- setSession(data.session);
+ updateSession(data.session);
}
} catch (err) {
console.error(
@@ -374,7 +401,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
resumeWorkbenchSession();
} else {
console.debug("[Auth Debug] Signed out successfully");
- setSession(null);
+ updateSession(null);
}
} catch (err) {
console.error("[Auth Debug] Unexpected error during sign out:", err);
@@ -403,7 +430,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
userId: data.session?.user?.id,
email: data.session?.user?.email,
});
- setSession(data.session);
+ updateSession(data.session);
// Awaited so the spinner does not clear before pro status is known.
await loadUserData(data.session);
@@ -442,7 +469,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Don't run supabase calls inside this callback; schedule them
setTimeout(() => {
if (mounted) {
- setSession(newSession);
+ updateSession(newSession);
setError(null);
// Additional handling for specific events
@@ -451,6 +478,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Clear pro status, profile picture, and metadata on sign out
setIsPro(null);
setProfilePictureUrl(null);
+ setProfilePictureResolvedFor(null);
setProfilePictureMetadata(null);
loadedForRef.current = null;
} else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
@@ -509,6 +537,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return () => {
mounted = false;
+ profilePictureRequest.current += 1;
subscription.unsubscribe();
};
// Empty and load-bearing: must subscribe once. The closures are recreated
@@ -528,6 +557,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
error,
isPro,
profilePictureUrl,
+ profilePictureLoading: Boolean(
+ user && profilePictureResolvedFor !== user.id,
+ ),
profilePictureMetadata,
signOut,
refreshSession,
diff --git a/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx b/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx
index 809138850a..e2cfe08214 100644
--- a/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx
+++ b/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx
@@ -1,10 +1,15 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { renderHook as baseRenderHook, waitFor } from "@testing-library/react";
+import {
+ act,
+ renderHook as baseRenderHook,
+ waitFor,
+} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
const get = vi.fn();
let currentUserId: string | null = null;
+let authLoading = false;
vi.mock("@app/services/apiClient", () => ({
default: {
@@ -13,10 +18,14 @@ vi.mock("@app/services/apiClient", () => ({
}));
vi.mock("@app/auth/UseSession", () => ({
- useAuth: () => ({ user: currentUserId ? { id: currentUserId } : null }),
+ useAuth: () => ({
+ user: currentUserId ? { id: currentUserId } : null,
+ loading: authLoading,
+ }),
}));
-const { usePortalAccess } = await import("@app/hooks/usePortalAccess");
+const { usePortalAccess, usePortalAccessState } =
+ await import("@app/hooks/usePortalAccess");
function meReturning(portalAccess: boolean) {
return { data: { user: { portalAccess } } };
@@ -41,6 +50,7 @@ describe("usePortalAccess", () => {
localStorage.clear();
get.mockReset();
currentUserId = null;
+ authLoading = false;
client = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
});
@@ -55,6 +65,60 @@ describe("usePortalAccess", () => {
await waitFor(() => expect(result.current).toBe(true));
});
+ it("does not report a settled denial while the incoming session is loading", async () => {
+ authLoading = true;
+ const { result, rerender } = renderHook(() => usePortalAccessState());
+ expect(result.current.settled).toBe(false);
+
+ currentUserId = "admin-1";
+ authLoading = false;
+ get.mockResolvedValue(meReturning(false));
+ rerender();
+ expect(result.current.settled).toBe(false);
+ await waitFor(() =>
+ expect(result.current).toEqual({ granted: false, settled: true }),
+ );
+ });
+
+ it("does not give a signed-out mount access from the previous browser cache", async () => {
+ currentUserId = "admin-1";
+ get.mockResolvedValue(meReturning(true));
+ const first = renderHook(() => usePortalAccessState());
+ await waitFor(() =>
+ expect(first.result.current).toEqual({ granted: true, settled: true }),
+ );
+ first.unmount();
+
+ currentUserId = null;
+ client.clear();
+ const signedOut = renderHook(() => usePortalAccessState());
+ expect(signedOut.result.current).toEqual({ granted: false, settled: true });
+ expect(get).toHaveBeenCalledTimes(1);
+ });
+
+ it("marks a cached answer unsettled while the incoming view revalidates it", async () => {
+ currentUserId = "admin-1";
+ get.mockResolvedValue(meReturning(true));
+ client.setDefaultOptions({ queries: { retry: false, gcTime: Infinity } });
+ const first = renderHook(() => usePortalAccessState());
+ await waitFor(() => expect(first.result.current.settled).toBe(true));
+ first.unmount();
+
+ let resolveAccess = (_value: ReturnType<typeof meReturning>) => {};
+ get.mockReturnValue(
+ new Promise<ReturnType<typeof meReturning>>((resolve) => {
+ resolveAccess = resolve;
+ }),
+ );
+ const next = renderHook(() => usePortalAccessState());
+ expect(next.result.current).toEqual({ granted: true, settled: false });
+
+ await act(async () => resolveAccess(meReturning(false)));
+ await waitFor(() =>
+ expect(next.result.current).toEqual({ granted: false, settled: true }),
+ );
+ });
+
it("re-asks the backend when a different user signs in without a reload", async () => {
// An admin gets a yes...
currentUserId = "admin-1";
diff --git a/frontend/editor/src/saas/hooks/usePortalAccess.ts b/frontend/editor/src/saas/hooks/usePortalAccess.ts
index 1bf22c79d5..c090d36ded 100644
--- a/frontend/editor/src/saas/hooks/usePortalAccess.ts
+++ b/frontend/editor/src/saas/hooks/usePortalAccess.ts
@@ -37,7 +37,7 @@ async function fetchPortalAccess(): Promise<boolean> {
* instead of appearing a request later. Guests skip the request entirely.
*/
export function usePortalAccessState(): PortalAccessState {
- const { user } = useAuth();
+ const { user, loading } = useAuth();
const userId = user?.id ?? null;
// The query cache is per-tree and per-load, so it can't help a cold start or
// the hop into the processor, which mounts its own client. Seed from the last
@@ -45,7 +45,7 @@ export function usePortalAccessState(): PortalAccessState {
// there at first paint. Marked ancient so it still revalidates immediately.
const [seed] = useState(readCachedOtherApp);
- const { data, isSuccess, isFetched } = useQuery({
+ const { data, isSuccess, isFetched, isFetching } = useQuery({
queryKey: qk.portalAccess(userId),
queryFn: fetchPortalAccess,
// Signed out: nothing to ask, and any previous answer is void.
@@ -67,8 +67,8 @@ export function usePortalAccessState(): PortalAccessState {
// once. Otherwise the seeded value is a guess until the probe comes back -
// callers that hide UI on "no access" must not act on the guess.
return {
- granted: data === true,
- settled: userId === null || isFetched,
+ granted: userId !== null && data === true,
+ settled: !loading && (userId === null || (isFetched && !isFetching)),
};
}
diff --git a/frontend/editor/src/saas/hooks/useProfilePictureUrl.ts b/frontend/editor/src/saas/hooks/useProfilePictureUrl.ts
index 3d2b4c635a..becf1f4aa6 100644
--- a/frontend/editor/src/saas/hooks/useProfilePictureUrl.ts
+++ b/frontend/editor/src/saas/hooks/useProfilePictureUrl.ts
@@ -3,3 +3,8 @@ import { useAuth } from "@app/auth/UseSession";
export function useProfilePictureUrl(): string | null {
return useAuth().profilePictureUrl;
}
+
+/** Whether the current user's initial picture lookup is still pending. */
+export function useProfilePictureLoading(): boolean {
+ return useAuth().profilePictureLoading;
+}