fix(ui): prevent organization title flicker during plugin loading (#13854)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The sidebar identifies the current organization.
> - An optional plugin can replace this navigation surface.
> - The built-in title appears before discovery and module loading
finish.
> - This pull request reserves the trigger until its owner is known.
> - The organization name appears once, while failures retain built-in
navigation.

## Linked Issues or Issue Description

Refs #13832. Searched related pull requests and issues; no duplicate fix
found.

**What happened?**
The organization switcher renders a provisional built-in title before an
installed replacement loads. Unrelated plugin imports can also affect
its loading state.

**Expected behavior**
Reserve the trigger with a neutral placeholder, then show the resolved
navigation surface. Keep the built-in menu on failed or absent
contributions.

**Steps to reproduce**
Install an organization-switcher contribution. Delay session, company,
contribution, and module responses. Reload the page and watch the
trigger through each stage.

## What Changed

- Reserve the trigger through account, company selection, slot
discovery, and module loading.
- Distinguish failed session lookup from pending lookup so errors retain
usable navigation.
- Load and await only contributions matching the requested slots.
Observe completion of imports started by another consumer.
- Document loading behavior and add regression coverage for loading,
failures, unrelated modules, and identity transitions.

## Verification

- `pnpm -r typecheck` passed, including Rust checks.
- `pnpm build` passed.
- All 629 UI test files passed: 6,593 tests. The 42 focused
UI/API/plugin tests also passed.
- `pnpm check:token-gates` and `git diff --check` passed.
- `pnpm test:run` was also attempted. The broad local server run was
stopped after recording skill-cache/channel fixture failures outside
this diff (for example, runtime skill source status `missing` instead of
`available`). The original cause is not established. All latest-head
Linux CI gates pass; the complete UI suite and affected local checks
pass.
- Desktop (1440px) and mobile (390px) Chromium checks passed with real
host components, dynamic module loading, and the built Account bundle.
Delayed fixture responses produced exactly two title states: empty
placeholder, then the resolved name. A slow refresh preserved the title
and trigger dimensions; absent/failed plugin fallback and Escape
dismissal passed, with zero uncaught browser errors. This is browser
component integration, not a live signed-in tenant test.

## Risks

A cold load displays a neutral placeholder until discovery completes.
Absent, ambiguous, failed, and invalid contributions still use the
built-in menu. No migrations or authorization changes. Scoped module
loading changes when an unrelated contribution is imported; each surface
loads its own matching modules.

## Model Used

OpenAI Codex, GPT-6, with reasoning, code execution, and browser
verification. The exact deployment ID and context window are not exposed
in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-09-22 20:33:29 -07:00
1 parent 106d89314f
commit e4237c45f3
7 files changed
+124 -24

No files matched your search

+3
View File
@@ -629,6 +629,9 @@ logout callback; authenticate remote account requests at their owning service.
resolve its external account/organization label itself; the host does not fetch
that portfolio on the plugin's behalf.
The slot props and `useHostContext()` are display context, not proof of identity.
The host reserves the trigger with a neutral placeholder while account, company,
and plugin discovery load. Plugins should reserve the same space while their
external label loads and retain resolved labels during same-account refreshes.
The host resets plugin state on account/company changes and keeps its built-in
menu when no unique contribution exists, discovery fails, the module is missing,
or rendering throws. The slot is a React-only contract; do not use a custom
+2 -1
View File
@@ -272,7 +272,8 @@ export interface PluginDetailTabProps {
}
/** A single installed contribution replaces the organization menu. The host
* retains its built-in menu while loading, on ambiguity, or on render failure.
* reserves the trigger while loading and uses its built-in menu when absent,
* ambiguous, or on render failure.
* These values/callbacks are presentation context, never authorization. */
export interface PluginOrganizationSwitcherProps {
organizationSwitcher: {
+3 -3
View File
@@ -73,9 +73,9 @@ const sessionQueryOptions = {
* So: settled on success only. A failed session lookup leaves the list unfetched
* until the query recovers, which it does on the next refetch.
*/
export function useAccountIdentity(): { userId: string | null; settled: boolean } {
const { data: session, isSuccess } = useQuery(sessionQueryOptions);
return { userId: session?.user.id ?? null, settled: isSuccess };
export function useAccountIdentity(): { userId: string | null; settled: boolean; failed: boolean } {
const { data: session, isSuccess, isError } = useQuery(sessionQueryOptions);
return { userId: session?.user.id ?? null, settled: isSuccess, failed: isError };
}
/**
@@ -8,8 +8,8 @@ import type { PluginOrganizationSwitcherProps } from "@paperclipai/plugin-sdk/ui
import { PluginOrganizationSwitcher } from "./PluginOrganizationSwitcher";
import { registerPluginReactComponent, registerPluginWebComponent, type ResolvedPluginSlot } from "@/plugins/slots";
const state = vi.hoisted(() => ({ userId: "alice", companyId: "company-a", settled: true, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [] as ResolvedPluginSlot[], errorMessage: null as string | null, mobile: false, collapsed: false, close: vi.fn(), signOut: vi.fn(), props: null as PluginOrganizationSwitcherProps | null }));
vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => state, useCompanyListQuery: () => ({ isSuccess: state.companyListReady, data: { unauthorized: false, companies: state.companyIds.map(id => ({ id, name: "Acme", issuePrefix: "ACME", logoUrl: "/logo" })) } }) }));
const state = vi.hoisted(() => ({ userId: "alice", companyId: "company-a", settled: true, failed: false, isLoading: false, companyListError: false, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [] as ResolvedPluginSlot[], errorMessage: null as string | null, mobile: false, collapsed: false, close: vi.fn(), signOut: vi.fn(), props: null as PluginOrganizationSwitcherProps | null }));
vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => state, useCompanyListQuery: () => ({ isSuccess: state.companyListReady, isError: state.companyListError, data: { unauthorized: false, companies: state.companyIds.map(id => ({ id, name: "Acme", issuePrefix: "ACME", logoUrl: "/logo" })) } }) }));
vi.mock("@/api/auth", () => ({ authApi: { getSession: async () => ({ user: { id: state.userId } }) } }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: state.companyId, selectedCompany: { name: "Acme", issuePrefix: "ACME", logoUrl: "/logo" } }) }));
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: state.mobile, setSidebarOpen: state.close, collapsed: state.collapsed, peeking: false }) }));
@@ -26,7 +26,7 @@ function render() {
}
afterEach(() => {
if (root) flushSync(() => root!.unmount()); root = undefined; container?.remove(); client.clear(); vi.restoreAllMocks();
Object.assign(state, { userId: "alice", companyId: "company-a", settled: true, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [], errorMessage: null, mobile: false, collapsed: false, props: null });
Object.assign(state, { userId: "alice", companyId: "company-a", settled: true, failed: false, isLoading: false, companyListError: false, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [], errorMessage: null, mobile: false, collapsed: false, props: null });
state.close.mockClear(); state.signOut.mockClear();
});
function register() {
@@ -39,11 +39,29 @@ function register() {
state.slots = [slot];
}
describe("organization navigation replacement", () => {
it("keeps built-in navigation for absent, ambiguous, failed or unsettled discovery", () => {
it("reserves the trigger until identity, companies, discovery and the module are ready", () => {
state.settled = false;
render();
expect(container.textContent).toBe("");
expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();
state.settled = true; state.companyListReady = false; render();
expect(container.textContent).toBe("");
state.companyListReady = true; state.isLoading = true; render();
expect(container.textContent).toBe("");
state.slots = [{ ...slot, exportName: "Delayed" }]; render();
expect(container.textContent).toBe("");
registerPluginReactComponent(slot.pluginKey, "Delayed", () => <button>Resolved organization</button>);
state.isLoading = false; render();
expect(container.textContent).toBe("Resolved organization");
expect(container.querySelector('[aria-busy="true"]')).toBeNull();
});
it("keeps built-in navigation for absent, ambiguous or failed discovery", () => {
render(); expect(container.textContent).toBe("Built-in organizations");
register(); state.slots = [slot, { ...slot, id: "other" }]; render(); expect(container.textContent).toBe("Built-in organizations");
state.slots = [slot]; state.errorMessage = "offline"; render(); expect(container.textContent).toBe("Built-in organizations");
state.errorMessage = null; state.settled = false; render(); expect(container.textContent).toBe("Built-in organizations");
state.errorMessage = null; state.settled = false; state.failed = true; render(); expect(container.textContent).toBe("Built-in organizations");
state.failed = false; state.settled = true; state.companyListReady = false; state.companyListError = true;
render(); expect(container.textContent).toBe("Built-in organizations");
});
it("falls back when a declared module is missing or rendering fails", () => {
state.slots = [{ ...slot, exportName: "Missing" }]; render(); expect(container.textContent).toBe("Built-in organizations");
@@ -57,12 +75,14 @@ describe("organization navigation replacement", () => {
state.companyListReady = false;
state.props = null;
render();
expect(container.textContent).toBe("Built-in organizations");
expect(container.querySelector('[aria-label="Loading organization"]')).not.toBeNull();
expect(container.textContent).toBe("");
expect(state.props).toBeNull();
state.companyListReady = true;
state.companyIds = ["company-b"];
render();
expect(container.textContent).toBe("Built-in organizations");
expect(container.querySelector('[aria-label="Loading organization"]')).not.toBeNull();
expect(container.textContent).toBe("");
expect(state.props).toBeNull();
state.companyId = "company-b";
render();
@@ -1,4 +1,5 @@
import { useState, type ReactNode } from "react";
import { ChevronsUpDown } from "lucide-react";
import type { PluginOrganizationSwitcherProps } from "@paperclipai/plugin-sdk/ui";
import { useAccountIdentity, useCompanyListQuery } from "@/api/companies-query";
import { useCompany } from "@/context/CompanyContext";
@@ -6,14 +7,27 @@ import { useSidebar } from "@/context/SidebarContext";
import { useSignOut } from "@/hooks/useSignOut";
import { PluginSlotMount, usePluginSlots } from "@/plugins/slots";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
import { Skeleton } from "./ui/skeleton";
/** Optional replacement; the built-in menu stays usable throughout rollout. */
/** Reserve the trigger's space until its owner is known. Never flash another name. */
function OrganizationSwitcherLoading({ collapsed }: { collapsed: boolean }) {
return <div role="status" aria-label="Loading organization" aria-busy="true"
className="flex h-9 min-w-0 flex-1 items-center gap-2 px-4">
<Skeleton className="size-5 shrink-0" />
{!collapsed && <>
<span className="min-w-0 flex-1"><Skeleton className="h-4 w-20 max-w-full" /></span>
<ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
</>}
</div>;
}
/** Optional replacement; use the built-in menu when discovery or rendering fails. */
export function PluginOrganizationSwitcher({ children, open: controlledOpen, onOpenChange }: {
children: ReactNode;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const { userId, settled } = useAccountIdentity();
const { userId, settled, failed } = useAccountIdentity();
const { selectedCompanyId } = useCompany();
const companyList = useCompanyListQuery();
// Selection is component state and can outlive its account until an effect
@@ -21,17 +35,18 @@ export function PluginOrganizationSwitcher({ children, open: controlledOpen, onO
const selectedCompany = companyList.data?.companies.find(company => company.id === selectedCompanyId) ?? null;
const contextSettled = settled && companyList.isSuccess && !companyList.data?.unauthorized
&& (selectedCompanyId === null || selectedCompany !== null);
const contextLoading = !contextSettled && !failed && !companyList.isError && !companyList.data?.unauthorized;
return (
<OrganizationSwitcher key={JSON.stringify([userId, selectedCompanyId])}
settled={contextSettled} companyId={selectedCompanyId}
settled={contextSettled} loading={contextLoading} companyId={selectedCompanyId}
company={selectedCompany} open={controlledOpen} onOpenChange={onOpenChange}>
{children}
</OrganizationSwitcher>
);
}
function OrganizationSwitcher({ children, settled, companyId, company, open: controlledOpen, onOpenChange }: {
children: ReactNode; settled: boolean; companyId: string | null;
function OrganizationSwitcher({ children, settled, loading, companyId, company, open: controlledOpen, onOpenChange }: {
children: ReactNode; settled: boolean; loading: boolean; companyId: string | null;
company: { name: string; issuePrefix: string; logoUrl?: string | null } | null;
open?: boolean; onOpenChange?: (open: boolean) => void;
}) {
@@ -44,7 +59,10 @@ function OrganizationSwitcher({ children, settled, companyId, company, open: con
if (isMobile) setSidebarOpen(false);
}
const signOut = useSignOut({ onSignedOut: closeNavigation });
const { slots, errorMessage } = usePluginSlots({ slotTypes: ["organizationSwitcher"], companyId, enabled: settled });
const { slots, isLoading, errorMessage } = usePluginSlots({ slotTypes: ["organizationSwitcher"], companyId, enabled: settled });
if (loading || (settled && isLoading && !errorMessage)) {
return <OrganizationSwitcherLoading collapsed={collapsed && !peeking} />;
}
// Never choose an arbitrary winner for a replacement surface.
if (!settled || errorMessage || slots.length !== 1) return children;
const props: PluginOrganizationSwitcherProps = {
+55
View File
@@ -0,0 +1,55 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { PluginUiContribution } from "@/api/plugins";
import { queryKeys } from "@/lib/queryKeys";
import { _resetPluginModuleLoader, ensurePluginContributionLoaded, usePluginSlots } from "./slots";
const contribution: PluginUiContribution = {
pluginId: "navigation", pluginKey: "fixture.navigation", displayName: "Navigation", version: "1",
uiEntryFile: "index.js", launchers: [],
slots: [{ type: "organizationSwitcher", id: "navigation", displayName: "Organizations", exportName: "Switcher" }],
};
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
function Consumer() {
const { isLoading } = usePluginSlots({ slotTypes: ["organizationSwitcher"] });
return <span>{isLoading ? "Loading" : "Ready"}</span>;
}
async function render() {
await act(async () => root.render(<QueryClientProvider client={client}><Consumer /></QueryClientProvider>));
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.stubGlobal("__paperclipPluginBridge__", {});
client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount()); container.remove(); client.clear(); _resetPluginModuleLoader();
vi.unstubAllGlobals(); vi.restoreAllMocks();
});
it("does not wait for or load modules for unrelated slots", async () => {
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
client.setQueryData(queryKeys.plugins.uiContributions, [{ ...contribution,
slots: [{ type: "page", id: "other", displayName: "Other", exportName: "Page", routePath: "other" }],
}]);
await render();
expect(container.textContent).toBe("Ready");
expect(fetch).not.toHaveBeenCalled();
});
it("settles when a module import started by another consumer fails", async () => {
let reject!: (error: Error) => void;
const fetch = vi.fn(() => new Promise<Response>((_resolve, rejectPromise) => { reject = rejectPromise; }));
vi.stubGlobal("fetch", fetch); vi.spyOn(console, "error").mockImplementation(() => {});
client.setQueryData(queryKeys.plugins.uiContributions, [contribution]);
const loading = ensurePluginContributionLoaded(contribution);
await render();
expect(container.textContent).toBe("Loading");
await act(async () => { reject(new Error("unavailable")); await loading; });
expect(container.textContent).toBe("Ready");
expect(fetch).toHaveBeenCalledOnce();
});
+10 -7
View File
@@ -614,10 +614,11 @@ function usePluginModuleLoader(contributions: PluginUiContribution[] | undefined
useEffect(() => {
if (!contributions || contributions.length === 0) return;
// Filter to contributions that haven't been loaded yet.
// Also await imports started by another consumer so this observer gets a
// completion render even when there is no export registration (e.g. errors).
const unloaded = contributions.filter((c) => {
const state = pluginLoadStates.get(buildPluginModuleKey(c));
return state !== "loaded" && state !== "loading";
return state !== "loaded";
});
if (unloaded.length === 0) return;
@@ -653,9 +654,6 @@ export function usePluginSlots(filters: SlotFilters): UsePluginSlotsResult {
enabled: queryEnabled,
});
// Kick off dynamic imports for any new plugin contributions.
usePluginModuleLoader(data);
const slotTypesKey = useMemo(() => [...filters.slotTypes].sort().join("|"), [filters.slotTypes]);
const slots = useMemo(() => {
@@ -688,8 +686,13 @@ export function usePluginSlots(filters: SlotFilters): UsePluginSlotsResult {
return rows;
}, [data, filters.entityType, slotTypesKey]);
// Consider loading until both query and module imports are done.
const modulesLoaded = data ? aggregateLoadState(data) === "loaded" : true;
// A replacement surface must not disappear while an unrelated plugin loads.
const contributions = useMemo(() => {
const pluginIds = new Set(slots.map(slot => slot.pluginId));
return data?.filter(contribution => pluginIds.has(contribution.pluginId));
}, [data, slots]);
usePluginModuleLoader(contributions);
const modulesLoaded = contributions ? aggregateLoadState(contributions) === "loaded" : true;
const isLoading = queryEnabled && (isQueryLoading || !modulesLoaded);
return {