Files
PaperClipAI/ui/src/hooks/useSignOut.test.tsx
T
DottaandPaperclip f258b34bbd fix(ui): unify cloud-managed sign-out (#10994)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip can run as a self-hosted app or as a Cloud-managed tenant.
> - These modes need different sign-out sequences because Cloud owns
three sessions.
> - Several visible controls implemented sign-out separately and could
choose different paths.
> - This pull request adds one Cloud-aware sign-out action and moves
every visible control to it.
> - The benefit is one safe sign-out path in Cloud and unchanged local
sign-out in self-hosted deployments.

## Linked Issues or Issue Description

Refs #2073. That older PR adds a separate company-settings sign-out
surface. This change centralizes the existing account, company, and
instance-settings surfaces and preserves the self-hosted behavior
described there.

**What happened?**

Visible sign-out controls used separate implementations. A Cloud-managed
control could call the app-local sign-out endpoint and open the local
auth page. That path did not enter the Cloud-owned logout sequence for
the tenant, Cloud, and identity sessions.

**Expected behavior**

Every visible sign-out control must use one action. Cloud-managed
instances must navigate the top-level window to the same-origin
`/cloud/logout` route without a local sign-out call first. Authenticated
self-hosted instances must keep the local sign-out API and cache
invalidation behavior.

**Steps to reproduce**

1. Open a Cloud-managed tenant.
2. Use the account menu, company menu, or instance-settings sign-out
control.
3. Observe that independently implemented controls can enter different
sign-out paths.

**Paperclip version or commit**

The problem reproduces at `656ecfa585b31938e2685ffab3db22e794474803`.

**Deployment mode**

Cloud-managed tenant built from source. The regression tests also cover
authenticated self-hosted mode.

## What Changed

- Added `useSignOut` as the shared Cloud-aware sign-out action.
- Navigated Cloud-managed sessions to `/cloud/logout` exactly once
without calling local auth first.
- Preserved local API sign-out and cache invalidation for authenticated
self-hosted sessions.
- Migrated the account menu, company menu, and instance general settings
to the shared action.
- Added focused tests for mode selection, menu closure, pending state,
failure state, and settings behavior.

## Verification

- `pnpm exec vitest run ui/src/hooks/useSignOut.test.tsx
ui/src/components/SidebarAccountMenu.test.tsx
ui/src/components/SidebarCompanyMenu.test.tsx
ui/src/pages/InstanceGeneralSettings.test.tsx` — 26 tests passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm check:token-gates` — passed.
- `git diff --check origin/master..HEAD` — passed.

## Risks

- Low risk. The change centralizes existing behavior and adds no schema,
API, telemetry, or style-token changes.
- Cloud mode depends on the existing health decision. Tests pin both
mode branches.
- The change does not alter Fetch Metadata, CSRF, cookie, prefetch, or
return-URL protections owned by the Cloud logout route.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, GPT-5. The runtime does not expose a more specific model
ID or context-window size. The agent used high-reasoning mode, shell
tools, and API tools.

## 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
- [ ] 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>
2026-08-06 12:13:14 -05:00

124 lines
4.4 KiB
TypeScript

// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { queryKeys } from "@/lib/queryKeys";
import { useSignOut } from "./useSignOut";
const mockAuthApi = vi.hoisted(() => ({ signOut: vi.fn() }));
const mockNavigateTopLevel = vi.hoisted(() => vi.fn());
vi.mock("@/api/auth", () => ({ authApi: mockAuthApi }));
vi.mock("@/lib/browserNavigation", () => ({ navigateTopLevel: mockNavigateTopLevel }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
let captured: ReturnType<typeof useSignOut> | null = null;
function Harness({ onSignedOut }: { onSignedOut?: () => void }) {
captured = useSignOut({ onSignedOut });
return null;
}
describe("useSignOut", () => {
let container: HTMLDivElement;
let queryClient: QueryClient;
beforeEach(() => {
captured = null;
container = document.createElement("div");
document.body.appendChild(container);
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => {
queryClient.clear();
container.remove();
vi.clearAllMocks();
});
function renderHarness(onSignedOut?: () => void) {
const root = createRoot(container);
flushSync(() => {
root.render(
<QueryClientProvider client={queryClient}>
<Harness onSignedOut={onSignedOut} />
</QueryClientProvider>,
);
});
return root;
}
it("closes caller chrome and navigates through Cloud without local sign-out", async () => {
const onSignedOut = vi.fn();
queryClient.setQueryData(queryKeys.health, {
status: "ok",
cloud: {
managed: true,
managedBy: "paperclip-cloud",
stackSlug: "acme",
cloudBaseUrl: "https://cloud.example.test",
},
});
const root = renderHarness(onSignedOut);
flushSync(() => captured?.mutate());
await vi.waitFor(() => expect(mockNavigateTopLevel).toHaveBeenCalledOnce());
expect(mockNavigateTopLevel).toHaveBeenCalledWith("/cloud/logout");
expect(onSignedOut).toHaveBeenCalledOnce();
expect(mockAuthApi.signOut).not.toHaveBeenCalled();
flushSync(() => root.unmount());
});
it("keeps self-hosted sign-out pending until the local request finishes, then invalidates caches", async () => {
let resolveSignOut: (() => void) | undefined;
mockAuthApi.signOut.mockImplementation(() => new Promise<void>((resolve) => {
resolveSignOut = resolve;
}));
queryClient.setQueryData(queryKeys.health, { status: "ok", deploymentMode: "authenticated" });
queryClient.setQueryData(queryKeys.auth.session, { session: { id: "session-1" } });
const onSignedOut = vi.fn();
const root = renderHarness(onSignedOut);
flushSync(() => captured?.mutate());
await vi.waitFor(() => expect(captured?.isPending).toBe(true));
expect(mockAuthApi.signOut).toHaveBeenCalledOnce();
expect(mockNavigateTopLevel).not.toHaveBeenCalled();
expect(onSignedOut).not.toHaveBeenCalled();
resolveSignOut?.();
await vi.waitFor(() => expect(captured?.isPending).toBe(false));
expect(captured?.error).toBeNull();
expect(onSignedOut).toHaveBeenCalledOnce();
expect(queryClient.getQueryState(queryKeys.auth.session)?.isInvalidated).toBe(true);
expect(queryClient.getQueryState(queryKeys.health)?.isInvalidated).toBe(true);
flushSync(() => root.unmount());
});
it("exposes a stable error without closing chrome or invalidating caches", async () => {
mockAuthApi.signOut.mockRejectedValue(new Error("Sign-out request failed"));
queryClient.setQueryData(queryKeys.health, { status: "ok", deploymentMode: "authenticated" });
queryClient.setQueryData(queryKeys.auth.session, { session: { id: "session-1" } });
const onSignedOut = vi.fn();
const root = renderHarness(onSignedOut);
flushSync(() => captured?.mutate());
await vi.waitFor(() => expect(captured?.error?.message).toBe("Sign-out request failed"));
expect(captured?.isPending).toBe(false);
expect(onSignedOut).not.toHaveBeenCalled();
expect(queryClient.getQueryState(queryKeys.auth.session)?.isInvalidated).toBe(false);
expect(queryClient.getQueryState(queryKeys.health)?.isInvalidated).toBe(false);
flushSync(() => root.unmount());
});
});