From c4c3fe128bf0fbb9d67dedfb66bf0f6e5384d8cf Mon Sep 17 00:00:00 2001 From: David McKay Date: Sat, 21 Nov 2026 16:12:39 -0800 Subject: [PATCH 1/2] App: agree to the OpenBot Cloud terms before using it OpenBot Cloud asks people to agree to its Terms of Service and Acceptable Use Policy before they use it, and again when the version changes. The signed-in gate now sends a person who has to agree to /terms from anywhere, before onboarding, remembering where they were headed. The screen is onboarding's frame with one step: an unticked box naming both documents as links, Continue that waits for it, and Sign out. Agreeing sends the version shown; terms that changed meanwhile show the new version unticked with the server's sentence. An OpenBot without the operation reads as having no terms. Any other failed read holds the person at the terms screen with Try again, so a failure never lets anybody past. Self-hosted and the personal edition have no terms and never see the screen. --- .github/workflows/ci.yml | 6 +- app/src/lib/service-terms/mutations.ts | 34 ++ app/src/lib/service-terms/queries.ts | 89 ++++ app/src/routeTree.gen.ts | 21 + app/src/routes/_authed.tsx | 10 + app/src/routes/_authed/terms.tsx | 220 ++++++++ app/tests/service-terms.fixture.tsx | 84 +++ app/tests/service-terms.test.tsx | 705 +++++++++++++++++++++++++ 8 files changed, 1167 insertions(+), 2 deletions(-) create mode 100644 app/src/lib/service-terms/mutations.ts create mode 100644 app/src/lib/service-terms/queries.ts create mode 100644 app/src/routes/_authed/terms.tsx create mode 100644 app/tests/service-terms.fixture.tsx create mode 100644 app/tests/service-terms.test.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba70769fa3..51c8b9862d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -386,7 +386,9 @@ jobs: # next language the recognizer has, or says which language to add and where. The page's # language and its names for languages are the engine's own. And the sidebar's edge, dragged in a # window zoomed in, narrowing the sidebar, which never takes more than two-fifths of the window. - # In the image, as above: WebKit's + # And the terms on OpenBot Cloud: the gate holding a person at them from anywhere until they tick + # the box and agree, asking again when they change, and never shown where there are none, in the + # engine the Mac window draws with too. In the image, as above: WebKit's # system packages are about 94 MB, which took nine minutes from the mirror on a slow day. app-browser-webkit: name: app (real browser, WebKit) @@ -410,7 +412,7 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx + bun test app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx # The desktop setup window's, for the same reason as the list above: the AI step's form holding # still while the install behind it comes and goes. It bundles the window from the desktop's own diff --git a/app/src/lib/service-terms/mutations.ts b/app/src/lib/service-terms/mutations.ts new file mode 100644 index 0000000000..fc3586f031 --- /dev/null +++ b/app/src/lib/service-terms/mutations.ts @@ -0,0 +1,34 @@ +import { mutationOptions, type QueryClient } from "@tanstack/react-query"; +import { acceptServiceTerms } from "@/lib/api/generated/people/people"; +import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { type ServiceTerms, serviceTermsKeys } from "./queries"; + +const FALLBACK = "Couldn't save that you agreed. Try again."; + +/** + * Agree to the terms, by the version the person was shown. A version that is no longer current is + * refused with SERVICE_TERMS_CHANGED, and the screen reads the terms again to show the new one. + * + * Either way the terms are read again, with `refetchType: "all"`: the gate reads them through + * `ensureQueryData`, which takes the cache as it finds it, so a stale "has to agree" would send the + * person straight back to the terms. + */ +export function acceptServiceTermsMutationOptions(queryClient: QueryClient) { + const invalidate = () => + queryClient.invalidateQueries({ + queryKey: serviceTermsKeys.all, + refetchType: "all", + }); + return mutationOptions({ + mutationFn: (version: string): Promise => + acceptServiceTerms( + organizationId(), + "me", + { version }, + { "Idempotency-Key": idempotencyKey() }, + { fallback: FALLBACK }, + ), + onSuccess: invalidate, + onError: invalidate, + }); +} diff --git a/app/src/lib/service-terms/queries.ts b/app/src/lib/service-terms/queries.ts new file mode 100644 index 0000000000..545e981f77 --- /dev/null +++ b/app/src/lib/service-terms/queries.ts @@ -0,0 +1,89 @@ +import { type QueryClient, queryOptions } from "@tanstack/react-query"; +import type { ServiceTerms } from "@/lib/api/generated/model"; +import { getServiceTerms } from "@/lib/api/generated/people/people"; +import { organizationId } from "@/lib/api/request"; +import { ClientError } from "@/lib/client"; + +/** + * The terms of service a person agrees to before they use OpenBot (getServiceTerms): the version in + * force, the one they last agreed to, and the server's verdict on whether they have to agree now. + * Only OpenBot Cloud has terms. Everywhere else `current` is null and nobody is asked. + */ +export type { ServiceTerms }; + +export const serviceTermsKeys = { + all: ["service-terms"] as const, + mine: ["service-terms", "mine"] as const, +}; + +/** What an OpenBot with no terms answers, and what an OpenBot older than the question reads as. */ +const NO_TERMS: ServiceTerms = { + current: null, + accepted: null, + acceptanceNeeded: false, +}; + +/** + * A 404 that says the person isn't there is about them, and fails like any other refusal. Any + * other 404 is an OpenBot older than this operation, which has no terms. An organization not found + * is read the same way: every other read in it fails too, and the app's own page for that answers + * the person (OrganizationBoundary), where the terms screen would only say it couldn't load. + */ +function olderOpenBot(error: unknown): boolean { + return ( + error instanceof ClientError && + error.status === 404 && + error.code !== "PERSON_NOT_FOUND" + ); +} + +/** The person's own terms. An OpenBot without the operation answers as one with no terms. */ +export function serviceTermsQueryOptions() { + return queryOptions({ + queryKey: serviceTermsKeys.mine, + queryFn: async ({ signal }): Promise => { + try { + return await getServiceTerms(organizationId(), "me", { + signal, + fallback: "Couldn't load the terms.", + }); + } catch (error) { + if (olderOpenBot(error)) return NO_TERMS; + throw error; + } + }, + }); +} + +/** + * Whether the person has to see the terms before anything else, for the signed-in gate: the + * server's verdict, never recomputed from the versions. + * + * A read that fails reads as yes. Letting somebody in because the question failed would let an + * OpenBot Cloud person use it without agreeing, so the terms screen takes them instead, says the + * read failed and offers Try again. An OpenBot with no terms answers no without failing, and an + * older one's 404 is read as no terms above, so neither ever shows the screen. + */ +export async function serviceTermsRequired( + queryClient: QueryClient, +): Promise { + try { + return (await queryClient.ensureQueryData(serviceTermsQueryOptions())) + .acceptanceNeeded; + } catch { + return true; + } +} + +/** + * Where the terms screen sends somebody once they agree: the address they were headed to, when it + * is a page of this app, else home. Only a path on this origin is followed, so the address can't + * send anybody off the app; the terms screen itself is never the destination. + */ +export function afterTerms(next: unknown): string { + if (typeof next !== "string") return "/"; + if (!next.startsWith("/") || next.startsWith("//") || next.includes("\\")) + return "/"; + if (next === "/terms" || next.startsWith("/terms?")) return "/"; + return next; +} diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.ts index 1c17ea8204..7144e4f608 100644 --- a/app/src/routeTree.gen.ts +++ b/app/src/routeTree.gen.ts @@ -17,6 +17,7 @@ import { Route as AuthedAppRouteImport } from './routes/_authed/_app' import { Route as AuthedAdminRouteRouteImport } from './routes/_authed/admin/route' import { Route as AuthedOnboardingRouteImport } from './routes/_authed/onboarding' import { Route as AuthedSettingsRouteRouteImport } from './routes/_authed/settings/route' +import { Route as AuthedTermsRouteImport } from './routes/_authed/terms' import { Route as AuthedAppIndexRouteImport } from './routes/_authed/_app/index' import { Route as AuthedAppApprovalsRouteImport } from './routes/_authed/_app/approvals' import { Route as AuthedAppBotRouteImport } from './routes/_authed/_app/bot' @@ -172,6 +173,11 @@ const AuthedSettingsRouteRoute = AuthedSettingsRouteRouteImport.update({ path: '/settings', getParentRoute: () => AuthedRoute, } as any) +const AuthedTermsRoute = AuthedTermsRouteImport.update({ + id: '/terms', + path: '/terms', + getParentRoute: () => AuthedRoute, +} as any) const AuthedAppIndexRoute = AuthedAppIndexRouteImport.update({ id: '/', path: '/', @@ -816,6 +822,7 @@ export interface FileRoutesByFullPath { '/admin': typeof AuthedAdminRouteRouteWithChildren '/settings': typeof AuthedSettingsRouteRouteWithChildren '/onboarding': typeof AuthedOnboardingRoute + '/terms': typeof AuthedTermsRoute '/approvals': typeof AuthedAppApprovalsRoute '/bot': typeof AuthedAppBotRoute '/browser': typeof AuthedAppBrowserRoute @@ -937,6 +944,7 @@ export interface FileRoutesByTo { '/desktop-return': typeof DesktopReturnRoute '/sign': typeof SignRoute '/onboarding': typeof AuthedOnboardingRoute + '/terms': typeof AuthedTermsRoute '/approvals': typeof AuthedAppApprovalsRoute '/bot': typeof AuthedAppBotRoute '/browser': typeof AuthedAppBrowserRoute @@ -1062,6 +1070,7 @@ export interface FileRoutesById { '/_authed/settings': typeof AuthedSettingsRouteRouteWithChildren '/_authed/_app': typeof AuthedAppRouteWithChildren '/_authed/onboarding': typeof AuthedOnboardingRoute + '/_authed/terms': typeof AuthedTermsRoute '/_authed/_app/approvals': typeof AuthedAppApprovalsRoute '/_authed/_app/bot': typeof AuthedAppBotRoute '/_authed/_app/browser': typeof AuthedAppBrowserRoute @@ -1189,6 +1198,7 @@ export interface FileRouteTypes { | '/admin' | '/settings' | '/onboarding' + | '/terms' | '/approvals' | '/bot' | '/browser' @@ -1310,6 +1320,7 @@ export interface FileRouteTypes { | '/desktop-return' | '/sign' | '/onboarding' + | '/terms' | '/approvals' | '/bot' | '/browser' @@ -1434,6 +1445,7 @@ export interface FileRouteTypes { | '/_authed/settings' | '/_authed/_app' | '/_authed/onboarding' + | '/_authed/terms' | '/_authed/_app/approvals' | '/_authed/_app/bot' | '/_authed/_app/browser' @@ -1617,6 +1629,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedSettingsRouteRouteImport parentRoute: typeof AuthedRoute } + '/_authed/terms': { + id: '/_authed/terms' + path: '/terms' + fullPath: '/terms' + preLoaderRoute: typeof AuthedTermsRouteImport + parentRoute: typeof AuthedRoute + } '/_authed/_app/': { id: '/_authed/_app/' path: '/' @@ -2718,6 +2737,7 @@ interface AuthedRouteChildren { AuthedSettingsRouteRoute: typeof AuthedSettingsRouteRouteWithChildren AuthedAppRoute: typeof AuthedAppRouteWithChildren AuthedOnboardingRoute: typeof AuthedOnboardingRoute + AuthedTermsRoute: typeof AuthedTermsRoute AuthedSignInRequestIdRoute: typeof AuthedSignInRequestIdRoute } @@ -2726,6 +2746,7 @@ const AuthedRouteChildren: AuthedRouteChildren = { AuthedSettingsRouteRoute: AuthedSettingsRouteRouteWithChildren, AuthedAppRoute: AuthedAppRouteWithChildren, AuthedOnboardingRoute: AuthedOnboardingRoute, + AuthedTermsRoute: AuthedTermsRoute, AuthedSignInRequestIdRoute: AuthedSignInRequestIdRoute, } diff --git a/app/src/routes/_authed.tsx b/app/src/routes/_authed.tsx index a0160d5e24..c50ccd8da8 100644 --- a/app/src/routes/_authed.tsx +++ b/app/src/routes/_authed.tsx @@ -22,6 +22,7 @@ import { ReportedErrorComponent } from "../lib/error-reporting"; import { AppHotkeys } from "../lib/hotkeys/app-hotkeys"; import { rememberInvitationLink } from "../lib/organizations/invitation-link"; import { learnShortenedToolNames } from "../lib/plugins/tool-names"; +import { serviceTermsRequired } from "../lib/service-terms/queries"; import { SkinAccountSync } from "../skins/account-sync"; import { useActiveSkin } from "../skins/registry"; @@ -42,6 +43,15 @@ export const Route = createFileRoute("/_authed")({ } throw redirect({ to: "/sign" }); } + /* + * Terms to agree to (OpenBot Cloud), before onboarding and everything else: from anywhere to + * the terms screen, which remembers where they were headed. The terms screen itself is let + * through here, past the gates after this one, until they agree. + */ + if (await serviceTermsRequired(context.queryClient)) { + if (location.pathname === "/terms") return; + throw redirect({ to: "/terms", search: { next: location.href } }); + } /* * Somebody who has not finished onboarding goes there and nowhere else. Here rather than in * `_app`, so admin and settings are behind the same gate; checked against the destination so diff --git a/app/src/routes/_authed/terms.tsx b/app/src/routes/_authed/terms.tsx new file mode 100644 index 0000000000..8c4190686d --- /dev/null +++ b/app/src/routes/_authed/terms.tsx @@ -0,0 +1,220 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router"; +import * as React from "react"; +import { useSignOut } from "@/components/app-sidebar/use-sign-out"; +import { IntroReel } from "@/components/onboarding/demos/intro-reel"; +import { StepIntro } from "@/components/onboarding/onboarding-frame"; +import { + type OnboardingStep, + OnboardingWizard, +} from "@/components/onboarding/onboarding-wizard"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Item, ItemContent, ItemMedia } from "@/components/ui/item"; +import { ClientError } from "@/lib/client"; +import { appConfig } from "@/lib/generated/application-config"; +import { acceptServiceTermsMutationOptions } from "@/lib/service-terms/mutations"; +import { + afterTerms, + type ServiceTerms, + serviceTermsQueryOptions, + serviceTermsRequired, +} from "@/lib/service-terms/queries"; +import { queryClient } from "@/query-client"; + +const PRODUCT = appConfig.brand.productName; + +export const Route = createFileRoute("/_authed/terms")({ + /* + * `?next=` is where the person was headed when the gate brought them here, and where agreeing + * takes them (`afterTerms` follows only a path in this app). Named even when absent, so a key + * left out never keeps whatever was typed into the address. + */ + validateSearch: (search: Record): { next?: string } => ({ + next: typeof search.next === "string" ? search.next : undefined, + }), + // Somebody with nothing to agree to has no business here: on to where they were headed. + beforeLoad: async ({ context, search }) => { + if (!(await serviceTermsRequired(context.queryClient))) + throw redirect({ href: afterTerms(search.next), replace: true }); + }, + component: TermsScreen, +}); + +/** + * THE TERMS, BEFORE ANYTHING ELSE. On OpenBot Cloud a person agrees to the Terms of Service and the + * Acceptable Use Policy before they use it, and again whenever the version changes. The signed-in + * gate (`_authed`) sends them here from anywhere until they do. + * + * Drawn as onboarding's first step, in its frame, so it reads as part of signing up rather than a + * wall in front of it. One step: no step list and no Back. The box starts unticked and Continue + * waits for it. Both names open in a new tab, which OpenBot Desktop opens in the person's browser. + * Sign out is the way out for somebody who won't agree. + * + * The tick is for one version: it is kept as the version ticked, so terms that change while the + * screen is open (the server refuses with SERVICE_TERMS_CHANGED, and the terms are read again) + * show unticked, with the server's sentence saying why. + * + * Once the server says there is nothing left to agree to, the person goes on to where they were + * headed, or home, which hands a new person to onboarding as before. + */ +function TermsScreen() { + const navigate = useNavigate(); + const { next } = Route.useSearch(); + const terms = useQuery(serviceTermsQueryOptions()); + const accept = useMutation(acceptServiceTermsMutationOptions(queryClient)); + const signOut = useSignOut(); + const [agreedTo, setAgreedTo] = React.useState(null); + + const agreed = terms.data?.acceptanceNeeded === false; + React.useEffect(() => { + if (agreed) void navigate({ href: afterTerms(next), replace: true }); + }, [agreed, navigate, next]); + + if (terms.isPending || agreed) return null; + + const current = terms.data?.current ?? null; + const checked = current !== null && agreedTo === current.version; + // Somebody who agreed to an earlier version is told what changed, not welcomed again. + const changed = Boolean(terms.data?.accepted); + + const failed = terms.error && !terms.data; + const notice = failed ? ( +
+

+ Couldn't load the terms. Try again to continue. +

+ +
+ ) : accept.error ? ( +

+ {refusalSentence(accept.error)} +

+ ) : undefined; + + const step: OnboardingStep = { + id: "terms", + title: changed ? "The terms have changed" : "Agree to the terms", + intro: () => ( + { + accept.reset(); + setAgreedTo(next ? current.version : null); + }} + /> + ) : undefined + } + > +

+ {changed + ? `Read the new version and agree to it to keep using ${PRODUCT}.` + : `Read the terms for using ${PRODUCT}, then agree to them to continue.`} +

+
+ ), + demo: () => , + primaryLabel: "Continue", + primaryDisabled: !checked, + primaryPending: accept.isPending, + onPrimary: () => { + if (current && checked) accept.mutate(current.version); + }, + secondary: { + label: signOut.pending ? "Signing out…" : "Sign out", + onClick: signOut.run, + }, + notice, + }; + + return ( + // Outside `_app` like onboarding: no sidebar and no chrome until the person is in. +
+ +
+ ); +} + +/** + * The one control: a tickbox and the sentence it agrees to, in the outlined row Welcome's switch + * sits in. The sentence is the tickbox's label, so pressing it ticks the box; the two names are + * links inside it, which open their page and leave the box as it was. + */ +function AgreeBox({ + current, + checked, + onChange, +}: { + current: NonNullable; + checked: boolean; + onChange: (checked: boolean) => void; +}) { + // Each name kept on one line, so a narrow screen never breaks one in two. + const link = + "font-medium whitespace-nowrap text-foreground underline underline-offset-4 hover:text-primary"; + return ( + + + onChange(next === true)} + /> + + + + + + ); +} + +/** + * What a refused agreement says. Terms that changed while the screen was open are said in the + * server's own sentence, over the new version; anything else in the screen's own words. + */ +function refusalSentence(error: Error): string { + if (error instanceof ClientError && error.code === "SERVICE_TERMS_CHANGED") + return error.message; + return "Couldn't save that you agreed. Try again."; +} diff --git a/app/tests/service-terms.fixture.tsx b/app/tests/service-terms.fixture.tsx new file mode 100644 index 0000000000..f97a6196b4 --- /dev/null +++ b/app/tests/service-terms.fixture.tsx @@ -0,0 +1,84 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import { + createBrowserHistory, + createRootRouteWithContext, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { createRoot } from "react-dom/client"; +import { ThemeProvider } from "@/components/theme-provider"; +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 OnboardingRoute } from "@/routes/_authed/onboarding"; +import { Route as TermsRoute } from "@/routes/_authed/terms"; + +/** + * The signed-in gate, the terms screen and onboarding, for service-terms.test.tsx to bundle and + * load in a browser. The gate is `_authed`'s own `beforeLoad`, and the terms screen and onboarding + * are their own routes, so where a person is sent is what the app does. Home and Settings behind the + * gate are pages that say their names: this is about getting there. What the server answers comes + * from the test's routes. + * + * Started in `default`, the organization those routes answer for, as every test does. + */ +setCurrentOrganization("default"); + +const rootRoute = createRootRouteWithContext()({ + component: () => , +}); + +const authedRoute = createRoute({ + id: "/_authed", + getParentRoute: () => rootRoute, + // The app's own gate, as it runs in front of every signed-in page. + beforeLoad: async (options) => { + await ( + AuthedRoute.options.beforeLoad as unknown as ( + given: typeof options, + ) => Promise + )(options); + }, + component: () => , +}); + +const mounted = (route: T, path: string) => + (route as unknown as { update: (options: unknown) => T }).update({ + id: path, + path, + getParentRoute: () => authedRoute, + }); + +const router = createRouter({ + history: createBrowserHistory(), + context: { queryClient }, + routeTree: rootRoute.addChildren([ + authedRoute.addChildren([ + mounted(TermsRoute, "/terms") as never, + mounted(OnboardingRoute, "/onboarding") as never, + createRoute({ + getParentRoute: () => authedRoute, + path: "/settings", + component: () =>

Settings

, + }), + createRoute({ + getParentRoute: () => authedRoute, + path: "/", + component: () =>

Home

, + }), + ]), + ]), +}); + +const root = document.getElementById("root"); +if (root) + createRoot(root).render( + + + + + , + ); diff --git a/app/tests/service-terms.test.tsx b/app/tests/service-terms.test.tsx new file mode 100644 index 0000000000..9f4f11fe31 --- /dev/null +++ b/app/tests/service-terms.test.tsx @@ -0,0 +1,705 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page, Request } from "playwright-core"; +import { compile } from "tailwindcss"; +import { parse } from "yaml"; +import type { ServiceTerms } from "@/lib/api/generated/model"; +import { + AcceptServiceTermsBody, + AcceptServiceTermsResponse, + GetServiceTermsResponse, +} from "@/lib/api/generated/people/people.zod"; +import { afterTerms } from "@/lib/service-terms/queries"; +import { personBody } from "./accounts-api"; + +/** + * The terms of service, on OpenBot Cloud and everywhere else. + * + * In a real browser, through the app's own signed-in gate (`_authed`), the terms screen and + * onboarding: + * + * - A new person on OpenBot Cloud is sent to the terms from anywhere. The box starts unticked and + * Continue waits for it. Ticking it and Continue agree to the version shown, and onboarding + * follows, as it always has. + * - Somebody who agreed to an older version is asked again, told the terms changed, and once they + * agree goes on to the page they were headed to. + * - Terms that change while the screen is open (409 SERVICE_TERMS_CHANGED) show the new version, + * unticked, with the server's sentence; agreeing then sends the new version. + * - A self-hosted OpenBot has no terms and never shows the screen, and neither does an OpenBot + * older than the question. A read that fails holds a person at the screen, with Try again. + * + * The server is served as routes at the API's address, answering as api/openapi.yaml says: the + * spec's own examples for the terms, every body the page sends checked against the generated + * request schema, every answer against the response schema. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/service-terms.test.tsx + * + * Chromium by default; OPENBOT_APP_ENGINES=chromium,webkit adds the engine the Mac window draws + * with, as CI runs it. With OPENBOT_APP_SHOTS= each screen is saved as + * terms----.png, beside onboarding's Welcome to compare. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORIGIN = "http://openbot.test"; +const ORGANIZATION = "/api/v2/organizations/default"; +const ME = `${ORGANIZATION}/people/me`; +const TERMS = `${ME}/terms`; + +const WIDE = { width: 1440, height: 900 }; +const PHONE = { width: 390, height: 844 }; +const THEMES = ["light", "dark"] as const; +type Theme = (typeof THEMES)[number]; +type Window = { width: number; height: number }; + +type Example = { value: Record }; +const spec = parse( + readFileSync(join(APP, "..", "api", "openapi.yaml"), "utf8"), +) as { + components: { + examples: Record; + responses: Record< + string, + { + content: { + "application/problem+json": { examples: Record }; + }; + } + >; + }; +}; +/** One of the spec's examples, as the server would send it. */ +function example(name: string): Record { + const found = spec.components.examples[name]?.value; + if (!found) throw new Error(`the spec has no ${name} example`); + return structuredClone(found); +} +const CHANGED_PROBLEM = + spec.components.responses.ServiceTermsConflict?.content[ + "application/problem+json" + ].examples.changed?.value; +if (!CHANGED_PROBLEM) throw new Error("the spec has no changed example"); + +type Start = "toAgree" | "changed" | "none"; +const START_EXAMPLE: Record = { + toAgree: "ServiceTermsToAgreeExample", + changed: "ServiceTermsChangedExample", + none: "ServiceTermsNoneExample", +}; + +/** One OpenBot's server, as far as these screens ask it. */ +class FakeServer { + terms: ServiceTerms; + onboarding: { step: number; completedAt: string | null }; + accepts: unknown[] = []; + termsReads = 0; + /** What reading the terms answers instead, while set: a failure, or a route an older OpenBot lacks. */ + termsAnswer: { status: number; json: unknown } | null = null; + + constructor(start: Start, onboarded = false) { + this.terms = GetServiceTermsResponse.parse( + example(START_EXAMPLE[start]), + ) as ServiceTerms; + this.onboarding = onboarded + ? { step: 1, completedAt: "2026-11-01T09:00:00.000Z" } + : { step: 0, completedAt: null }; + } + + /** A new version is published while the person has the screen open. */ + publish(version: string) { + const current = this.terms.current; + if (!current) throw new Error("no terms to change"); + this.terms = { ...this.terms, current: { ...current, version } }; + this.terms.acceptanceNeeded = this.terms.accepted?.version !== version; + } + + answer(request: Request): { status: number; json: unknown } { + const url = new URL(request.url()); + const path = url.pathname; + const method = request.method(); + if (path === TERMS && method === "GET") { + this.termsReads += 1; + if (this.termsAnswer) return this.termsAnswer; + return { status: 200, json: GetServiceTermsResponse.parse(this.terms) }; + } + if (path === `${TERMS}/accept` && method === "POST") { + expect(request.headers()["idempotency-key"]?.length ?? 0).toBeGreaterThan( + 0, + ); + const body = request.postDataJSON() as Record; + this.accepts.push(body); + const input = AcceptServiceTermsBody.parse(body); + for (const key of Object.keys(body)) + expect(Object.keys(input)).toContain(key); + if (input.version !== this.terms.current?.version) + return { status: 409, json: CHANGED_PROBLEM }; + this.terms = AcceptServiceTermsResponse.parse({ + ...this.terms, + accepted: { + version: input.version, + acceptedAt: "2026-11-21T18:04:00.000Z", + }, + acceptanceNeeded: false, + }) as ServiceTerms; + return { status: 200, json: this.terms }; + } + if (path === ME && method === "GET") + return { + status: 200, + json: { + person: personBody({ + id: "dana", + name: "Dana Whitfield", + email: "dana@example.com", + role: "admin", + onboarding: this.onboarding, + }), + openbotVersion: "v1.1.3", + }, + }; + if (path === `${ME}/onboarding/advance` && method === "POST") { + const { step } = request.postDataJSON() as { step: number }; + this.onboarding = { ...this.onboarding, step }; + return { status: 200, json: { onboarding: this.onboarding } }; + } + if (path === `${ORGANIZATION}/deployment`) + return { + status: 200, + json: { + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }, + }; + if (path === `${ME}/approval-preferences`) + return { + status: 200, + json: { + enabled: false, + autoReview: false, + hostCommands: "ask", + effectiveHostCommands: "ask", + }, + }; + if (path === `${ME}/preferences`) + return { + status: 200, + json: { + messageListEmphasis: "thread", + selfHostBannerDismissed: false, + narration: null, + skin: "openbot", + proactive: "on", + }, + }; + return { status: 404, json: { detail: "Not found." } }; + } +} + +/** The vendored marks as data URIs, as Vite's `import.meta.glob` hands them to `@/lib/marks`. */ +function marksModule(): string { + const dir = join(APP, "..", "shared", "marks"); + const marks = Object.fromEntries( + readdirSync(dir) + .filter((file) => file.endsWith(".svg")) + .map((file) => [ + file.replace(".svg", ""), + `data:image/svg+xml;base64,${readFileSync(join(dir, file)).toString("base64")}`, + ]), + ); + return `const marks = ${JSON.stringify(marks)}; export const markFor = (id) => (id && marks[id]) || null;`; +} + +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "service-terms.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + // The gate's module brings the app behind it, whose chat loads a map library only when a Bot + // draws a map. Nothing here does. + external: ["maplibre-gl"], + plugins: [ + { + name: "marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "marks", + })); + build.onLoad({ filter: /.*/, namespace: "marks" }, () => ({ + contents: marksModule(), + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let script: string; + +beforeAll(async () => { + if (!asked) return; + script = await bundle(); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); +}); + +/** The page at `path`, its server answering from `server`. */ +async function open( + path: string, + server: FakeServer, + engine: string, + theme: Theme, + window: Window, +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const inter = join(packageDir("@fontsource-variable/inter"), "files"); + await page.route(`${ORIGIN}/**`, (route) => { + const where = new URL(route.request().url()).pathname; + if (where === "/screens.js") + return route.fulfill({ contentType: "text/javascript", body: script }); + const font = join(inter, where.split("/").pop() ?? ""); + if (where.startsWith("/files/") && existsSync(font)) + return route.fulfill({ path: font }); + if (where.startsWith("/api/")) { + const { status, json } = server.answer(route.request()); + return route.fulfill({ + status, + json, + headers: + status >= 400 ? { "content-type": "application/problem+json" } : {}, + }); + } + return route.fulfill({ + contentType: "text/html", + body: `
`, + }); + }); + await page.goto(`${ORIGIN}${path}`); + return page; +} + +/** Style the page for every class it draws now: what just opened brings classes of its own. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(250); +} + +async function shoot( + page: Page, + screen: string, + engine: string, + theme: Theme, + window: Window, +) { + if (!shots) return; + await style(page); + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join(shots, `terms-${screen}-${engine}-${theme}-${window.width}.png`), + fullPage: true, + }); +} + +/** What a person would see wrong: sideways scroll, or a control cut off at the side. */ +async function measured(page: Page) { + await style(page); + return page.evaluate(() => { + const inside = (rect: DOMRect) => + rect.left >= -0.5 && rect.right <= innerWidth + 0.5; + const cut = [...document.querySelectorAll("button, a, input")] + .filter((control) => { + const rect = control.getBoundingClientRect(); + // A tickbox's own input is a 1px box out of sight; its control is what shows. + return rect.width > 1 && rect.height > 1; + }) + .filter((control) => !inside(control.getBoundingClientRect())) + .map( + (control) => + control.textContent?.trim() || + control.getAttribute("aria-label") || + control.tagName, + ); + return { sideways: document.documentElement.scrollWidth > innerWidth, cut }; + }); +} + +const FINE = { sideways: false, cut: [] }; +const primary = (page: Page) => page.locator("[data-onboarding-primary]"); +const agree = (page: Page) => + page.getByRole("checkbox", { + name: "I agree to the Terms of Service and Acceptable Use Policy", + }); +/** Tick the box as a person does, by pressing its sentence (not one of the links in it). */ +const tick = (page: Page) => + page.locator("label[for=terms-agree]").click({ position: { x: 4, y: 4 } }); +const heading = (page: Page, name: string) => + page.getByRole("heading", { level: 1, name }).waitFor(); +const at = (page: Page) => new URL(page.url()).pathname; + +describe("where agreeing to the terms goes on to", () => { + test("a page of this app, and nowhere else", () => { + expect(afterTerms("/settings?tab=ai")).toBe("/settings?tab=ai"); + expect(afterTerms("/invitations/abc123")).toBe("/invitations/abc123"); + expect(afterTerms(undefined)).toBe("/"); + expect(afterTerms("https://example.com/")).toBe("/"); + expect(afterTerms("//example.com/")).toBe("/"); + expect(afterTerms("/\\example.com")).toBe("/"); + expect(afterTerms("/terms?next=%2F")).toBe("/"); + }); +}); + +describe.skipIf(!asked)("The terms on OpenBot Cloud", () => { + for (const engine of engines) + test(`a new person agrees before anything else, then onboarding follows, in ${engine}`, async () => { + const server = new FakeServer("toAgree"); + const page = await open("/settings", server, engine, "light", WIDE); + try { + await heading(page, "Agree to the terms"); + expect(at(page)).toBe("/terms"); + expect(new URL(page.url()).searchParams.get("next")).toBe("/settings"); + // Unticked, and Continue waits for it. Sign out is the only other way. + expect(await agree(page).isChecked()).toBe(false); + expect(await primary(page).isDisabled()).toBe(true); + expect( + await page.locator("[data-onboarding-secondary]").textContent(), + ).toBe("Sign out"); + // Both names link to their page, in a new tab. + for (const [name, href] of [ + ["Terms of Service", "https://open.bot/legal/terms"], + ["Acceptable Use Policy", "https://open.bot/legal/acceptable-use"], + ]) { + const link = page.getByRole("link", { name }); + expect(await link.getAttribute("href")).toBe(href); + expect(await link.getAttribute("target")).toBe("_blank"); + } + // Pressing Continue while unticked does nothing. + await primary(page).click({ force: true }); + expect(server.accepts).toEqual([]); + + // Onboarding and home are behind it too. + await page.goto(`${ORIGIN}/onboarding`); + await heading(page, "Agree to the terms"); + expect(at(page)).toBe("/terms"); + await page.goto(`${ORIGIN}/`); + await heading(page, "Agree to the terms"); + + // The sentence is the box's label. + await tick(page); + expect(await agree(page).isChecked()).toBe(true); + expect(await primary(page).isDisabled()).toBe(false); + await primary(page).click(); + await heading(page, "Welcome to OpenBot"); + expect(at(page)).toBe("/onboarding"); + expect(server.accepts).toEqual([{ version: "2026-11-21" }]); + // Agreed: the terms screen sends them on. + await page.goto(`${ORIGIN}/terms`); + await heading(page, "Welcome to OpenBot"); + } finally { + await page.close(); + } + }, 90_000); + + for (const engine of engines) + test(`terms that changed are asked again, then the page they were headed to, in ${engine}`, async () => { + const server = new FakeServer("changed", true); + const page = await open("/settings", server, engine, "light", WIDE); + try { + await heading(page, "The terms have changed"); + expect(at(page)).toBe("/terms"); + expect(await agree(page).isChecked()).toBe(false); + await tick(page); + await primary(page).click(); + await page.locator("[data-app-settings]").waitFor(); + expect(at(page)).toBe("/settings"); + expect(server.accepts).toEqual([{ version: "2027-03-01" }]); + } finally { + await page.close(); + } + }, 60_000); + + for (const engine of engines) + test(`terms that change while the screen is open show the new version, in ${engine}`, async () => { + const server = new FakeServer("toAgree", true); + const page = await open("/", server, engine, "light", WIDE); + try { + await heading(page, "Agree to the terms"); + await tick(page); + server.publish("2027-03-01"); + await primary(page).click(); + const alert = page.getByRole("alert"); + await alert.waitFor(); + expect(await alert.textContent()).toBe( + "The terms have changed since you opened them. Read the new version and agree again.", + ); + // The new version, unticked: the tick was for the one they saw. + await page.waitForFunction( + () => + document + .querySelector("[data-terms-agree]") + ?.getAttribute("aria-checked") === "false", + ); + expect(await primary(page).isDisabled()).toBe(true); + await tick(page); + expect(await alert.count()).toBe(0); + await primary(page).click(); + await page.locator("[data-app-home]").waitFor(); + expect(server.accepts).toEqual([ + { version: "2026-11-21" }, + { version: "2027-03-01" }, + ]); + } finally { + await page.close(); + } + }, 60_000); + + for (const engine of engines) + test(`a forged address to go on to is never followed off the app, in ${engine}`, async () => { + for (const forged of ["https://evil.example/", "//evil.example/"]) { + const server = new FakeServer("toAgree", true); + const page = await open( + `/terms?next=${encodeURIComponent(forged)}`, + server, + engine, + "light", + WIDE, + ); + try { + await heading(page, "Agree to the terms"); + await tick(page); + await primary(page).click(); + await page.locator("[data-app-home]").waitFor(); + expect(new URL(page.url()).origin).toBe(ORIGIN); + expect(at(page)).toBe("/"); + // Opened again once agreed, the terms send them on, never back to the forged address. + await page.goto(`${ORIGIN}/terms?next=${encodeURIComponent(forged)}`); + await page.locator("[data-app-home]").waitFor(); + expect(new URL(page.url()).origin).toBe(ORIGIN); + } finally { + await page.close(); + } + } + }, 60_000); + + for (const engine of engines) + test(`a read that fails holds the person at the terms, with Try again, in ${engine}`, async () => { + const server = new FakeServer("toAgree", true); + server.termsAnswer = { + status: 503, + json: { detail: "Service unavailable.", status: 503 }, + }; + const page = await open("/settings", server, engine, "light", WIDE); + try { + await heading(page, "Agree to the terms"); + expect(at(page)).toBe("/terms"); + await page + .getByText("Couldn't load the terms. Try again to continue.") + .waitFor(); + expect(await agree(page).count()).toBe(0); + expect(await primary(page).isDisabled()).toBe(true); + server.termsAnswer = null; + await page.getByRole("button", { name: "Try again" }).click(); + await page.locator("label[for=terms-agree]").waitFor(); + await tick(page); + await primary(page).click(); + await page.locator("[data-app-settings]").waitFor(); + expect(server.accepts).toEqual([{ version: "2026-11-21" }]); + } finally { + await page.close(); + } + }, 60_000); +}); + +describe.skipIf(!asked)("No terms to agree to", () => { + for (const engine of engines) + test(`a self-hosted OpenBot never shows the terms, in ${engine}`, async () => { + const server = new FakeServer("none", true); + const page = await open("/settings", server, engine, "light", WIDE); + try { + await page.locator("[data-app-settings]").waitFor(); + expect(at(page)).toBe("/settings"); + // Asked for by its address, it sends them home. + await page.goto(`${ORIGIN}/terms`); + await page.locator("[data-app-home]").waitFor(); + expect(at(page)).toBe("/"); + expect(server.accepts).toEqual([]); + } finally { + await page.close(); + } + }, 60_000); + + for (const engine of engines) + test(`a new person on a self-hosted OpenBot goes to onboarding as before, in ${engine}`, async () => { + const server = new FakeServer("none"); + const page = await open("/", server, engine, "light", WIDE); + try { + await heading(page, "Welcome to OpenBot"); + expect(at(page)).toBe("/onboarding"); + } finally { + await page.close(); + } + }, 60_000); + + for (const engine of engines) + test(`an OpenBot older than the terms never shows them, in ${engine}`, async () => { + const server = new FakeServer("toAgree", true); + // A route it doesn't have: a 404 that isn't about the person. + server.termsAnswer = { status: 404, json: { detail: "Not found." } }; + const page = await open("/settings", server, engine, "light", WIDE); + try { + await page.locator("[data-app-settings]").waitFor(); + expect(at(page)).toBe("/settings"); + expect(server.termsReads).toBeGreaterThan(0); + } finally { + await page.close(); + } + }, 60_000); +}); + +// The screen, light and dark, wide and at a phone's width, its changed version, and the Welcome +// step after it, beside onboarding's Welcome from before to compare. +test.skipIf(!asked || !shots)( + "screenshots of the terms, beside Welcome", + async () => { + for (const engine of engines) + for (const theme of THEMES) + for (const window of [WIDE, PHONE]) { + const before = await open( + "/", + new FakeServer("none"), + engine, + theme, + window, + ); + try { + await heading(before, "Welcome to OpenBot"); + await shoot(before, "compare-welcome", engine, theme, window); + } finally { + await before.close(); + } + + const page = await open( + "/", + new FakeServer("toAgree"), + engine, + theme, + window, + ); + try { + await heading(page, "Agree to the terms"); + expect(await measured(page)).toEqual(FINE); + await shoot(page, "screen", engine, theme, window); + await tick(page); + await shoot(page, "screen-ticked", engine, theme, window); + await primary(page).click(); + await heading(page, "Welcome to OpenBot"); + await shoot(page, "after-welcome", engine, theme, window); + } finally { + await page.close(); + } + + const changed = await open( + "/", + new FakeServer("changed", true), + engine, + theme, + window, + ); + try { + await heading(changed, "The terms have changed"); + expect(await measured(changed)).toEqual(FINE); + await shoot(changed, "changed", engine, theme, window); + } finally { + await changed.close(); + } + } + }, + 600_000, +); From b73872942f20f23ea3c8e40f3b73defa4bccc70e Mon Sep 17 00:00:00 2001 From: David McKay Date: Sat, 21 Nov 2026 17:38:06 -0800 Subject: [PATCH 2/2] Onboarding: keep a step's last line clear of the fade above its buttons On a phone the buttons are pinned to the bottom with a 32px fade above them, which says the step scrolls on. Scrolled to the end there is nothing more, yet the step's last line still sat under the fade: Welcome's carousel dots, and the terms step's, were half hidden behind the first button. The footer now keeps 32px above it on a phone, the fade's own height, so the last line stops above it. --- .../onboarding/onboarding-frame.tsx | 6 +- app/tests/service-terms.test.tsx | 94 +++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) diff --git a/app/src/components/onboarding/onboarding-frame.tsx b/app/src/components/onboarding/onboarding-frame.tsx index 07d5d6558c..11969d7a1c 100644 --- a/app/src/components/onboarding/onboarding-frame.tsx +++ b/app/src/components/onboarding/onboarding-frame.tsx @@ -178,8 +178,12 @@ export function OnboardingFrame({ * On a phone, a step taller than the screen scrolls under the buttons rather than being cut * at them: the fade above says there is more. On a desktop they sit at the bottom of the * pane, under the row that takes up the space between them and the sentence. + * + * The 32px above the buttons on a phone is the fade's own height. Scrolled to the end there + * is nothing more, so the step's last line (Welcome's carousel dots) stops above the fade + * rather than half hidden in it. */} -