diff --git a/api/openapi.yaml b/api/openapi.yaml index 75a7eb3595..e5492053ab 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -22580,6 +22580,55 @@ paths: $ref: '#/components/responses/ServerError' default: $ref: '#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/business-events: + parameters: + - $ref: '#/components/parameters/OrganizationId' + post: + tags: + - Product events + operationId: recordBusinessEvent + summary: Record the caller opening OpenBot for Business, or booking a call in it + description: 'Tell OpenBot that the caller opened OpenBot for Business in the app, or booked a call in its calendar, and from which screen. The booking itself is Calendly''s record, which keeps the same screen as its `utm_content`; this counts the opening and the booking by that place, so the two read together. It is best effort: a client sends one per opening or booking and waits on nothing. Each accepted report is sent, and its event id repeats for the same person, organization, place, surface and UTC day, so distinct ids count each once a day; Calendly''s records stay the count of bookings. The event counts for the caller and names nothing else: never the time booked or anything typed into the calendar. Where this OpenBot has product telemetry switched off, it is accepted and dropped.' + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BusinessEvent' + examples: + opened: + $ref: '#/components/examples/BusinessOpened' + responses: + '204': + description: The event is accepted. + headers: + X-Request-Id: + $ref: '#/components/headers/RequestId' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/OrganizationNotFound' + '409': + $ref: '#/components/responses/IdempotencyConflict' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + default: + $ref: '#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/settings/learning: parameters: - $ref: '#/components/parameters/OrganizationId' @@ -47263,6 +47312,37 @@ components: - web - desktop description: Where the caller saw or answered it. + BusinessEvent: + type: object + description: What the caller did with OpenBot for Business in the app, and where. Names nothing about the person, who is the caller, and nothing about the call booked. + additionalProperties: false + required: + - action + - place + - surface + properties: + action: + type: string + enum: + - opened + - booked + description: 'opened when one of the app''s entries opened OpenBot for Business, or Book a demo put the calendar on onboarding''s step; booked when its calendar said a call was booked in it: Calendly''s own message, from Calendly''s origin and the calendar''s frame.' + place: + type: string + enum: + - account_menu + - home + - admin + - computer_line + - self_host_banner + - onboarding + description: 'The screen that put OpenBot for Business in front of the caller, as its calendar''s `utm_content` names it: account_menu for the account menu''s entry, home for the home page''s Meet OpenBot for Business, admin for an Admin page that applies only to a team, computer_line for a Bot''s line about a computer of its own, self_host_banner for the self-hosting bar''s Book a call, and onboarding for onboarding''s Book a demo step. OpenBot Cloud''s sign-in screen is not one: nobody is signed in there.' + surface: + type: string + enum: + - web + - desktop + description: Where the caller opened it or booked, in a browser or in OpenBot Desktop's window. LearningSpaceId: type: string description: A Learning space's id in the backend (its container). @@ -64897,6 +64977,12 @@ components: action: clicked place: card surface: desktop + BusinessOpened: + summary: The caller opened OpenBot for Business from the account menu, in OpenBot Desktop. + value: + action: opened + place: account_menu + surface: desktop LearningConfigurationExample: summary: Learning on, every Bot learning into the space OpenBot assigned, people reviewing their own. value: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index f4e606bb15..633f8361b3 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -541,6 +541,7 @@ paths: /api/v2/organizations/{organizationId}/app-errors: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1app-errors' } /api/v2/app-errors: { $ref: './conversations.yaml#/paths/~1api~1v2~1app-errors' } /api/v2/organizations/{organizationId}/nudge-events: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1nudge-events' } + /api/v2/organizations/{organizationId}/business-events: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1business-events' } /api/v2/organizations/{organizationId}/settings/learning: { $ref: './learning.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1settings~1learning' } /api/v2/organizations/{organizationId}/settings/learning/create-container: { $ref: './learning.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1settings~1learning~1create-container' } /api/v2/organizations/{organizationId}/settings/learning/overview: { $ref: './learning.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1settings~1learning~1overview' } diff --git a/api/openapi/conversations.yaml b/api/openapi/conversations.yaml index 62e6869b02..bd00f3306d 100644 --- a/api/openapi/conversations.yaml +++ b/api/openapi/conversations.yaml @@ -2221,6 +2221,67 @@ paths: $ref: './common.yaml#/components/responses/ServerError' default: $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/business-events: + parameters: + - $ref: './common.yaml#/components/parameters/OrganizationId' + post: + tags: + - Product events + operationId: recordBusinessEvent + summary: Record the caller opening OpenBot for Business, or booking a call in it + description: >- + Tell OpenBot that the caller opened OpenBot for Business in the app, + or booked a call in its calendar, and from which screen. The booking + itself is Calendly's record, which keeps the same screen as its + `utm_content`; this counts the opening and the booking by that place, + so the two read together. It is best effort: a client sends one per + opening or booking and waits on nothing. Each accepted report is + sent, and its event id repeats for the same person, organization, + place, surface and UTC day, so distinct ids count each once a day; + Calendly's records stay the count of bookings. The event counts for the + caller and names nothing else: never the time booked or anything + typed into the calendar. Where this OpenBot has product telemetry + switched off, it is accepted and dropped. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BusinessEvent' + examples: + opened: + $ref: '#/components/examples/BusinessOpened' + responses: + '204': + description: The event is accepted. + headers: + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '403': + $ref: './common.yaml#/components/responses/Forbidden' + '404': + $ref: './common.yaml#/components/responses/OrganizationNotFound' + '409': + $ref: './common.yaml#/components/responses/IdempotencyConflict' + '413': + $ref: './common.yaml#/components/responses/PayloadTooLarge' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' components: parameters: ConversationLimit: @@ -2782,6 +2843,53 @@ components: - web - desktop description: Where the caller saw or answered it. + BusinessEvent: + type: object + description: >- + What the caller did with OpenBot for Business in the app, and where. + Names nothing about the person, who is the caller, and nothing about + the call booked. + additionalProperties: false + required: + - action + - place + - surface + properties: + action: + type: string + enum: + - opened + - booked + description: >- + opened when one of the app's entries opened OpenBot for Business, + or Book a demo put the calendar on onboarding's step; booked when + its calendar said a call was booked in it: Calendly's own message, + from Calendly's origin and the calendar's frame. + place: + type: string + enum: + - account_menu + - home + - admin + - computer_line + - self_host_banner + - onboarding + description: >- + The screen that put OpenBot for Business in front of the caller, + as its calendar's `utm_content` names it: account_menu for the + account menu's entry, home for the home page's Meet OpenBot for + Business, admin for an Admin page that applies only to a team, + computer_line for a Bot's line about a computer of its own, + self_host_banner for the self-hosting bar's Book a call, and + onboarding for onboarding's Book a demo step. OpenBot Cloud's + sign-in screen is not one: nobody is signed in there. + surface: + type: string + enum: + - web + - desktop + description: Where the caller opened it or booked, in a browser or in + OpenBot Desktop's window. AppError: type: object description: An error the app hit and did not handle, as the app saw it. @@ -4205,6 +4313,9 @@ components: NudgeClicked: summary: "The caller opened OpenBot's repository from the star card, in OpenBot Desktop." value: {"nudge": "star-on-github", "action": "clicked", "place": "card", "surface": "desktop"} + BusinessOpened: + summary: "The caller opened OpenBot for Business from the account menu, in OpenBot Desktop." + value: {"action": "opened", "place": "account_menu", "surface": "desktop"} AppErrorBoundary: summary: "An error the web app's error screen caught." value: {"source": "error_boundary", "type": "TypeError", "message": "Cannot read properties of undefined (reading 'title')", "stack": "TypeError: Cannot read properties of undefined (reading 'title')\n at BotCard (/assets/route-app-secondary.js:12:345)", "surface": "web", "appVersion": "1.1.0-rc.2"} diff --git a/app/src/components/edition/team-features-dialog.tsx b/app/src/components/edition/team-features-dialog.tsx index 3e6d1542de..91d9f63cb7 100644 --- a/app/src/components/edition/team-features-dialog.tsx +++ b/app/src/components/edition/team-features-dialog.tsx @@ -39,7 +39,9 @@ import type { NavigationItem } from "@/lib/navigation"; import { type AppBusinessPlace, BUSINESS_URL, + recordBusiness, } from "@/lib/openbot-for-business"; +import { onOrganizationChange } from "@/lib/organizations/current"; import { cn } from "@/lib/utils"; import { BOOK_A_DEMO_LINE, @@ -91,8 +93,9 @@ export const TEAM_FEATURES = TEAM_FEATURE_GROUPS.flatMap( * skin (the navigation, the home page's link, a Bot's computer line, the self-host banner) can open * it without a provider of its own. * - * With where it was opened from, which its calendar is tagged with and counts (`BookingCalendar`). - * The calendar is drawn only while the dialog is open, so it reads the entry that opened it. + * With where it was opened from, which its calendar is tagged with (`BookingCalendar`) and the + * opening and a call booked in it are counted by (`recordBusiness`). The calendar is drawn only + * while the dialog is open, so it reads the entry that opened it. */ let open = false; let openedFrom: AppBusinessPlace = "account_menu"; @@ -103,7 +106,24 @@ function setOpen(next: boolean) { for (const listener of listeners) listener(); } +/* + * Closed when the person starts working in another organization, before React draws it. The layout + * holding the dialog is built again for the new one (`OrganizationBoundary`), and its copy read this + * flag still open: it drew the dialog, with a calendar of its own that counted a booking there, until + * the old copy's unmount closed it a moment later. The same organization again is no change. + */ +onOrganizationChange(() => setOpen(false)); + +/* + * The opening is counted here, as the entry is pressed, and never as the dialog draws: so StrictMode's + * second run of an effect, or the dialog drawn again, counts nothing more. Closed and opened again is + * a new opening; an entry reached while the dialog is already open is not, and changes nothing: the + * place stays the first entry's for the dialog's life, so its count, its calendar's `utm_content` and + * a call booked in it name the same entry, even when a second is reached before the dialog draws. + */ export function openTeamFeatures(from: AppBusinessPlace) { + if (open) return; + void recordBusiness("opened", from); openedFrom = from; setOpen(true); } @@ -187,8 +207,15 @@ function BookDemo() { const [place] = useState(() => openedFrom); const [failed, setFailed] = useState(false); const fail = useCallback(() => setFailed(true), []); - // Calendly shows its own confirmation in the frame; there is nothing more to say here. - const booked = useCallback(() => {}, []); + /* + * Calendly shows its own confirmation in the frame; there is nothing more to say here, only the + * call to count, by the entry that opened the dialog. `BookingCalendar` calls this only for + * Calendly's own message, from its origin and this calendar's frame. + */ + const booked = useCallback( + () => void recordBusiness("booked", place), + [place], + ); return (
+ >[0], + ) => Promise | void), + options?: RequestHandlerOptions, +) => { + return http.post<{ organizationId: string }, BusinessEvent>( + "*/api/v2/organizations/:organizationId/business-events", + async ( + info: Parameters< + HttpResponseResolver<{ organizationId: string }, BusinessEvent> + >[0], + ) => { + if (typeof overrideResponse === "function") { + await overrideResponse(info); + } + + return new HttpResponse(null, { status: 204 }); + }, + options, + ); +}; export const getProductEventsMock = () => [ getRecordProductEventMockHandler(), getRecordAppErrorMockHandler(), getRecordSignedOutAppErrorMockHandler(), getRecordNudgeEventMockHandler(), + getRecordBusinessEventMockHandler(), ]; diff --git a/app/src/lib/api/generated/product-events/product-events.ts b/app/src/lib/api/generated/product-events/product-events.ts index 99a4c08d8f..4c49c529f1 100644 --- a/app/src/lib/api/generated/product-events/product-events.ts +++ b/app/src/lib/api/generated/product-events/product-events.ts @@ -11,6 +11,7 @@ import type { import type { AppError, + BusinessEvent, ForbiddenResponse, IdempotencyConflictResponse, InvalidRequestResponse, @@ -19,6 +20,7 @@ import type { PayloadTooLargeResponse, ProductEvent, RecordAppErrorHeaders, + RecordBusinessEventHeaders, RecordNudgeEventHeaders, RecordProductEventHeaders, RecordSignedOutAppErrorHeaders, @@ -631,3 +633,157 @@ export const useRecordNudgeEvent = < > => { return useMutation(getRecordNudgeEventMutationOptions(options), queryClient); }; +export const getRecordBusinessEventUrl = (organizationId: string) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/business-events`; +}; + +/** + * Tell OpenBot that the caller opened OpenBot for Business in the app, or booked a call in its calendar, and from which screen. The booking itself is Calendly's record, which keeps the same screen as its `utm_content`; this counts the opening and the booking by that place, so the two read together. It is best effort: a client sends one per opening or booking and waits on nothing. Each accepted report is sent, and its event id repeats for the same person, organization, place, surface and UTC day, so distinct ids count each once a day; Calendly's records stay the count of bookings. The event counts for the caller and names nothing else: never the time booked or anything typed into the calendar. Where this OpenBot has product telemetry switched off, it is accepted and dropped. + * @summary Record the caller opening OpenBot for Business, or booking a call in it + */ +export const recordBusinessEvent = async ( + organizationId: string, + businessEvent: BusinessEvent, + headers: RecordBusinessEventHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest(getRecordBusinessEventUrl(organizationId), { + ...options, + method: "POST", + headers: { + "Content-Type": "application/json", + ...headers, + ...getHeaders(options?.headers), + }, + body: JSON.stringify(businessEvent), + }); +}; + +export const getRecordBusinessEventMutationKey = () => + ["recordBusinessEvent"] as const; + +export const getRecordBusinessEventMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | OrganizationNotFoundResponse + | IdempotencyConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + RecordBusinessEventMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + RecordBusinessEventMutationVariables, + TContext +> => { + const mutationKey = getRecordBusinessEventMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + RecordBusinessEventMutationVariables + > = (props) => { + const { organizationId, data, headers } = props ?? {}; + + return recordBusinessEvent(organizationId, data, headers, requestOptions); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type RecordBusinessEventMutationResult = NonNullable< + Awaited> +>; +export type RecordBusinessEventMutationBody = BusinessEvent; +export type RecordBusinessEventMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | OrganizationNotFoundResponse + | IdempotencyConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse; +export type RecordBusinessEventMutationVariables = { + organizationId: string; + data: BusinessEvent; + headers: RecordBusinessEventHeaders; +}; + +/** + * @summary Record the caller opening OpenBot for Business, or booking a call in it + */ +export const useRecordBusinessEvent = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | OrganizationNotFoundResponse + | IdempotencyConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + RecordBusinessEventMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + RecordBusinessEventMutationVariables, + TContext +> => { + return useMutation( + getRecordBusinessEventMutationOptions(options), + queryClient, + ); +}; diff --git a/app/src/lib/api/generated/product-events/product-events.zod.ts b/app/src/lib/api/generated/product-events/product-events.zod.ts index 96e7e21885..58b14c55cf 100644 --- a/app/src/lib/api/generated/product-events/product-events.zod.ts +++ b/app/src/lib/api/generated/product-events/product-events.zod.ts @@ -288,3 +288,60 @@ export const RecordNudgeEventBody = zod ); export const RecordNudgeEventResponse = zod.void(); + +/** + * Tell OpenBot that the caller opened OpenBot for Business in the app, or booked a call in its calendar, and from which screen. The booking itself is Calendly's record, which keeps the same screen as its `utm_content`; this counts the opening and the booking by that place, so the two read together. It is best effort: a client sends one per opening or booking and waits on nothing. Each accepted report is sent, and its event id repeats for the same person, organization, place, surface and UTC day, so distinct ids count each once a day; Calendly's records stay the count of bookings. The event counts for the caller and names nothing else: never the time booked or anything typed into the calendar. Where this OpenBot has product telemetry switched off, it is accepted and dropped. + * @summary Record the caller opening OpenBot for Business, or booking a call in it + */ + +export const RecordBusinessEventParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), +}); + +export const recordBusinessEventHeaderIdempotencyKeyMax = 128; + +export const RecordBusinessEventHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(recordBusinessEventHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const RecordBusinessEventBody = zod + .object({ + action: zod + .enum(["opened", "booked"]) + .describe( + "opened when one of the app's entries opened OpenBot for Business, or Book a demo put the calendar on onboarding's step; booked when its calendar said a call was booked in it: Calendly's own message, from Calendly's origin and the calendar's frame.", + ), + place: zod + .enum([ + "account_menu", + "home", + "admin", + "computer_line", + "self_host_banner", + "onboarding", + ]) + .describe( + "The screen that put OpenBot for Business in front of the caller, as its calendar's `utm_content` names it: account_menu for the account menu's entry, home for the home page's Meet OpenBot for Business, admin for an Admin page that applies only to a team, computer_line for a Bot's line about a computer of its own, self_host_banner for the self-hosting bar's Book a call, and onboarding for onboarding's Book a demo step. OpenBot Cloud's sign-in screen is not one: nobody is signed in there.", + ), + surface: zod + .enum(["web", "desktop"]) + .describe( + "Where the caller opened it or booked, in a browser or in OpenBot Desktop's window.", + ), + }) + .describe( + "What the caller did with OpenBot for Business in the app, and where. Names nothing about the person, who is the caller, and nothing about the call booked.", + ); + +export const RecordBusinessEventResponse = zod.void(); diff --git a/app/src/lib/openbot-for-business.ts b/app/src/lib/openbot-for-business.ts index 3bf43ffb31..e1e6826130 100644 --- a/app/src/lib/openbot-for-business.ts +++ b/app/src/lib/openbot-for-business.ts @@ -1,6 +1,15 @@ +import type { AppBusinessPlace } from "@openbot/shared/openbot-for-business"; +import type { BusinessEvent } from "@/lib/api/generated/model"; +import { recordBusinessEvent } from "@/lib/api/generated/product-events/product-events"; +import { idempotencyKey } from "@/lib/api/request"; +import { ClientError } from "@/lib/client"; +import { desktopShell } from "@/lib/desktop/shell"; +import { organizationId } from "@/lib/organizations/current"; + /** * OpenBot for Business's page, its Calendly event and the calendar's address. They live in - * `@openbot/shared/openbot-for-business`, which Desktop's first screen reads too. + * `@openbot/shared/openbot-for-business`, which Desktop's first screen reads too. Counting it is + * the web app's own: {@link recordBusiness}. */ export { type AppBusinessPlace, @@ -10,3 +19,46 @@ export { BUSINESS_URL, bookingCalendarSrc, } from "@openbot/shared/openbot-for-business"; + +/** + * What a person did with OpenBot for Business: `BusinessEvent.action` in + * api/openapi/conversations.yaml, read from the client generated from it, so an action the spec + * adds or drops is the app's too. + */ +export type BusinessAction = BusinessEvent["action"]; + +/** + * Count OpenBot for Business opened from an entry, or a call booked in its calendar, by the place + * it was opened from: the same place its calendar's address carries as `utm_content`, so a booking + * Calendly keeps and these counts name the same screen. Best effort, like a nudge's count: the + * server works out who, and a count that does not arrive changes nothing on screen. Never throws, + * so a caller fires and forgets; with keepalive, so a count made as the page goes still leaves. + * + * Nothing is sent from OpenBot Cloud's sign-in screen (`sign_in`): nobody is signed in there, and + * the count is the signed-in person's, in the organization they are working in. + */ +export async function recordBusiness( + action: BusinessAction, + place: AppBusinessPlace, +): Promise { + if (place === "sign_in") return; + try { + await recordBusinessEvent( + organizationId(), + { + action, + place, + surface: desktopShell() === null ? "web" : "desktop", + }, + { "Idempotency-Key": idempotencyKey() }, + { keepalive: true }, + ); + } catch (error) { + if (error instanceof ClientError) + console.warn( + "OpenBot for Business telemetry was not accepted.", + error.status, + ); + else console.warn("OpenBot for Business telemetry could not be delivered."); + } +} diff --git a/app/src/routes/_authed/onboarding.tsx b/app/src/routes/_authed/onboarding.tsx index 8f25abafc8..e012e8d239 100644 --- a/app/src/routes/_authed/onboarding.tsx +++ b/app/src/routes/_authed/onboarding.tsx @@ -38,7 +38,7 @@ import { advanceOnboardingMutationOptions, completeOnboardingMutationOptions, } from "@/lib/onboarding/mutations"; -import { BUSINESS_URL } from "@/lib/openbot-for-business"; +import { BUSINESS_URL, recordBusiness } from "@/lib/openbot-for-business"; import { setupChecklistQueryOptions } from "@/lib/setup/queries"; import { queryClient } from "@/query-client"; @@ -194,7 +194,11 @@ function useBookDemoStep(): OnboardingStep { const [failed, setFailed] = React.useState(false); const [booked, setBooked] = React.useState(false); const fail = React.useCallback(() => setFailed(true), []); - const book = React.useCallback(() => setBooked(true), []); + // A call booked in the calendar, counted from onboarding (`recordBusiness`), as the dialog's is. + const book = React.useCallback(() => { + setBooked(true); + void recordBusiness("booked", "onboarding"); + }, []); const value: OnboardingStep = { id: "selfhost", title: "OpenBot for Business", @@ -210,7 +214,15 @@ function useBookDemoStep(): OnboardingStep { ), demo: () => , primaryLabel: "Book a demo", - onPrimary: () => setCalendar(true), + /* + * The step's opening, counted from onboarding (`recordBusiness`): Book a demo puts the calendar + * on screen, as an entry to the dialog does. The step itself is shown to every local evaluator + * unasked, so it is not one. + */ + onPrimary: () => { + setCalendar(true); + void recordBusiness("opened", "onboarding"); + }, secondary: { label: "Not now" }, }; if (!calendar) return value; diff --git a/app/tests/app-navigation.test.tsx b/app/tests/app-navigation.test.tsx index a9f1e05648..5be3f40b3b 100644 --- a/app/tests/app-navigation.test.tsx +++ b/app/tests/app-navigation.test.tsx @@ -57,6 +57,19 @@ class OfflineWebSocket extends EventTarget { } const originalFetch = globalThis.fetch; + +/** + * Opening OpenBot for Business counts the opening (`recordBusiness`). The count is answered as the + * server answers it, an empty 204, so the console stays quiet; what is counted is + * business-events.test.tsx's to check. Everything else is still not served. + */ +function notServed(input: RequestInfo | URL): Response { + return new URL(String(input), "http://localhost/").pathname.endsWith( + "/business-events", + ) + ? new Response(null, { status: 204 }) + : Response.json({ error: "not served" }, { status: 404 }); +} const originalWebSocket = globalThis.WebSocket; const clients: QueryClient[] = []; @@ -70,7 +83,7 @@ beforeAll(() => { }); beforeEach(() => { globalThis.fetch = Object.assign( - async () => Response.json({ error: "not served" }, { status: 404 }), + async (input: RequestInfo | URL) => notServed(input), { preconnect: originalFetch.preconnect }, ); }); @@ -120,7 +133,7 @@ function renderSidebar( async (input: RequestInfo | URL) => new URL(String(input), "http://localhost/").pathname === ME_PATH ? meResponse({ user: person, ...me }) - : Response.json({ error: "not served" }, { status: 404 }), + : notServed(input), { preconnect: originalFetch.preconnect }, ); } else { diff --git a/app/tests/business-events.test.tsx b/app/tests/business-events.test.tsx new file mode 100644 index 0000000000..4cd3904ea3 --- /dev/null +++ b/app/tests/business-events.test.tsx @@ -0,0 +1,909 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + spyOn, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import type { UserPreferences } from "@openbot/shared/user-preferences"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { + act, + cleanup, + fireEvent, + render, + waitFor, +} from "@testing-library/react"; +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { type ReactNode, StrictMode } from "react"; +import { CloudSignIn } from "@/components/auth/cloud-sign-in"; +import { BusinessLink } from "@/components/edition/business-link"; +import { ForATeam } from "@/components/edition/for-a-team"; +import { + BusinessComputerLink, + NavigationTarget, + navigationRender, + openTeamFeatures, + TeamFeaturesDialog, +} from "@/components/edition/team-features-dialog"; +import { SelfHostBanner } from "@/components/layout/self-host-banner"; +import { OrganizationBoundary } from "@/components/organizations/organization-boundary"; +import { BusinessEventPlace } from "@/lib/api/generated/model"; +import { getRecordBusinessEventMockHandler } from "@/lib/api/generated/product-events/product-events.msw"; +import { + RecordBusinessEventBody, + RecordBusinessEventHeader, +} from "@/lib/api/generated/product-events/product-events.zod"; +import { authKeys } from "@/lib/auth/queries"; +import { deploymentKeys } from "@/lib/deployment/queries"; +import { navigationFor } from "@/lib/navigation"; +import type { AppBusinessPlace } from "@/lib/openbot-for-business"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { userPreferencesQueryOptions } from "@/lib/settings/message-list"; +import { settleReactWork } from "./settle-react-work"; + +/* + * OPENBOT FOR BUSINESS, OPENED AND BOOKED, COUNTED IN THE APP. Every entry to the OpenBot for + * Business dialog tagged its calendar with where it was opened from, and Calendly kept the tag on a + * booking, but nothing counted the opening, and the dialog's booked handler did nothing. Each + * signed-in entry now sends one `opened` as it is pressed, and a call booked in the calendar sends + * one `booked`, to `recordBusinessEvent`, by the place that opened it. + * + * Against the API's own contract: the requests are answered by the handler generated from + * api/openapi.yaml, at the path and with the names the spec gives (`getRecordBusinessEventMockHandler`), + * and every body is held to the spec's schema with nothing else allowed in it + * (`RecordBusinessEventBody`, strict). Anything else the page asks for is a stray, and fails the test. + */ + +/** One request the spec's handler answered: the organization in its path, its body and its key. */ +type Sent = { organizationId: string; body: unknown; key: string | null }; + +const sent: Sent[] = []; +const strays: string[] = []; +/** What each request to the API was sent with, read on its way out: keepalive is not on the Request msw hands a handler. */ +const inits: { url: string; keepalive: boolean | undefined }[] = []; + +const server = setupServer( + getRecordBusinessEventMockHandler(async ({ request, params }) => { + sent.push({ + organizationId: params.organizationId, + body: await request.json(), + key: request.headers.get("Idempotency-Key"), + }); + }), + http.all("*", ({ request }) => { + strays.push(`${request.method} ${new URL(request.url).pathname}`); + return new HttpResponse(null, { status: 404 }); + }), +); + +/** The spec's own path for the count, from its generated handler, for a test that answers it otherwise. */ +const BUSINESS_EVENTS_PATH = getRecordBusinessEventMockHandler().info.path; + +let realFetch: typeof fetch; + +// The dialog's booking calendar keeps its address but never fetches it: no test reaches Calendly. +beforeAll(() => { + GlobalRegistrator.register({ + url: "http://openbot.invalid/", + settings: { navigation: { disableChildFrameNavigation: true } }, + }); + server.listen({ onUnhandledRequest: "error" }); + realFetch = globalThis.fetch; + globalThis.fetch = Object.assign( + (input: RequestInfo | URL, init?: RequestInit) => { + inits.push({ url: String(input), keepalive: init?.keepalive }); + return realFetch(input, init); + }, + { preconnect: realFetch.preconnect }, + ); +}); +beforeEach(() => { + sent.length = 0; + strays.length = 0; + inits.length = 0; + sessionStorage.clear(); +}); +afterEach(async () => { + cleanup(); + await sentAll(); + server.resetHandlers(); + delete (window as unknown as Record).__TAURI_INTERNALS__; + expect(strays).toEqual([]); +}); +afterAll(async () => { + globalThis.fetch = realFetch; + server.close(); + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +/** + * Long enough for any request the page started to have reached the server and been answered. A + * count is sent as the entry is pressed, so a second one would be on its way by now. + */ +async function sentAll() { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 60)); + }); +} + +/** The bodies sent, each held to the spec's schema with nothing else in it. */ +function bodies() { + return sent.map((request) => + RecordBusinessEventBody.strict().parse(request.body), + ); +} + +/** + * A signed-in person in the personal edition, whose answers every entry needs are already in, so + * drawing one asks the server for nothing: the only requests are the counts. + */ +function signedIn() { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity } }, + }); + client.setQueryData(authKeys.currentUser(), { + id: "person-1", + email: "person@example.test", + name: "Person", + role: "admin", + }); + client.setQueryData(deploymentKeys.capabilities(), { + generativeUi: false, + selfHostBanner: true, + localEvaluation: true, + edition: "personal", + transcription: false, + voice: false, + }); + const preferences: UserPreferences = { + messageListEmphasis: "thread", + selfHostBannerDismissed: false, + dismissedNotices: [], + narration: null, + skin: "openbot", + proactive: "on", + }; + client.setQueryData( + userPreferencesQueryOptions("person-1").queryKey, + preferences, + ); + return client; +} + +/** + * The signed-in layout's one dialog, beside the entry that opens it. `redraw` draws it again from + * new elements, built afresh each time, as a parent's render would: handed the same element objects, + * React could skip the render the test means to make. + */ +function draw(entry: () => ReactNode, { strict = false } = {}) { + const client = signedIn(); + const tree = () => { + const page = ( + + {entry()} + + + ); + return strict ? {page} : page; + }; + const view = render(tree()); + return Object.assign(view, { redraw: () => view.rerender(tree()) }); +} + +/** The account menu's OpenBot for Business entry, as the personal edition lists it. */ +function accountMenuItem() { + const item = navigationFor("admin", "personal").find( + (entry) => entry.kind === "dialog", + ); + if (!item) throw new Error("no OpenBot for Business entry"); + return item; +} + +type SignedInPlace = Exclude; + +/** + * Every entry in the signed-in app that opens the dialog (each caller of `openTeamFeatures`), with + * the button somebody presses and the place it is counted by. The account menu's entry is drawn two + * ways, as a component and as a menu item's `render`, and every skin goes through one of them. + */ +const ENTRIES: [ + string, + { place: SignedInPlace; button: string; entry: () => ReactNode }, +][] = [ + [ + "the account menu's entry, as a component", + { + place: "account_menu", + button: "OpenBot for Business", + entry: () => ( + + {accountMenuItem().label} + + ), + }, + ], + [ + "the account menu's entry, as a menu item's render", + { + place: "account_menu", + button: "OpenBot for Business", + entry: () => + navigationRender(accountMenuItem(), { + children: accountMenuItem().label, + }), + }, + ], + [ + "the home page's Meet OpenBot for Business", + { + place: "home", + button: "Meet OpenBot for Business", + entry: () => , + }, + ], + [ + "an Admin page that applies only to a team", + { + place: "admin", + button: "Meet OpenBot for Business", + entry: () => , + }, + ], + [ + "a Bot's line about a computer of its own", + { + place: "computer_line", + button: "Give each Bot its own computer with OpenBot for Business.", + entry: () => , + }, + ], + [ + "the self-hosting bar's Book a call", + { + place: "self_host_banner", + button: "Book a call", + entry: () => , + }, + ], +]; + +/** The booking calendar's frame inside the dialog. */ +function calendarFrame(view: ReturnType) { + const frame = view.baseElement.querySelector( + '[data-booking-calendar] iframe[title="Booking calendar"]', + ); + if (!frame) throw new Error("no booking calendar"); + return frame; +} + +/** The place the dialog's calendar is tagged with (`utm_content`), which Calendly keeps on a booking. */ +function calendarPlace(view: ReturnType) { + return new URL(calendarFrame(view).src).searchParams.get("utm_content"); +} + +/** A message to this window, as Calendly posts one: from `origin`, by `source`. */ +function calendly( + event: string, + origin: string, + source: MessageEventSource | null, + payload: object = {}, +) { + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { event, payload }, + origin, + source, + }), + ); + }); +} + +/** + * What `calendly.event_scheduled` carries, as Calendly documents it: the booked event and the + * invitee, by their addresses in Calendly's API. Synthetic. The app reads only the message's + * `event`, so nothing of it may reach a count. + */ +const SCHEDULED_PAYLOAD = { + event: { uri: "https://api.calendly.test/scheduled_events/SYNTHETIC-EVENT" }, + invitee: { + uri: "https://api.calendly.test/scheduled_events/SYNTHETIC-EVENT/invitees/SYNTHETIC-INVITEE", + }, +}; + +async function opened(view: ReturnType) { + return view.findByRole("dialog", { name: "OpenBot for Business" }); +} + +describe("opening OpenBot for Business", () => { + test.each(ENTRIES)( + "%s sends one opened, by its place, at the spec's path, with keepalive and a key", + async (_, { place, button, entry }) => { + const view = draw(entry); + expect(sent).toEqual([]); + + fireEvent.click(view.getByRole("button", { name: button })); + + await opened(view); + await waitFor(() => expect(sent.length).toBe(1)); + await sentAll(); + expect(bodies()).toEqual([{ action: "opened", place, surface: "web" }]); + expect(sent[0]?.organizationId).toBe("default"); + expect( + RecordBusinessEventHeader.safeParse({ + "Idempotency-Key": sent[0]?.key, + }).success, + ).toBe(true); + expect( + inits + .filter((init) => init.url.endsWith("/business-events")) + .map((init) => init.keepalive), + ).toEqual([true]); + }, + ); + + /* + * The places the spec takes are exactly the ones the app counts: every signed-in entry above, and + * onboarding's Book a demo step. OpenBot Cloud's sign-in screen is not one: nobody is signed in. + */ + test("the spec's places are the app's signed-in ones, and no others", () => { + const places: SignedInPlace[] = [ + ...new Set(ENTRIES.map(([, { place }]) => place)), + "onboarding", + ]; + expect(Object.values(BusinessEventPlace).sort()).toEqual(places.sort()); + }); + + /* + * In OpenBot Desktop's window, which is this web app, the same entry says `desktop`, by the same + * test the app's other counts use (`desktopShell`). + */ + test("in OpenBot Desktop's window the opening says desktop", async () => { + (window as unknown as Record).__TAURI_INTERNALS__ = { + invoke: async () => null, + transformCallback: () => 0, + }; + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + await waitFor(() => expect(sent.length).toBe(1)); + expect(bodies()).toEqual([ + { action: "opened", place: "home", surface: "desktop" }, + ]); + }); + + /* + * The count goes to the organization the person is working in, by its id in the path, whichever + * organization that is: the server counts it for the person. + */ + test("it is counted in the organization the person is working in", async () => { + setCurrentOrganization("org-acme"); + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { + name: "Give each Bot its own computer with OpenBot for Business.", + }), + ); + await opened(view); + await waitFor(() => expect(sent.length).toBe(1)); + expect(sent.map((request) => request.organizationId)).toEqual(["org-acme"]); + }); + + /* + * ONE OPENING, ONE COUNT. It is counted as the entry is pressed, not as the dialog draws, so + * StrictMode's second run of every effect and a re-render send nothing more. Closed and opened + * again is a new opening, counted by the entry that opened it. + */ + test("under StrictMode one press sends one opened, and drawing again sends nothing", async () => { + const view = draw( + () => ( + + {accountMenuItem().label} + + ), + { strict: true }, + ); + fireEvent.click(view.getByRole("button", { name: "OpenBot for Business" })); + await opened(view); + view.redraw(); + view.redraw(); + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "account_menu", surface: "web" }, + ]); + }); + + test("closed and opened again is a second opening, by its own entry; opening it while it is open is not", async () => { + const view = draw(() => ( + <> + + + + )); + const [home, admin] = view.getAllByRole("button", { + name: "Meet OpenBot for Business", + }); + if (!home || !admin) throw new Error("no entries"); + + fireEvent.click(home); + await opened(view); + act(() => openTeamFeatures("computer_line")); + fireEvent.click(view.getByRole("button", { name: "Close" })); + await waitFor(() => expect(view.queryByRole("dialog")).toBeNull()); + fireEvent.click(admin); + await opened(view); + + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "home", surface: "web" }, + { action: "opened", place: "admin", surface: "web" }, + ]); + }); + + /* + * THE OPENING'S PLACE HOLDS FOR THE DIALOG'S LIFE. Two entries reached before the dialog has + * drawn (a second press handled before React commits the first) are one opening, by the first: + * its count, the calendar's `utm_content` and a call booked in it all name that entry, never the + * second. Closed and opened again from the other entry, all three name that one. + */ + test("two entries reached before the dialog draws are one opening by the first: its count, the calendar's tag and a booking all name it; closed and opened again, all three name the new entry", async () => { + const view = draw(() => ( + <> + + + + )); + const [home, admin] = view.getAllByRole("button", { + name: "Meet OpenBot for Business", + }); + if (!home || !admin) throw new Error("no entries"); + + // One act: React draws nothing until both presses are handled. + act(() => { + fireEvent.click(home); + fireEvent.click(admin); + }); + await opened(view); + calendly( + "calendly.event_scheduled", + "https://calendly.com", + calendarFrame(view).contentWindow, + ); + await waitFor(() => expect(sent.length).toBe(2)); + await sentAll(); + expect({ counts: bodies(), calendar: calendarPlace(view) }).toEqual({ + counts: [ + { action: "opened", place: "home", surface: "web" }, + { action: "booked", place: "home", surface: "web" }, + ], + calendar: "home", + }); + + fireEvent.click(view.getByRole("button", { name: "Close" })); + await waitFor(() => expect(view.queryByRole("dialog")).toBeNull()); + fireEvent.click(admin); + await opened(view); + calendly( + "calendly.event_scheduled", + "https://calendly.com", + calendarFrame(view).contentWindow, + ); + await waitFor(() => expect(sent.length).toBe(4)); + await sentAll(); + expect({ + counts: bodies().slice(2), + calendar: calendarPlace(view), + }).toEqual({ + counts: [ + { action: "opened", place: "admin", surface: "web" }, + { action: "booked", place: "admin", surface: "web" }, + ], + calendar: "admin", + }); + }); +}); + +describe("a call booked in the dialog's calendar", () => { + /* + * Every signed-in entry, end to end: its opening, the place its calendar is tagged with and a call + * booked in it name the same place. The booking's message carries what Calendly sends with it + * (the event and the invitee), and the body sent is the three fields, with nothing of that in it. + */ + test.each(ENTRIES)( + "%s: opened, booked and the calendar's utm_content all name its place; Calendly's payload adds nothing to the body", + async (_, { place, button, entry }) => { + const view = draw(entry); + fireEvent.click(view.getByRole("button", { name: button })); + await opened(view); + calendly( + "calendly.event_scheduled", + "https://calendly.com", + calendarFrame(view).contentWindow, + SCHEDULED_PAYLOAD, + ); + await waitFor(() => expect(sent.length).toBe(2)); + await sentAll(); + expect({ + calendar: calendarPlace(view), + bodies: sent.map((request) => request.body), + }).toStrictEqual({ + calendar: place, + bodies: [ + { action: "opened", place, surface: "web" }, + { action: "booked", place, surface: "web" }, + ], + }); + }, + ); + + /* + * Calendly says a call was booked by posting `calendly.event_scheduled` to this window. Only its + * own origin, from this calendar's frame, is believed: the same message from another site, from + * the page itself or from another frame counts nothing, and neither does any other message. + */ + test("sends one booked, by the entry that opened it; a message from another origin or frame sends nothing", async () => { + const view = draw(() => ); + fireEvent.click(view.getByRole("button", { name: "Book a call" })); + await opened(view); + await waitFor(() => expect(sent.length).toBe(1)); + const frame = calendarFrame(view); + const other = document.createElement("iframe"); + document.body.append(other); + + calendly( + "calendly.event_scheduled", + "https://example.com", + frame.contentWindow, + ); + calendly("calendly.event_scheduled", "https://calendly.com", window); + calendly( + "calendly.event_scheduled", + "https://calendly.com", + other.contentWindow, + ); + calendly( + "calendly.event_type_viewed", + "https://calendly.com", + frame.contentWindow, + ); + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "self_host_banner", surface: "web" }, + ]); + + calendly( + "calendly.event_scheduled", + "https://calendly.com", + frame.contentWindow, + ); + await waitFor(() => expect(sent.length).toBe(2)); + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "self_host_banner", surface: "web" }, + { action: "booked", place: "self_host_banner", surface: "web" }, + ]); + other.remove(); + }); + + test("under StrictMode one booking sends one booked", async () => { + const view = draw(() => , { strict: true }); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + view.redraw(); + calendly( + "calendly.event_scheduled", + "https://calendly.com", + calendarFrame(view).contentWindow, + ); + await waitFor(() => expect(sent.length).toBe(2)); + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "admin", surface: "web" }, + { action: "booked", place: "admin", surface: "web" }, + ]); + }); + + /* + * Signing out takes the signed-in layout away, and the dialog with it: it closes, and its calendar + * stops listening, so a booking said after that is not counted against anybody. Signed in again, + * the next opening is counted as a new one. + */ + test("signing out with it open closes it; a booking said after that sends nothing, and the next opening is counted", async () => { + const first = draw(() => ); + fireEvent.click( + first.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(first); + await waitFor(() => expect(sent.length).toBe(1)); + const frameWindow = calendarFrame(first).contentWindow; + + first.unmount(); + calendly("calendly.event_scheduled", "https://calendly.com", frameWindow); + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "home", surface: "web" }, + ]); + + const again = draw(() => ); + expect(again.queryByRole("dialog")).toBeNull(); + fireEvent.click( + again.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(again); + await waitFor(() => expect(sent.length).toBe(2)); + }); + + /* + * Working in another organization builds the signed-in layout again: routes/_authed.tsx mounts + * the dialog inside `OrganizationBoundary`, which is keyed by the organization. A switch with the + * dialog open closes it, and nothing of it is drawn again in the new organization: no dialog, open + * or closing, and no calendar. So a booking said by any calendar frame after the switch, the old + * one or another, is counted in neither organization. The next opening is counted in the new one. + */ + test("switching organization with it open closes it and draws no dialog or calendar in the new one; a booking said by any calendar after that sends nothing, and the next opening is counted in the new organization", async () => { + const client = signedIn(); + const root = createRootRoute({ + component: () => ( + + + + + ), + }); + const router = createRouter({ + routeTree: root, + history: createMemoryHistory({ initialEntries: ["/"] }), + }); + const view = render( + + + , + ); + fireEvent.click( + await view.findByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + await waitFor(() => expect(sent.length).toBe(1)); + const oldFrame = calendarFrame(view).contentWindow; + + act(() => setCurrentOrganization("org-second")); + await sentAll(); + // Every frame on the page now, and the old calendar's, each says a call was booked. + const frames = [ + oldFrame, + ...Array.from( + document.querySelectorAll("iframe"), + (frame) => frame.contentWindow, + ), + ]; + for (const frame of frames) + calendly( + "calendly.event_scheduled", + "https://calendly.com", + frame, + SCHEDULED_PAYLOAD, + ); + await sentAll(); + expect({ + dialogs: document.querySelectorAll('[role="dialog"]').length, + calendars: document.querySelectorAll("[data-booking-calendar] iframe") + .length, + sent: sent.map((request) => [request.organizationId, request.body]), + }).toEqual({ + dialogs: 0, + calendars: 0, + sent: [["default", { action: "opened", place: "home", surface: "web" }]], + }); + + fireEvent.click( + await view.findByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + await waitFor(() => expect(sent.length).toBe(2)); + await sentAll(); + expect( + sent.map((request) => [request.organizationId, request.body]), + ).toEqual([ + ["default", { action: "opened", place: "home", surface: "web" }], + ["org-second", { action: "opened", place: "home", surface: "web" }], + ]); + }); + + /* + * Only a real change of organization closes it. Told the organization it is already in, the dialog + * stays open; the organization becoming known, as signing in makes it, opens nothing, and the next + * opening is counted there. + */ + test("the same organization again leaves the dialog open; the organization becoming known leaves it closed, and the next opening is counted there", async () => { + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + act(() => setCurrentOrganization("default")); + await sentAll(); + expect( + view.getByRole("dialog", { name: "OpenBot for Business" }), + ).toBeTruthy(); + fireEvent.click(view.getByRole("button", { name: "Close" })); + await waitFor(() => expect(view.queryByRole("dialog")).toBeNull()); + + act(() => setCurrentOrganization(undefined)); + act(() => setCurrentOrganization("default")); + await sentAll(); + expect(view.queryByRole("dialog")).toBeNull(); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + await waitFor(() => expect(sent.length).toBe(2)); + await sentAll(); + expect(sent.map((request) => request.organizationId)).toEqual([ + "default", + "default", + ]); + }); + + /* + * A calendar that can't load gives way to Book a demo, which opens the business page in the + * browser. The opening was counted; a booking made on that page is not one OpenBot hears of. + */ + test("a calendar that can't load counted the opening, and nothing more", async () => { + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { + name: "Give each Bot its own computer with OpenBot for Business.", + }), + ); + await opened(view); + fireEvent.error(calendarFrame(view)); + expect(await view.findByRole("link", { name: "Book a demo" })).toBeTruthy(); + await sentAll(); + expect(bodies()).toEqual([ + { action: "opened", place: "computer_line", surface: "web" }, + ]); + }); +}); + +/* + * OpenBot Cloud's sign-in screen has an OpenBot for Business row of its own, which opens the same + * dialog over the sign-in screen. Nobody is signed in there, and the count is a signed-in person's, + * in their organization, so nothing is sent from it: not on opening, not for a booking. Its booking + * still carries `utm_content=sign_in`, which Calendly keeps. + */ +test("OpenBot Cloud's sign-in screen sends nothing, on opening or for a booking", async () => { + const view = render(); + fireEvent.click(view.getByRole("button", { name: /OpenBot for Business/ })); + await opened(view); + const frame = calendarFrame(view); + expect(new URL(frame.src).searchParams.get("utm_content")).toBe("sign_in"); + + calendly( + "calendly.event_scheduled", + "https://calendly.com", + frame.contentWindow, + ); + await sentAll(); + expect(sent).toEqual([]); + expect(inits.filter((init) => init.url.endsWith("/business-events"))).toEqual( + [], + ); +}); + +/* + * A count is best effort. The dialog opens, draws its calendar and takes a booking whatever the + * server does with the count: refuses it, answers from a release without it (404), breaks, or never + * answers at all. The app says so in the console and nothing on screen. + */ +describe("a count that does not arrive", () => { + test.each([ + [ + "the server refuses it", + () => HttpResponse.json({ error: "Invalid" }, { status: 400 }), + ], + [ + "a server without it answers 404", + () => new HttpResponse(null, { status: 404 }), + ], + [ + "the server breaks", + () => HttpResponse.json({ error: "down" }, { status: 503 }), + ], + ])( + "%s: the dialog opens, the calendar is there, and a booking still goes through", + async (_, answer) => { + const warned = spyOn(console, "warn").mockImplementation(() => {}); + try { + let asked = 0; + server.use( + http.post(BUSINESS_EVENTS_PATH, () => { + asked += 1; + return answer(); + }), + ); + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + calendly( + "calendly.event_scheduled", + "https://calendly.com", + calendarFrame(view).contentWindow, + ); + await waitFor(() => expect(asked).toBe(2)); + await sentAll(); + expect(calendarFrame(view)).toBeTruthy(); + expect( + view.getByRole("dialog", { name: "OpenBot for Business" }), + ).toBeTruthy(); + expect(warned.mock.calls.map((call) => call[0])).toEqual([ + "OpenBot for Business telemetry was not accepted.", + "OpenBot for Business telemetry was not accepted.", + ]); + } finally { + warned.mockRestore(); + } + }, + ); + + test("no answer at all: the dialog is the same, and the page says only that it could not be delivered", async () => { + const warned = spyOn(console, "warn").mockImplementation(() => {}); + try { + server.use(http.post(BUSINESS_EVENTS_PATH, () => HttpResponse.error())); + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await opened(view); + await waitFor(() => + expect(warned.mock.calls.map((call) => call[0])).toEqual([ + "OpenBot for Business telemetry could not be delivered.", + ]), + ); + expect(calendarFrame(view)).toBeTruthy(); + } finally { + warned.mockRestore(); + } + }); + + test("the dialog never waits for the count", async () => { + let answer: () => void = () => {}; + const answered = new Promise((resolve) => { + answer = resolve; + }); + let asked = 0; + server.use( + http.post(BUSINESS_EVENTS_PATH, async () => { + asked += 1; + await answered; + return new HttpResponse(null, { status: 204 }); + }), + ); + const view = draw(() => ); + fireEvent.click( + view.getByRole("button", { name: "Meet OpenBot for Business" }), + ); + await waitFor(() => expect(asked).toBe(1)); + expect(await opened(view)).toBeTruthy(); + expect(calendarFrame(view)).toBeTruthy(); + answer(); + }); +}); diff --git a/app/tests/business-link.test.tsx b/app/tests/business-link.test.tsx index 46706832a1..f5fb4b0714 100644 --- a/app/tests/business-link.test.tsx +++ b/app/tests/business-link.test.tsx @@ -9,8 +9,10 @@ import { import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { cleanup, fireEvent, render } from "@testing-library/react"; +import { setupServer } from "msw/node"; import { BusinessLink } from "@/components/edition/business-link"; import { TeamFeaturesDialog } from "@/components/edition/team-features-dialog"; +import { getRecordBusinessEventMockHandler } from "@/lib/api/generated/product-events/product-events.msw"; import { deploymentKeys } from "@/lib/deployment/queries"; /** @@ -18,16 +20,25 @@ import { deploymentKeys } from "@/lib/deployment/queries"; * the session, so it is back the next time the app starts. */ +/* + * Pressing the link counts the opening (`recordBusiness`). Here the count is answered by the + * handler generated from api/openapi.yaml, so it arrives and the console stays quiet; what is + * counted is business-events.test.tsx's to check. Any other request fails the test. + */ +const server = setupServer(getRecordBusinessEventMockHandler()); + // The dialog's booking calendar keeps its address but never fetches it: no test reaches Calendly. -beforeAll(() => +beforeAll(() => { GlobalRegistrator.register({ url: "http://localhost/", settings: { navigation: { disableChildFrameNavigation: true } }, - }), -); + }); + server.listen({ onUnhandledRequest: "error" }); +}); beforeEach(() => sessionStorage.clear()); afterEach(cleanup); afterAll(async () => { + server.close(); await GlobalRegistrator.unregister(); }); diff --git a/app/tests/narrow-sidebar-sheet.test.tsx b/app/tests/narrow-sidebar-sheet.test.tsx index db053af075..69b6ecf6af 100644 --- a/app/tests/narrow-sidebar-sheet.test.tsx +++ b/app/tests/narrow-sidebar-sheet.test.tsx @@ -58,6 +58,19 @@ class OfflineWebSocket extends EventTarget { } const originalFetch = globalThis.fetch; + +/** + * Opening OpenBot for Business counts the opening (`recordBusiness`). The count is answered as the + * server answers it, an empty 204, so the console stays quiet; what is counted is + * business-events.test.tsx's to check. Everything else is still not served. + */ +function notServed(input: RequestInfo | URL): Response { + return new URL(String(input), "http://localhost/").pathname.endsWith( + "/business-events", + ) + ? new Response(null, { status: 204 }) + : Response.json({ error: "not served" }, { status: 404 }); +} const originalWebSocket = globalThis.WebSocket; const clients: QueryClient[] = []; @@ -74,7 +87,7 @@ beforeAll(() => { }); beforeEach(() => { globalThis.fetch = Object.assign( - async () => Response.json({ error: "not served" }, { status: 404 }), + async (input: RequestInfo | URL) => notServed(input), { preconnect: originalFetch.preconnect }, ); }); diff --git a/app/tests/onboarding-route.test.tsx b/app/tests/onboarding-route.test.tsx index a426fd2e8e..d26a1f0ce5 100644 --- a/app/tests/onboarding-route.test.tsx +++ b/app/tests/onboarding-route.test.tsx @@ -4,6 +4,7 @@ import { beforeAll, beforeEach, expect, + spyOn, test, } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; @@ -25,6 +26,8 @@ import { within, } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; +import { getRecordBusinessEventUrl } from "@/lib/api/generated/product-events/product-events"; +import { RecordBusinessEventBody } from "@/lib/api/generated/product-events/product-events.zod"; import { queryClient } from "@/query-client"; import type { RouterContext } from "@/router-context"; import { Route as OnboardingRoute } from "@/routes/_authed/onboarding"; @@ -115,6 +118,12 @@ let askFirstChanges: unknown[]; /** Whether the API's `deployment` answers, and how many times it was asked. */ let capabilitiesFail: boolean; let capabilitiesAsked: number; +/** + * The OpenBot for Business counts sent (`recordBusinessEvent`), by their bodies, and what the API + * answers them with: accepted, or a server that broke. + */ +let businessEvents: unknown[]; +let businessEventsFail: boolean; const defaults = queryClient.getDefaultOptions(); beforeEach(() => { @@ -139,10 +148,19 @@ beforeEach(() => { askFirstChanges = []; capabilitiesFail = false; capabilitiesAsked = 0; + businessEvents = []; + businessEventsFail = false; globalThis.fetch = Object.assign( async (input: RequestInfo | URL, init?: RequestInit) => { const path = String(input); const method = init?.method ?? "GET"; + // The count's address, from the client generated from the spec. + if (path === getRecordBusinessEventUrl("default") && method === "POST") { + businessEvents.push(JSON.parse(String(init?.body))); + return businessEventsFail + ? Response.json({ error: "down" }, { status: 503 }) + : new Response(null, { status: 204 }); + } if (path === ME_PATH && method === "GET") return meResponse({ user: { @@ -809,6 +827,343 @@ test("a booking made in the calendar turns Not now into Continue; a message from expect(await heading(view, "What should we call you?")).toBeTruthy(); }); +/** Every count sent, each held to the spec's schema with nothing else in it, and the bookings among them. */ +const bookedCounts = () => + businessEvents + .map((body) => RecordBusinessEventBody.strict().parse(body)) + .filter((body) => body.action === "booked"); + +/** Long enough for a count the page started to have been sent and answered. */ +const countsSent = () => + act(async () => { + await new Promise((resolve) => setTimeout(resolve, 60)); + }); + +/* + * The same Calendly message that turns Not now into Continue counts the call, once, as booked from + * onboarding's step: only from Calendly's origin and the calendar's own frame. + */ +test("a call booked in onboarding's calendar sends one booked from onboarding; a message from anywhere else sends none", async () => { + localEvaluation = true; + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + await bookDemo(view); + const frame = calendar(view); + const scheduled = { event: "calendly.event_scheduled", payload: {} }; + const say = (origin: string, source: MessageEventSource | null) => + act(() => { + window.dispatchEvent( + new MessageEvent("message", { data: scheduled, origin, source }), + ); + }); + + say("https://example.com", frame.contentWindow); + say("https://calendly.com", window); + await countsSent(); + expect(bookedCounts()).toEqual([]); + + say("https://calendly.com", frame.contentWindow); + await waitFor(() => + expect(bookedCounts()).toEqual([ + { action: "booked", place: "onboarding", surface: "web" }, + ]), + ); + await countsSent(); + expect(bookedCounts()).toHaveLength(1); +}); + +/* + * Onboarding's OpenBot for Business step is shown to every local evaluator unasked, so the step on + * screen is not an opening. Book a demo is: it puts the calendar on screen, as an entry to the + * dialog does. Not now sends nothing. + */ +test("Book a demo on onboarding's step sends one opened from onboarding; the step itself and Not now send none", async () => { + localEvaluation = true; + const shown = open("/onboarding?step=selfhost"); + await heading(shown, "OpenBot for Business"); + fireEvent.click(await ready(shown, "Not now")); + expect(await heading(shown, "What should we call you?")).toBeTruthy(); + await countsSent(); + expect(businessEvents).toEqual([]); + cleanup(); + + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + await bookDemo(view); + await waitFor(() => + expect( + businessEvents.map((body) => + RecordBusinessEventBody.strict().parse(body), + ), + ).toEqual([{ action: "opened", place: "onboarding", surface: "web" }]), + ); + await countsSent(); + expect(businessEvents).toHaveLength(1); +}); + +/** Every count sent, each held to the spec's schema with nothing else in it. */ +const counts = () => + businessEvents.map((body) => RecordBusinessEventBody.strict().parse(body)); +const OPENED = { + action: "opened", + place: "onboarding", + surface: "web", +} as const; +const BOOKED = { + action: "booked", + place: "onboarding", + surface: "web", +} as const; + +/** Calendly's message, from its origin and the calendar's own frame, saying a call was booked. */ +const scheduled = (view: ReturnType, payload: object = {}) => + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { event: "calendly.event_scheduled", payload }, + origin: "https://calendly.com", + source: calendar(view).contentWindow, + }), + ); + }); + +/* + * ARRIVING AT THE STEP IS NOT AN OPENING. However somebody comes to onboarding's OpenBot for + * Business step, nothing is sent until they press Book a demo: from Welcome's Continue, at the step + * the server saved, or on a reload of the step. An organization's person with the step in the + * address is sent on to the name step, and nothing is sent for them either. + */ +test.each([ + ["from Welcome's Continue", "/onboarding?step=welcome", true, 0], + ["at the step the server saved", "/onboarding", true, 2], + ["on a reload of the step", "/onboarding?step=selfhost", true, 0], + [ + "for an organization's person, sent on to the name step", + "/onboarding?step=selfhost", + false, + 0, + ], +] as const)( + "arriving at onboarding's OpenBot for Business step sends nothing: %s", + async (_label, path, local, stored) => { + localEvaluation = local; + saved = stored; + const view = open(path); + if (path.endsWith("=welcome")) { + await heading(view, "Welcome to OpenBot"); + fireEvent.click(await continueButton(view)); + } + expect( + await heading( + view, + local ? "OpenBot for Business" : "What should we call you?", + ), + ).toBeTruthy(); + await countsSent(); + expect(businessEvents).toEqual([]); + }, +); + +/* + * NOR IS COMING BACK TO IT, and each press of Book a demo is one opening. Back from the next step, + * the list of steps, and the browser's Forward and Back bring the step back and send nothing. Book a + * demo sends one opened; coming back to the step after it, its calendar still there, sends nothing + * more. A reload starts the step again, and Book a demo pressed there is a second opening, under + * the same event id on the server that UTC day (the person, the organization, the action, the + * place, the surface and the day). + */ +test("coming back to onboarding's step without pressing Book a demo sends nothing, and each press of Book a demo is one opened", async () => { + localEvaluation = true; + const view = open("/onboarding?step=welcome"); + await heading(view, "Welcome to OpenBot"); + fireEvent.click(await continueButton(view)); + await heading(view, "OpenBot for Business"); + + // Not now, then Back. + fireEvent.click(view.getByRole("button", { name: "Not now" })); + await heading(view, "What should we call you?"); + fireEvent.click(back(view)); + await heading(view, "OpenBot for Business"); + // Not now, then the list of steps. + fireEvent.click(view.getByRole("button", { name: "Not now" })); + await heading(view, "What should we call you?"); + fireEvent.click( + within(await openSteps(view)).getByRole("button", { + name: /OpenBot for Business/, + }), + ); + await heading(view, "OpenBot for Business"); + // The browser's Forward, then Back. + await act(async () => view.history.forward()); + await heading(view, "What should we call you?"); + await act(async () => view.history.back()); + await heading(view, "OpenBot for Business"); + await countsSent(); + expect(businessEvents).toEqual([]); + + await bookDemo(view); + await waitFor(() => expect(counts()).toEqual([OPENED])); + fireEvent.click(view.getByRole("button", { name: "Not now" })); + await heading(view, "What should we call you?"); + fireEvent.click(back(view)); + await heading(view, "OpenBot for Business"); + expect(calendar(view)).toBeTruthy(); + await countsSent(); + expect(counts()).toEqual([OPENED]); + + // The same history, a new page: what a reload keeps. + const history = view.history; + view.unmount(); + queryClient.clear(); + const reloaded = open("/onboarding?step=selfhost", history); + await heading(reloaded, "OpenBot for Business"); + await countsSent(); + expect(counts()).toEqual([OPENED]); + await bookDemo(reloaded); + await waitFor(() => expect(counts()).toEqual([OPENED, OPENED])); + await countsSent(); + expect(counts()).toEqual([OPENED, OPENED]); +}); + +/* + * A calendar that can't load (its frame fails, or the browser is offline) gives Book a demo's place + * to Book a call, which opens the OpenBot for Business page in a new tab and moves on. The press of + * Book a demo was the opening; Book a call and the move on send nothing more, since a booking then + * happens on the website. + */ +test.each([ + ["its frame fails", false], + ["offline", true], +] as const)( + "when the calendar can't load (%s), Book a call opens the website and moves on; the opening is counted, and nothing more", + async (_label, offline) => { + localEvaluation = true; + // Shadows the prototype's getter for this test only. + if (offline) + Object.defineProperty(navigator, "onLine", { + configurable: true, + get: () => false, + }); + try { + await withOpen(async (opened) => { + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + fireEvent.click( + await view.findByRole("button", { name: "Book a demo" }), + ); + if (!offline) fireEvent.error(await waitFor(() => calendar(view))); + + fireEvent.click(await ready(view, "Book a call")); + + expect(opened).toEqual([ + [OPENBOT_FOR_BUSINESS, "_blank", "noopener,noreferrer"], + ]); + expect(await heading(view, "What should we call you?")).toBeTruthy(); + await countsSent(); + expect(counts()).toEqual([OPENED]); + }); + } finally { + if (offline) Reflect.deleteProperty(navigator, "onLine"); + } + }, +); + +/* + * With the name known, OpenBot for Business is the last step, and its buttons finish onboarding. + * Not now opens the app and sends nothing. Book a demo is one opened, a booking in its calendar one + * booked, and the button that then takes Not now's place opens the app with nothing more. + */ +test("on the last step, Not now opens the app and sends nothing", async () => { + named = "Maya"; + localEvaluation = true; + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + + fireEvent.click(await ready(view, "Not now")); + + await waitFor(() => expect(view.getByText("Home")).toBeTruthy(), { + timeout: 3000, + }); + await countsSent(); + expect(businessEvents).toEqual([]); +}); + +test("on the last step, Book a demo is one opened and a booking one booked, and going on opens the app with nothing more", async () => { + named = "Maya"; + localEvaluation = true; + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + await bookDemo(view); + scheduled(view); + await waitFor(() => + expect(footerButtons(view)).toEqual(["Back", "Get started"]), + ); + + fireEvent.click(view.getByRole("button", { name: "Get started" })); + + await waitFor(() => expect(view.getByText("Home")).toBeTruthy(), { + timeout: 3000, + }); + await countsSent(); + expect(counts()).toEqual([OPENED, BOOKED]); +}); + +/* + * Calendly's message about a booking carries the event and the invitee, by their addresses in + * Calendly's API (synthetic here). The app reads only which message it is: the count's body is + * exactly action, place and surface. + */ +test("a booking whose message carries Calendly's whole payload sends action, place and surface, and nothing of the payload", async () => { + localEvaluation = true; + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + await bookDemo(view); + + scheduled(view, { + event: { + uri: "https://api.calendly.test/scheduled_events/SYNTHETIC-EVENT", + }, + invitee: { + uri: "https://api.calendly.test/scheduled_events/SYNTHETIC-EVENT/invitees/SYNTHETIC-INVITEE", + }, + }); + + await waitFor(() => expect(businessEvents).toHaveLength(2)); + await countsSent(); + expect(businessEvents).toStrictEqual([OPENED, BOOKED]); +}); + +test("a booking whose count the server can't take still turns Not now into Continue", async () => { + localEvaluation = true; + businessEventsFail = true; + const warned = spyOn(console, "warn").mockImplementation(() => {}); + try { + const view = open("/onboarding?step=selfhost"); + await heading(view, "OpenBot for Business"); + await bookDemo(view); + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { event: "calendly.event_scheduled", payload: {} }, + origin: "https://calendly.com", + source: calendar(view).contentWindow, + }), + ); + }); + await waitFor(() => + expect(footerButtons(view)).toEqual(["Back", "Continue"]), + ); + await waitFor(() => expect(bookedCounts()).toHaveLength(1)); + await waitFor(() => + expect(warned.mock.calls.map((call) => call[0])).toContain( + "OpenBot for Business telemetry was not accepted.", + ), + ); + } finally { + warned.mockRestore(); + } +}); + test("Not now on Book a demo moves on without opening anything", async () => { localEvaluation = true; await withOpen(async (opened) => { diff --git a/app/tests/team-features-dialog.test.tsx b/app/tests/team-features-dialog.test.tsx index d4532c22f9..a1d8ae9aaf 100644 --- a/app/tests/team-features-dialog.test.tsx +++ b/app/tests/team-features-dialog.test.tsx @@ -16,6 +16,7 @@ import { render, waitFor, } from "@testing-library/react"; +import { setupServer } from "msw/node"; import { NavigationTarget, openTeamFeatures, @@ -24,6 +25,7 @@ import { TeamFeaturesDialog, } from "@/components/edition/team-features-dialog"; import { BOOKING_CALENDAR_TIMEOUT_MS } from "@/components/onboarding/booking-calendar"; +import { getRecordBusinessEventMockHandler } from "@/lib/api/generated/product-events/product-events.msw"; import { authKeys } from "@/lib/auth/queries"; import { deploymentKeys } from "@/lib/deployment/queries"; import { navigationFor } from "@/lib/navigation"; @@ -31,14 +33,24 @@ import type { AppBusinessPlace } from "@/lib/openbot-for-business"; import { Route as AdminRoute } from "@/routes/_authed/admin/route"; import { settleReactWork } from "./settle-react-work"; +/* + * Opening the dialog counts the opening (`recordBusiness`). Here the count is answered by the + * handler generated from api/openapi.yaml, so it arrives and the console stays quiet; what is + * counted is business-events.test.tsx's to check. Any other request fails the test. + */ +const server = setupServer(getRecordBusinessEventMockHandler()); + // The booking calendar's frame keeps its address but never fetches it: no test reaches Calendly. -beforeAll(() => +beforeAll(() => { GlobalRegistrator.register({ + url: "http://openbot.invalid/", settings: { navigation: { disableChildFrameNavigation: true } }, - }), -); + }); + server.listen({ onUnhandledRequest: "error" }); +}); afterEach(cleanup); afterAll(async () => { + server.close(); await settleReactWork(); GlobalRegistrator.unregister(); }); diff --git a/desktop/TELEMETRY.md b/desktop/TELEMETRY.md index 98f849f27f..ae55c24d31 100644 --- a/desktop/TELEMETRY.md +++ b/desktop/TELEMETRY.md @@ -76,7 +76,7 @@ For `model_chosen`, providers are `openai`, `anthropic`, `google`, `xai`, `cloud `windows_probe` is one of the Windows readiness check's probes, which the setup window waits on before it shows its first screen, that ran long or was stopped at its limit. Sent by the desktop itself, once per such probe, on Windows only. `probe` is which one, by what it asks: `virtualization`, `administrator`, `wsl_feature`, `wsl_service`, `virtual_machine_platform_feature`, `wsl_version`, `wsl_system_start` (`wsl.exe --system`, which starts WSL's own VM) or `docker`. `outcome` is `slow` (it answered, after the probe's slow mark) or `timed_out` (it was stopped at its limit and counted as no answer). `duration_ms` is how long it ran. Slow marks are well under the limits: 5 seconds for the PowerShell probes and `wsl_version` (limit 30), 3 for `docker` (limit 10), and 20 for `wsl_system_start` (limit 60; a cold start measured about 6). A probe that answers in good time sends nothing. Never the command, its output, its error or a path. -`business_opened` is OpenBot for Business's booker coming on screen because it was picked: on the first screen (`welcome`) or in Move to Cloud (`move_to_cloud`), once for each place each time the setup window's page loads (coming back to setup from OpenBot loads it again), however often it is picked again there. `business_booked` is a call booked in its calendar, said by Calendly from its own origin and the calendar's frame. The window sends both, with the place and nothing else: never the time booked or anything typed into the calendar. The calendar's address carries the same place as `utm_content` beside `utm_source=openbot_app` and `utm_medium=in_app`, which Calendly keeps on the booking, so a booking and these events name the same screen. +`business_opened` is OpenBot for Business's booker coming on screen because it was picked: on the first screen (`welcome`) or in Move to Cloud (`move_to_cloud`), once for each place each time the setup window's page loads (coming back to setup from OpenBot loads it again), however often it is picked again there. `business_booked` is a call booked in its calendar, said by Calendly from its own origin and the calendar's frame. The window sends both, with the place and nothing else: never the time booked or anything typed into the calendar. The calendar's address carries the same place as `utm_content` beside `utm_source=openbot_app` and `utm_medium=in_app`, which Calendly keeps on the booking, so a booking and these events name the same screen. They are the setup window's only. Desktop's main window is OpenBot's web app, whose OpenBot for Business dialog (opened from the account menu's entry or the others, and a call booked in it) and onboarding's Book a demo step (Book a demo pressed, and a call booked) are counted by the OpenBot the window is signed in to, as `oss.runtime.openbot.business_opened` and `business_booked` with `business_surface` `desktop`, under that server's telemetry switch ([product telemetry](../docs/TELEMETRY.md)), and never as these events. `openbot_connect` is the first screen's connection to an OpenBot that runs elsewhere, by the screen it was made on: OpenBot Cloud's sign-in (`cloud`) or a company's OpenBot by its address (`connect_openbot`). It counts that screen whenever it shows: on a first setup, and on a later launch that shows it again, such as a saved connection whose sign-in ended (Sign in again) or the choice of where OpenBot runs made again from Settings. Shown again once a connection is kept, its `step_viewed` starts no setup session (see `setup_abandoned`). The window sends `started` when the person presses Sign in, Connect, Try again or Sign in again, then `failed` when the address check or the browser sign-in fails, or `cancelled` when the person presses Cancel. The desktop itself sends `completed` once signed in and the window has gone to that OpenBot: through the relay, once that OpenBot is shown; through the window's own sign-in, once the window goes to the page that trades its code, so before the trade. Each ending has `duration_ms` from the press, and the outcomes are `sign_in`'s. A Cancel pressed just as the sign-in completes can give `cancelled` and then `completed` for one go: it did connect. `completed` also ends the setup session, as `activated` does for OpenBot on this computer, so a quit afterwards is not `setup_abandoned`; it is not `activated`, since nothing started here. Move to Cloud signs in its own way and never sends it. Opening a connection again with the sign-in this computer already has sends nothing, and a sign-in left behind when the screen goes says nothing when it ends. Never the address, its host or the sentence about what went wrong. It is not `sign_in`, which stays the Account step's CopilotKit sign-in. diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 2b23bf2636..b930bf0948 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -31,7 +31,7 @@ With product telemetry on, every run also states the shared Intelligence analyti ## Events and interpretation -The event names are `oss.runtime.openbot.run_accepted`, `.run_terminal`, `.run_stop_requested`, `.capability`, `.result_viewed`, `.result_copied`, `.exception`, `.nudge_shown`, `.nudge_clicked` and `.nudge_dismissed`. Common properties include `schema_version`, `app_id`, `event_id`, `occurred_at`, `deployment_id`, `deployment_kind`, `user_id`, `environment`, `openbot_version` and `openbot_edition`. `deployment_kind` is `cloud` for OpenBot Cloud, `desktop` for OpenBot Desktop and `self_hosted` for any other server. On OpenBot Cloud, whose `deployment_id` is `openbot-cloud`, `run_accepted` and `run_terminal` also carry `org_id`, the organization's opaque internal id, never its name; no other deployment sends it. `openbot_version` is the release the running server is, as its image is tagged and without the tag's `v` (`1.1.0`, `1.1.0-rc.2`); an internal build is `1.1.0-internal`; a development server or a local image build is `unknown`. `openbot_edition` is `team` or `personal`. Together they let a staged rollout be watched release by release. `environment` (and `deployment_environment`, the same value) says what kind of deployment sent the event, decided by the build it runs and not by `NODE_ENV`, which a Compose install and OpenBot Desktop leave empty: a build with a version (a release, a release candidate or an internal build) is `production`; a development server or a local image build, whose `openbot_version` is `unknown`, is `development`; a test run (`NODE_ENV=test`) is `test`. Events sent before this say `unknown`. Those that carry an `openbot_version` other than `unknown` came from such a build and count as `production`; those with no `openbot_version` at all predate it and cannot be told apart. [The queries](telemetry-queries.sql) read history this way. Run events carry known thread/run/root/parent IDs, `attempt_id=run_id`, a numeric `attempt` only when available, `trigger`, `surface` and `purpose`. Unknown linkage stays unknown. +The event names are `oss.runtime.openbot.run_accepted`, `.run_terminal`, `.run_stop_requested`, `.capability`, `.result_viewed`, `.result_copied`, `.exception`, `.nudge_shown`, `.nudge_clicked`, `.nudge_dismissed`, `.business_opened` and `.business_booked`. Common properties include `schema_version`, `app_id`, `event_id`, `occurred_at`, `deployment_id`, `deployment_kind`, `user_id`, `environment`, `openbot_version` and `openbot_edition`. `deployment_kind` is `cloud` for OpenBot Cloud, `desktop` for OpenBot Desktop and `self_hosted` for any other server. On OpenBot Cloud, whose `deployment_id` is `openbot-cloud`, `run_accepted` and `run_terminal` also carry `org_id`, the organization's opaque internal id, never its name; no other deployment sends it. `openbot_version` is the release the running server is, as its image is tagged and without the tag's `v` (`1.1.0`, `1.1.0-rc.2`); an internal build is `1.1.0-internal`; a development server or a local image build is `unknown`. `openbot_edition` is `team` or `personal`. Together they let a staged rollout be watched release by release. `environment` (and `deployment_environment`, the same value) says what kind of deployment sent the event, decided by the build it runs and not by `NODE_ENV`, which a Compose install and OpenBot Desktop leave empty: a build with a version (a release, a release candidate or an internal build) is `production`; a development server or a local image build, whose `openbot_version` is `unknown`, is `development`; a test run (`NODE_ENV=test`) is `test`. Events sent before this say `unknown`. Those that carry an `openbot_version` other than `unknown` came from such a build and count as `production`; those with no `openbot_version` at all predate it and cannot be told apart. [The queries](telemetry-queries.sql) read history this way. Run events carry known thread/run/root/parent IDs, `attempt_id=run_id`, a numeric `attempt` only when available, `trigger`, `surface` and `purpose`. Unknown linkage stays unknown. `run_accepted` records entry into agent execution, rather than every HTTP run/connect request. Only runs OpenBot started as work are counted: a person's, a routine's, a subagent's or a hop's. The runtime's own runs on a Bot, naming a new conversation or offering suggestions, carry no OpenBot context and emit no run events. `run_terminal` records the observed `outcome`, bounded `failure_category`, duration, `is_root` and up to 256 `result_message_ids`. A run that ended because its model provider failed also carries `refusal_kind`, one closed name for what went wrong: `usage_limit` (a plan's usage limit, until it resets), `usage_credits`, `rate_limit`, `billing`, `key`, `model`, `outdated_client`, `too_many_tools`, `too_long`, `too_large`, `provider_down`, `connection_dropped`, `no_response`, `unreachable`, `declined` (the model declined to answer), `unknown` or `other`. It is `null` on every other run, and never carries the provider's words. An actual protocol finish without an explicit failure is normal completion; source errors, cancellation and timeout remain distinct. The host may emit `run_stop_requested` with a bounded stop reason; this records a request, not a terminal outcome. A run OpenBot knows it stopped ends `cancelled` with `failure_category` `none`: a person's Stop (on a browser run or on a thread a headless turn runs in), a stop that reaches a subagent, a headless cancel or pause, and a paused hop. A headless turn stopped at its deadline ends `timeout`. A lost lock is not a stop. Missing terminal evidence is unknown. A child run never determines its parent's outcome. Human initiation, scheduled routines, followups and subagents remain separate triggers. @@ -77,7 +77,21 @@ A nudge is a notice OpenBot shows a person once, such as the ask to star OpenBot ## OpenBot for Business bookings -The OpenBot for Business calendar, in the web app and in OpenBot Desktop, is Calendly's, and the booking is Calendly's record. Its address (`shared/openbot-for-business.ts`) carries `utm_source=openbot_app`, `utm_medium=in_app` and `utm_content`, the screen that put it in front of the person, which Calendly keeps on the booking: `account_menu` (the account menu's entry, in every skin), `home` (the home page's Meet OpenBot for Business), `admin` (an Admin page that applies only to a team), `computer_line` (a Bot's line about a computer of its own), `self_host_banner` (the self-hosting bar's Book a call), `sign_in` (OpenBot Cloud's sign-in screen), `onboarding` (onboarding's Book a demo step), and Desktop's `welcome` and `move_to_cloud`. A place names the entry, not the page it sits on: a Bot's computer line on an Admin page is `computer_line`. Nothing about the person is added to the address. The tags are on the address whatever the telemetry setting, since they describe where a booking was made and reach only Calendly, with the booking. A calendar that could not load hands over to the OpenBot for Business page in the browser, which OpenBot does not tag. Desktop's setup window also counts its booker opened and a call booked in it, by place ([desktop telemetry](../desktop/TELEMETRY.md)). +The OpenBot for Business calendar, in the web app and in OpenBot Desktop, is Calendly's, and the booking is Calendly's record. Its address (`shared/openbot-for-business.ts`) carries `utm_source=openbot_app`, `utm_medium=in_app` and `utm_content`, the screen that put it in front of the person, which Calendly keeps on the booking: `account_menu` (the account menu's entry, in every skin), `home` (the home page's Meet OpenBot for Business), `admin` (an Admin page that applies only to a team), `computer_line` (a Bot's line about a computer of its own), `self_host_banner` (the self-hosting bar's Book a call), `sign_in` (OpenBot Cloud's sign-in screen), `onboarding` (onboarding's Book a demo step), and Desktop's `welcome` and `move_to_cloud`. A place names the entry, not the page it sits on: a Bot's computer line on an Admin page is `computer_line`. Nothing about the person is added to the address. The tags are on the address whatever the telemetry setting, since they describe where a booking was made and reach only Calendly, with the booking. A calendar that could not load hands over to the OpenBot for Business page in the browser, which OpenBot does not tag. + +The web app counts OpenBot for Business opened, and a call booked in its calendar, by the same places, at `POST /api/v2/organizations/{organizationId}/business-events` (`recordBusinessEvent`), with keepalive and no retry, in a strict body: + +```json +{"action":"opened","place":"account_menu","surface":"web"} +``` + +`action` is `opened` when an entry opens the OpenBot for Business dialog, or Book a demo puts the calendar on onboarding's step. It is counted as the entry or Book a demo is pressed, once for each opening: StrictMode's second effect and the dialog drawn again count nothing more. An entry reached while the dialog is already open is not a new opening and changes nothing, so the opening, the calendar's `utm_content` and a booking in it all name the entry that opened it; the dialog closed and opened again is a new opening, by its own entry. `booked` is a call booked in the dialog's calendar or in onboarding's Book a demo step, as Calendly says it (`calendly.event_scheduled`) from its own origin and the calendar's frame; no other message, origin or frame is a booking. Onboarding's step itself, which every local evaluator is shown, is not an opening, and neither is its Not now, nor coming back to the step (Back, the list of steps, the browser's Back and Forward, a reload) without pressing Book a demo; each press of Book a demo is one. Desktop's setup window, by contrast, counts its page coming on screen. `place` is `account_menu`, `home`, `admin`, `computer_line`, `self_host_banner` or `onboarding`, as above. `surface` is `web`, or `desktop` in OpenBot Desktop's main window, which is this web app. Nothing else is accepted: never the time booked or anything typed into the calendar. The server sends `business_opened` or `business_booked` with `business_place` and `business_surface`, under the signed-in person's `user_id` pseudonym, for each opening and each booking. The stable event ID is made of six things, on that deployment: the person, the organization they are working in, the action, the place, the surface and the UTC day. Exactly, it is the lowercase hex SHA-256 of `:business::::::`. The organization id is the one the address resolves to, so an organization named by its slug or by its id is one organization, and a personal server's is `default`. The day and `occurred_at` come from one reading of the server's clock. Servers of one deployment give the same ID while they share its `deployment_id` and `KEY_ENCRYPTION_KEY`. Every accepted report is still sent: opening the dialog again from the same entry, or booking from it again, in the same organization and on the same surface that day, sends the same ID again, and at midnight UTC the next day's ID starts. So counted by distinct event ID, each person opens and books at most once per organization, place, surface and UTC day. The organization is part of the ID only, and the event never names it. Every other part of the ID is in the event, though, so the ID is pseudonymous, not secret: anyone holding a list of candidate organization ids, such as the `org_id` that OpenBot Cloud's run events carry, can find the organization by hashing each one, and a personal server's is `default`. The same person on another deployment has another pseudonym, and so another ID. To count people rather than person-days, count distinct `user_id` with `deployment_id`. A booking's own count is Calendly's: `business_booked` says where a call was booked, not how many calls, and carries no reference to the booking. [Query G](telemetry-queries.sql) counts both per place and surface. + +The body is at most 4 KiB, and a larger one is refused (413). Every request carries an `Idempotency-Key` of 1 to 128 characters, which the server keeps for 24 hours for the person, the organization and the operation, whether telemetry is on or off: the same key sent again with the same body gets the first answer back, marked `Idempotent-Replayed: true`, and nothing is sent again; the same key with another body is refused (409 `IDEMPOTENCY_KEY_CONFLICT`); and a second request with the key while the first is still being answered is told to try again (409 `IDEMPOTENCY_IN_PROGRESS`, with `Retry-After`). The app makes a new key for each count and never sends one twice. The answer is `204` with no body, where telemetry is off too: it means the handler completed, not that PostHog has the event. A nudge event is held to the same. + +Nothing is sent from OpenBot Cloud's sign-in screen (`sign_in`): nobody is signed in there, so its bookings carry their tag and nothing else. A calendar that could not load sends the opening and nothing more, since the booking then happens on the website. Signing out closes the dialog, and so does switching to another organization, before the new one is drawn; a booking said after either is not counted. The count goes to the OpenBot the window is signed in to, in the organization the person is working in: in OpenBot Desktop's window that is the OpenBot on this computer, or OpenBot Cloud or a company's OpenBot once connected to one. The app sends it whatever the telemetry setting, and that OpenBot decides, by its existing product telemetry switch and no switch of its own: like a nudge, an event is accepted and dropped where telemetry is off. The OpenBot that Desktop runs on this computer is started with `COPILOTKIT_TELEMETRY_DISABLED=1` while Share usage data is off (`fresh_runtime_env` in `desktop/src-tauri/src/desktop_telemetry.rs`), so turning it off drops these from OpenBot's next start. OpenBot Cloud or a company's OpenBot follows its own setting, never Desktop's. A count that is refused, gets no answer, or reaches a server from before this endpoint (404) changes nothing on screen. + +Desktop's setup window counts its own booker, opened and a call booked in it, for `welcome` and `move_to_cloud`, with its own events, `oss.desktop.business_opened` and `oss.desktop.business_booked` ([desktop telemetry](../desktop/TELEMETRY.md)); these are unchanged. ## Desktop updates and the join with the server diff --git a/docs/telemetry-queries.sql b/docs/telemetry-queries.sql index f85118cbfe..50d990e223 100644 --- a/docs/telemetry-queries.sql +++ b/docs/telemetry-queries.sql @@ -167,3 +167,43 @@ WHERE event IN ('oss.runtime.openbot.nudge_shown', AND coalesce(properties.openbot_version,'unknown')!='unknown')) AND properties.event_id IS NOT NULL GROUP BY nudge, place, moment; + +-- G. OpenBot for Business in the web app, OpenBot Desktop's main window included: +-- opening it and booking a call in its calendar, per place and surface. An +-- event_id is one person, organization, action, place, surface and UTC day on +-- one deployment: opening again, or booking again, from the same place, in the +-- same organization and on the same surface that day sends the same id again. +-- So distinct event_id counts person-days (one per organization a person used +-- that day), added up over every organization and day in each place and +-- surface; distinct deployment_id + user_id counts people, on known deployments +-- only (an unknown deployment scope can't tell people apart); the same person on +-- another deployment has another user_id pseudonym. Booked is Calendly's own message from the +-- calendar and says where a call was booked: count the bookings themselves from +-- Calendly's record, which carries the same place as utm_content. OpenBot +-- Cloud's sign-in screen sends neither. Desktop's setup window counts its own +-- booker (oss.desktop.business_opened and business_booked), which this leaves +-- out; its events name the place `place`, so a funnel across both reads it as +-- coalesce(properties.business_place, properties.place). +SELECT properties.business_place AS place, + properties.business_surface AS surface, + count(DISTINCT if(event='oss.runtime.openbot.business_opened', + properties.event_id, NULL)) AS opened_person_days, + count(DISTINCT if(event='oss.runtime.openbot.business_booked', + properties.event_id, NULL)) AS booked_person_days, + count(DISTINCT if(event='oss.runtime.openbot.business_opened' + AND properties.deployment_id!='unknown', + concat(properties.deployment_id, ':', + properties.user_id), NULL)) AS people_opened, + count(DISTINCT if(event='oss.runtime.openbot.business_booked' + AND properties.deployment_id!='unknown', + concat(properties.deployment_id, ':', + properties.user_id), NULL)) AS people_booked +FROM events +WHERE event IN ('oss.runtime.openbot.business_opened', + 'oss.runtime.openbot.business_booked') + AND properties.app_id='openbot' + AND (properties.environment='production' + OR (properties.environment='unknown' + AND coalesce(properties.openbot_version,'unknown')!='unknown')) + AND properties.event_id IS NOT NULL +GROUP BY place, surface;