From 8ebd01804f2aa345c167599c19e801dbd66133b6 Mon Sep 17 00:00:00 2001 From: David McKay Date: Sat, 21 Nov 2026 17:48:21 -0800 Subject: [PATCH] App: show the sign-in screen after signing out of a hosted OpenBot On a hosted OpenBot with many organizations, Sign out showed the router's "Something went wrong! Couldn't find that organization." in place of the sign-in screen. The tab keeps the organization it worked in after signing out, so the sign-in screen read the deployment there, as nobody, and the server tells anybody who isn't a member that an organization doesn't exist. A self-hosted OpenBot's organization is `default`, which answers anybody, so it never showed there. The deployment, told "not found" in the organization the tab knows, is now read the way it is before signing in: at `default`, as nobody. --- app/src/lib/deployment/queries.ts | 18 +- app/tests/sign-in-after-sign-out.test.tsx | 236 ++++++++++++++++++++++ 2 files changed, 253 insertions(+), 1 deletion(-) create mode 100644 app/tests/sign-in-after-sign-out.test.tsx diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 9fb350839c..4b003776b9 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -120,13 +120,29 @@ function showsOpenBotOnThisComputer(): Promise { * Inside OpenBot Desktop, on the OpenBot on this computer, it is asked with the page's cookies, * which that OpenBot needs; the person is in `default` there. Told "not found" all the same, it is * asked in one of their own. + * + * SIGNED OUT, THE TAB STILL KNOWS THE ORGANIZATION IT WORKED IN, and on a hosted OpenBot with many + * organizations that one tells nobody it exists. Asked there after Sign out, the sign-in screen was + * told "not found" and drew the router's error in its place. Told "not found" in the organization + * it knows (signed out since, or no longer in it), it is asked the way it is before signing in. */ export async function readDeployment(options: { signal?: AbortSignal; fallback: string; }): Promise { const known = currentOrganizationId(); - if (known !== undefined) return getDeployment(known, options); + if (known !== undefined) { + try { + return await getDeployment(known, options); + } catch (error) { + if (!(error instanceof ClientError) || error.status !== 404) throw error; + if (await showsOpenBotOnThisComputer()) throw error; + return getDeployment(DEPLOYMENT_ORGANIZATION, { + ...options, + credentials: "omit", + }); + } + } if (!(await showsOpenBotOnThisComputer())) return getDeployment(DEPLOYMENT_ORGANIZATION, { ...options, diff --git a/app/tests/sign-in-after-sign-out.test.tsx b/app/tests/sign-in-after-sign-out.test.tsx new file mode 100644 index 0000000000..5027534374 --- /dev/null +++ b/app/tests/sign-in-after-sign-out.test.tsx @@ -0,0 +1,236 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + type AnyRoute, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useSignOut } from "@/components/app-sidebar/use-sign-out"; +import { getGetDeploymentResponseMock } from "@/lib/api/generated/organization-settings/organization-settings.msw"; +import { GetDeploymentResponse } from "@/lib/api/generated/organization-settings/organization-settings.zod"; +import { ListOrganizationsResponse } from "@/lib/api/generated/organizations/organizations.zod"; +import { ReportedErrorComponent } from "@/lib/error-reporting"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import type { RouterContext } from "@/router-context"; +import { Route as AuthedRoute } from "@/routes/_authed"; +import { Route as SignRoute } from "@/routes/sign"; +import { nativeFetch, pageFetch } from "./page-fetch"; +import { settleReactWork } from "./settle-react-work"; + +/** + * Signing out on a hosted OpenBot with many organizations (OpenBot Cloud). The person works in their own + * organization, not `default`, and the server answers an organization's deployment only to its members; anybody + * else, signed out included, is told it isn't found. Asked as nobody, `default`'s says what this OpenBot offers + * anybody. + * + * Signing out kept the organization the person had been working in, so the sign-in screen asked that + * organization's deployment as nobody, was told it wasn't found, and showed the router's "Something went wrong! + * Couldn't find that organization." in place of the sign-in screen. Now it shows the sign-in screen. + * + * The OpenBot is a real HTTP server on this computer, its answers checked against the schemas generated from the + * spec. The app is the real sign-in gate, the real sign-in screen, the app's own error screen, and Sign out as the + * account menu has it. + */ + +const NativeResponse = globalThis.Response; +const ORGANIZATION = "org_acme"; +let openbot: ReturnType; +let signedIn: boolean; +let requests: string[]; + +const problem = (status: number, code: string, detail: string) => + new NativeResponse(JSON.stringify({ status, code, detail, title: detail }), { + status, + headers: { "content-type": "application/problem+json" }, + }); + +const NOT_FOUND = () => + problem(404, "ORGANIZATION_NOT_FOUND", "Couldn't find that organization."); + +const deployment = () => + NativeResponse.json( + GetDeploymentResponse.parse({ + ...getGetDeploymentResponseMock(), + edition: "team", + authProviders: ["google"], + hostedSignIn: true, + ssoConfigured: false, + ssoRequired: false, + }), + ); + +async function answer(request: Request): Promise { + const url = new URL(request.url); + const path = url.pathname; + const session = request.headers.get("x-test-session") === "yes"; + requests.push(`${request.method} ${path}${session ? "" : " (as nobody)"}`); + const deploymentOf = /^\/api\/v2\/organizations\/([^/]+)\/deployment$/.exec( + path, + )?.[1]; + if (deploymentOf === "default") + // Asked as nobody: what this OpenBot offers anybody. Asked by somebody who isn't in `default`: not found. + return session ? NOT_FOUND() : deployment(); + if (deploymentOf === ORGANIZATION) + // Only a member is told an organization exists. + return session ? deployment() : NOT_FOUND(); + if (path === "/api/auth/sign-out" && request.method === "POST") { + signedIn = false; + return NativeResponse.json({ success: true }); + } + if (!signedIn) return problem(401, "UNAUTHENTICATED", "Sign in to OpenBot."); + if (path === "/api/v2/people/me/organizations") + return NativeResponse.json( + ListOrganizationsResponse.parse({ + organizations: [ + { + id: ORGANIZATION, + slug: "acme", + name: "Acme", + role: "admin", + active: true, + personal: false, + }, + ], + canCreate: true, + nextCursor: null, + }), + ); + if (path === `/api/v2/organizations/${ORGANIZATION}/people/me`) + return NativeResponse.json({ + person: { + id: "dana", + email: "dana@example.com", + name: "Dana Whitfield", + needsName: false, + image: null, + role: "admin", + onboarding: null, + }, + openbotVersion: null, + }); + if (path === `/api/v2/organizations/${ORGANIZATION}/shortened-tool-names`) + return NativeResponse.json({ tools: [] }); + return NOT_FOUND(); +} + +beforeAll(() => { + openbot = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: answer }); + GlobalRegistrator.register({ url: `http://127.0.0.1:${openbot.port}/` }); +}); +beforeEach(() => { + signedIn = true; + requests = []; + setCurrentOrganization(undefined); + queryClient.clear(); + const page = pageFetch(); + // The browser sends the session's cookie while there is one, unless the request asks as nobody. + globalThis.fetch = Object.assign( + (input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + if (signedIn && init?.credentials !== "omit") + headers.set("x-test-session", "yes"); + return page(input, { ...init, headers }); + }, + { preconnect: nativeFetch.preconnect }, + ) as typeof fetch; +}); +afterEach(async () => { + cleanup(); + await settleReactWork(); + queryClient.clear(); + globalThis.fetch = nativeFetch; +}); +afterAll(async () => { + await settleReactWork(); + await GlobalRegistrator.unregister(); + openbot.stop(true); + setCurrentOrganization("default"); +}); + +/** The app as somebody signed in sees it: home, with Sign out as the account menu has it. */ +function Home() { + const signOut = useSignOut(); + return ( +
+

The app

+ +
+ ); +} + +/** The app opened at `start`: the real sign-in gate in front of home, the sign-in screen, the app's error screen. */ +function openApp(start: string) { + const root = createRootRouteWithContext()({ + component: Outlet, + }); + const gate = AuthedRoute.options as unknown as Record; + const authed = createRoute({ + id: "_authed", + getParentRoute: () => root, + component: Outlet, + ...{ beforeLoad: gate.beforeLoad, errorComponent: gate.errorComponent }, + } as never) as unknown as AnyRoute; + const home = createRoute({ + getParentRoute: () => authed, + path: "/", + component: Home, + } as never) as unknown as AnyRoute; + const sign = SignRoute.options as unknown as Record; + const signIn = createRoute({ + getParentRoute: () => root, + path: "/sign", + ...{ + validateSearch: sign.validateSearch, + beforeLoad: sign.beforeLoad, + component: sign.component, + }, + } as never) as unknown as AnyRoute; + const router = createRouter({ + routeTree: root.addChildren([authed.addChildren([home]), signIn]), + history: createMemoryHistory({ initialEntries: [start] }), + context: { queryClient }, + defaultErrorComponent: ReportedErrorComponent, + }); + const view = render( + + + , + ); + return { view, router, person: userEvent.setup({ document }) }; +} + +test("signed out of an organization that isn't default, the sign-in screen shows, not an error", async () => { + const { view, router, person } = openApp("/"); + await view.findByText("The app"); + await person.click(view.getByRole("button", { name: "Sign out" })); + await waitFor(() => expect(requests).toContain("POST /api/auth/sign-out")); + await view.findByRole( + "link", + { name: "Continue with OpenBot by CopilotKit" }, + { timeout: 5_000 }, + ); + expect(router.state.location.pathname).toBe("/sign"); + expect(view.queryByText(/Something went wrong/)).toBeNull(); + expect(view.queryByText("Couldn't find that organization.")).toBeNull(); + // What the sign-in screen offers was asked as nobody, of what this OpenBot offers anybody. + expect(requests).toContain( + "GET /api/v2/organizations/default/deployment (as nobody)", + ); +}, 15_000);