From 0d7d667741bb17e4d7abac54faf6daf92dc4e031 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 17 Nov 2026 19:52:59 -0800 Subject: [PATCH 01/12] Publish the API versions and oldest apps a server serves, and name the app on every request The deployment answer gains api (the API versions served), minimumClients (the oldest release of each app served), launcherApi and extensionApi. Apps name themselves in an OpenBot-Client header, and an app below its minimum is refused with CLIENT_UPDATE_REQUIRED. shared/client-version.ts holds the rules every app decides by, and shared/fixtures/client-version the cases each app runs. --- api/openapi.yaml | 72 +++++- api/openapi/admin-settings.yaml | 62 ++++- api/openapi/common.yaml | 35 +++ .../lib/api/generated/model/clientRelease.ts | 9 + app/src/lib/api/generated/model/deployment.ts | 18 ++ app/src/lib/api/generated/model/index.ts | 3 + .../lib/api/generated/model/minimumClients.ts | 14 ++ app/src/lib/api/generated/model/problem.ts | 5 + .../lib/api/generated/model/problemClient.ts | 15 ++ .../organization-settings.msw.ts | 9 + .../organization-settings.ts | 2 +- .../organization-settings.zod.ts | 67 +++++- extension/src/shared/generated/recorder.ts | 16 ++ .../src/api/generated/model/clientRelease.ts | 9 + mobile/src/api/generated/model/deployment.ts | 18 ++ mobile/src/api/generated/model/index.ts | 3 + .../src/api/generated/model/minimumClients.ts | 14 ++ mobile/src/api/generated/model/problem.ts | 5 + .../src/api/generated/model/problemClient.ts | 15 ++ .../organization-settings.ts | 2 +- shared/client-version.ts | 220 ++++++++++++++++++ shared/fixtures/client-version/cases.json | 192 +++++++++++++++ shared/tests/client-version.test.ts | 127 ++++++++++ 23 files changed, 926 insertions(+), 6 deletions(-) create mode 100644 app/src/lib/api/generated/model/clientRelease.ts create mode 100644 app/src/lib/api/generated/model/minimumClients.ts create mode 100644 app/src/lib/api/generated/model/problemClient.ts create mode 100644 mobile/src/api/generated/model/clientRelease.ts create mode 100644 mobile/src/api/generated/model/minimumClients.ts create mode 100644 mobile/src/api/generated/model/problemClient.ts create mode 100644 shared/client-version.ts create mode 100644 shared/fixtures/client-version/cases.json create mode 100644 shared/tests/client-version.test.ts diff --git a/api/openapi.yaml b/api/openapi.yaml index 9a208d5d7a..7b2758a3bf 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -14,6 +14,8 @@ info: An install for one person on one computer has no sign-in. It signs nobody in, so it has neither OAuth nor API keys, and the operations that manage keys and sessions answer 503 with the code SIGN_IN_UNAVAILABLE. + OpenBot's own apps name themselves on every request in the header `OpenBot-Client`: `/`, where kind is web, desktop, mobile or recorder, such as `OpenBot-Client: desktop/1.1.0`. A header may name more than one, separated by spaces: OpenBot Desktop adds its own to the one its window's page sent. getDeployment says which API versions this OpenBot serves and the oldest release of each app it serves (minimumClients). Every other operation refuses an app older than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem names the app (client) and its minimum (minimumVersion) and whose detail tells the person to update OpenBot. A program of your own need not send the header; without it nothing is refused for a version. + This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. servers: - url: http://127.0.0.1:3001 @@ -1690,7 +1692,7 @@ paths: - Organization settings operationId: getDeployment summary: Read what this OpenBot offers - description: 'Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required.' + description: 'Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app''s version, so an app reads it first to learn whether it, or the OpenBot, needs an update.' x-openbot-singleton: true security: - {} @@ -22284,6 +22286,23 @@ components: description: 'Whether this OpenBot has computers for Bots at all. False, a Bot has no computer, browser or sign-in to a website, and the computers answer 503 to every call. Not isolatedBots: an OpenBot whose Bots share one computer has computers (true) and cannot give a Bot one of its own (isolatedBots false).' attachmentLimits: $ref: '#/components/schemas/AttachmentLimits' + api: + type: array + description: 'The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can''t use it: when they are all newer than the app''s, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2.' + minItems: 1 + items: + type: string + pattern: ^v[1-9][0-9]{0,3}$ + minimumClients: + $ref: '#/components/schemas/MinimumClients' + launcherApi: + type: integer + minimum: 1 + description: The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. + extensionApi: + type: integer + minimum: 1 + description: The version of what the OpenBot Recorder and this OpenBot exchange. AllowlistEntry: type: string minLength: 1 @@ -23452,6 +23471,17 @@ components: description: 'What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it.' items: type: object + client: + type: string + enum: + - web + - desktop + - mobile + - recorder + description: On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. + minimumVersion: + type: string + description: On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. ConversationJoinToken: type: object description: 'What a client needs to watch a conversation live: a token, and the socket and topic to use it on (the threadStream channel of api/asyncapi.yaml).' @@ -23818,6 +23848,24 @@ components: type: integer minimum: 1 description: The largest text file, or a file of any other kind. + ClientRelease: + type: string + description: An OpenBot release, such as 1.1.0. + pattern: ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + examples: + - 1.1.0 + MinimumClients: + type: object + description: The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published. + properties: + web: + $ref: '#/components/schemas/ClientRelease' + desktop: + $ref: '#/components/schemas/ClientRelease' + mobile: + $ref: '#/components/schemas/ClientRelease' + recorder: + $ref: '#/components/schemas/ClientRelease' ConversationWork: type: object description: 'Something still owed an answer in a conversation: another Bot that was asked and has not answered (handoff), or a routine running into it (routine).' @@ -37081,6 +37129,19 @@ components: retryable: true requestId: req_example traceId: trace_example + clientUpdateRequired: + value: + type: https://open.bot/errors/client-update-required + title: This app is too old for this OpenBot. + status: 400 + detail: This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again. + code: CLIENT_UPDATE_REQUIRED + category: validation + retryable: false + requestId: req_example + traceId: trace_example + client: desktop + minimumVersion: 1.0.2 ConversationNotFound: description: The conversation does not exist, was removed, or the caller is not in it, or the organization does not exist. content: @@ -41869,6 +41930,15 @@ components: imageBytes: 104857600 documentBytes: 104857600 fileBytes: 104857600 + api: + - v2 + minimumClients: + web: 1.1.0 + desktop: 1.0.2 + mobile: 1.1.0 + recorder: 1.1.0 + launcherApi: 1 + extensionApi: 1 OrganizationSettingsExample: summary: The settings, with what an administrator needs beside them. value: diff --git a/api/openapi/admin-settings.yaml b/api/openapi/admin-settings.yaml index bb9b452388..909d2b1759 100644 --- a/api/openapi/admin-settings.yaml +++ b/api/openapi/admin-settings.yaml @@ -19,8 +19,11 @@ paths: member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity - provider and no version: only whether - single sign-on is set up and required. + provider and no build: only whether + single sign-on is set up and required, and which API versions and + which releases of each OpenBot app it serves. It is never refused for + the app's version, so an app reads it first to learn whether it, or + the OpenBot, needs an update. x-openbot-singleton: true security: - {} @@ -1086,6 +1089,53 @@ components: a Bot one of its own (isolatedBots false). attachmentLimits: $ref: '#/components/schemas/AttachmentLimits' + api: + type: array + description: >- + The API versions this OpenBot serves, by major, such as v2. An app + that speaks none of them can't use it: when they are all newer than + the app's, the app needs an update; when they are all older, this + OpenBot does. Absent from a release before it was published, which + serves v2. + minItems: 1 + items: + type: string + pattern: ^v[1-9][0-9]{0,3}$ + minimumClients: + $ref: '#/components/schemas/MinimumClients' + launcherApi: + type: integer + minimum: 1 + description: >- + The version of what OpenBot Desktop supplies when it starts this + OpenBot on its own computer. It changes when Desktop must supply + something new. + extensionApi: + type: integer + minimum: 1 + description: The version of what the OpenBot Recorder and this OpenBot exchange. + MinimumClients: + type: object + description: >- + The oldest release of each OpenBot app this OpenBot serves. An app + names itself in the OpenBot-Client header, and one older than its + minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but + this deployment answer. An app not listed has no minimum. Absent from + a release before it was published. + properties: + web: + $ref: '#/components/schemas/ClientRelease' + desktop: + $ref: '#/components/schemas/ClientRelease' + mobile: + $ref: '#/components/schemas/ClientRelease' + recorder: + $ref: '#/components/schemas/ClientRelease' + ClientRelease: + type: string + description: An OpenBot release, such as 1.1.0. + pattern: ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + examples: [1.1.0] AttachmentLimits: type: object description: >- @@ -2173,6 +2223,14 @@ components: imageBytes: 104857600 documentBytes: 104857600 fileBytes: 104857600 + api: [v2] + minimumClients: + web: 1.1.0 + desktop: 1.0.2 + mobile: 1.1.0 + recorder: 1.1.0 + launcherApi: 1 + extensionApi: 1 OrganizationSettingsExample: summary: The settings, with what an administrator needs beside them. value: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index 0ed795d676..c3dbbb2a9e 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -57,6 +57,19 @@ info: SIGN_IN_UNAVAILABLE. + OpenBot's own apps name themselves on every request in the header + `OpenBot-Client`: `/`, where kind is web, desktop, + mobile or recorder, such as `OpenBot-Client: desktop/1.1.0`. A header + may name more than one, separated by spaces: OpenBot Desktop adds its + own to the one its window's page sent. getDeployment says which API + versions this OpenBot serves and the oldest release of each app it + serves (minimumClients). Every other operation refuses an app older + than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem + names the app (client) and its minimum (minimumVersion) and whose + detail tells the person to update OpenBot. A program of your own need + not send the header; without it nothing is refused for a version. + + This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. @@ -985,6 +998,15 @@ components: reason: each entry names the item and says what is wrong with it. items: type: object + client: + type: string + enum: [web, desktop, mobile, recorder] + description: >- + On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named + that is older than this OpenBot serves. + minimumVersion: + type: string + description: On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. ConversationJoinToken: { $ref: './conversations.yaml#/components/schemas/ConversationJoinToken' } CredentialKind: { $ref: './model-connections.yaml#/components/schemas/CredentialKind' } Credential: { $ref: './model-connections.yaml#/components/schemas/Credential' } @@ -1302,6 +1324,19 @@ components: retryable: true requestId: req_example traceId: trace_example + clientUpdateRequired: + value: + type: https://open.bot/errors/client-update-required + title: This app is too old for this OpenBot. + status: 400 + detail: This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again. + code: CLIENT_UPDATE_REQUIRED + category: validation + retryable: false + requestId: req_example + traceId: trace_example + client: desktop + minimumVersion: 1.0.2 ConversationNotFound: description: >- The conversation does not exist, was removed, or the caller is not in diff --git a/app/src/lib/api/generated/model/clientRelease.ts b/app/src/lib/api/generated/model/clientRelease.ts new file mode 100644 index 0000000000..45b5f0897a --- /dev/null +++ b/app/src/lib/api/generated/model/clientRelease.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * An OpenBot release, such as 1.1.0. + * @pattern ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + */ +export type ClientRelease = string; diff --git a/app/src/lib/api/generated/model/deployment.ts b/app/src/lib/api/generated/model/deployment.ts index 30fdbaebc1..30cb696d50 100644 --- a/app/src/lib/api/generated/model/deployment.ts +++ b/app/src/lib/api/generated/model/deployment.ts @@ -4,6 +4,7 @@ import type { AttachmentLimits } from "./attachmentLimits"; import type { DeploymentAuthProvidersItem } from "./deploymentAuthProvidersItem"; import type { DeploymentEdition } from "./deploymentEdition"; +import type { MinimumClients } from "./minimumClients"; /** * What this OpenBot offers and how people sign in to it. @@ -36,4 +37,21 @@ export interface Deployment { /** Whether this OpenBot has computers for Bots at all. False, a Bot has no computer, browser or sign-in to a website, and the computers answer 503 to every call. Not isolatedBots: an OpenBot whose Bots share one computer has computers (true) and cannot give a Bot one of its own (isolatedBots false). */ botComputers: boolean; attachmentLimits?: AttachmentLimits; + /** + * The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2. + * @minItems 1 + * @items.pattern ^v[1-9][0-9]{0,3}$ + */ + api?: string[]; + minimumClients?: MinimumClients; + /** + * The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. + * @minimum 1 + */ + launcherApi?: number; + /** + * The version of what the OpenBot Recorder and this OpenBot exchange. + * @minimum 1 + */ + extensionApi?: number; } diff --git a/app/src/lib/api/generated/model/index.ts b/app/src/lib/api/generated/model/index.ts index 814ac6b88d..5fa28a6a33 100644 --- a/app/src/lib/api/generated/model/index.ts +++ b/app/src/lib/api/generated/model/index.ts @@ -422,6 +422,7 @@ export * from "./clearBotBrowserHeaders"; export * from "./clearPersonBrowserHeaders"; export * from "./clearTeamBotConsentsHeaders"; export * from "./clickComputerHeaders"; +export * from "./clientRelease"; export * from "./completeGoalHeaders"; export * from "./completeOnboardingHeaders"; export * from "./component"; @@ -1011,6 +1012,7 @@ export * from "./memorySourceToolInputSchema"; export * from "./memorySourceToolPage"; export * from "./memoryUnavailableResponse"; export * from "./messageListEmphasis"; +export * from "./minimumClients"; export * from "./modelCatalogue"; export * from "./modelCatalogueExposure"; export * from "./modelCatalogueProvider"; @@ -1137,6 +1139,7 @@ export * from "./pressComputerKeyHeaders"; export * from "./previewCapabilityChangesHeaders"; export * from "./problem"; export * from "./problemCategory"; +export * from "./problemClient"; export * from "./problemProblemsItem"; export * from "./productEvent"; export * from "./productEventKind"; diff --git a/app/src/lib/api/generated/model/minimumClients.ts b/app/src/lib/api/generated/model/minimumClients.ts new file mode 100644 index 0000000000..26e1e29164 --- /dev/null +++ b/app/src/lib/api/generated/model/minimumClients.ts @@ -0,0 +1,14 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { ClientRelease } from "./clientRelease"; + +/** + * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published. + */ +export interface MinimumClients { + web?: ClientRelease; + desktop?: ClientRelease; + mobile?: ClientRelease; + recorder?: ClientRelease; +} diff --git a/app/src/lib/api/generated/model/problem.ts b/app/src/lib/api/generated/model/problem.ts index 703b301dfb..6ed25de3a0 100644 --- a/app/src/lib/api/generated/model/problem.ts +++ b/app/src/lib/api/generated/model/problem.ts @@ -2,6 +2,7 @@ * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ import type { ProblemCategory } from "./problemCategory"; +import type { ProblemClient } from "./problemClient"; import type { ProblemProblemsItem } from "./problemProblemsItem"; /** @@ -31,4 +32,8 @@ export interface Problem { capability?: string; /** What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it. */ problems?: ProblemProblemsItem[]; + /** On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. */ + client?: ProblemClient; + /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ + minimumVersion?: string; } diff --git a/app/src/lib/api/generated/model/problemClient.ts b/app/src/lib/api/generated/model/problemClient.ts new file mode 100644 index 0000000000..b2d4bb76e5 --- /dev/null +++ b/app/src/lib/api/generated/model/problemClient.ts @@ -0,0 +1,15 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. + */ +export type ProblemClient = (typeof ProblemClient)[keyof typeof ProblemClient]; + +export const ProblemClient = { + web: "web", + desktop: "desktop", + mobile: "mobile", + recorder: "recorder", +} as const; diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts index e5d623fe6f..af2dc5a7d4 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts @@ -33,6 +33,15 @@ export const getGetDeploymentResponseMock = (): Deployment => ({ documentBytes: 104857600, fileBytes: 104857600, }, + api: ["v2"], + minimumClients: { + web: "1.1.0", + desktop: "1.0.2", + mobile: "1.1.0", + recorder: "1.1.0", + }, + launcherApi: 1, + extensionApi: 1, }); export const getGetOrganizationSettingsResponseMock = diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.ts b/app/src/lib/api/generated/organization-settings/organization-settings.ts index 3aeaebb45d..b0029d371d 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.ts @@ -101,7 +101,7 @@ export const getGetDeploymentUrl = (organizationId: string) => { }; /** - * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required. + * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app's version, so an app reads it first to learn whether it, or the OpenBot, needs an update. * @summary Read what this OpenBot offers */ export const getDeployment = async ( diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts index 48d9e98b28..0db9bb4821 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts @@ -4,7 +4,7 @@ import * as zod from "zod"; /** - * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required. + * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app's version, so an app reads it first to learn whether it, or the OpenBot, needs an update. * @summary Read what this OpenBot offers */ @@ -17,6 +17,23 @@ export const GetDeploymentParams = zod.object({ ), }); +export const getDeploymentResponseApiItemRegExp = new RegExp( + "^v[1-9][0-9]{0,3}$", +); + +export const getDeploymentResponseMinimumClientsWebRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseMinimumClientsDesktopRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseMinimumClientsMobileRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseMinimumClientsRecorderRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); + export const GetDeploymentResponse = zod .object({ edition: zod @@ -83,6 +100,54 @@ export const GetDeploymentResponse = zod .describe( "How large a file attached to a message may be, by kind, in bytes. An upload over its kind's limit is refused. Absent, as from an older OpenBot, the limits are 8388608 for an image or a PDF and 1048576 for any other file. The limits can rise while OpenBot runs, so a client reads them again rather than keeping them for good. What a Bot's model is shown of a large file is a separate matter: the file is kept and can be downloaded whatever the model can read of it.", ), + api: zod + .array(zod.string().regex(getDeploymentResponseApiItemRegExp)) + .min(1) + .optional() + .describe( + "The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2.", + ), + minimumClients: zod + .object({ + web: zod + .string() + .regex(getDeploymentResponseMinimumClientsWebRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + desktop: zod + .string() + .regex(getDeploymentResponseMinimumClientsDesktopRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + mobile: zod + .string() + .regex(getDeploymentResponseMinimumClientsMobileRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + recorder: zod + .string() + .regex(getDeploymentResponseMinimumClientsRecorderRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + }) + .optional() + .describe( + "The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published.", + ), + launcherApi: zod + .int() + .min(1) + .optional() + .describe( + "The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new.", + ), + extensionApi: zod + .int() + .min(1) + .optional() + .describe( + "The version of what the OpenBot Recorder and this OpenBot exchange.", + ), }) .describe("What this OpenBot offers and how people sign in to it."); diff --git a/extension/src/shared/generated/recorder.ts b/extension/src/shared/generated/recorder.ts index e7929d0e5a..125ed97816 100644 --- a/extension/src/shared/generated/recorder.ts +++ b/extension/src/shared/generated/recorder.ts @@ -262,6 +262,18 @@ export const ProblemCategory = { export type ProblemProblemsItem = { [key: string]: unknown }; +/** + * On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. + */ +export type ProblemClient = (typeof ProblemClient)[keyof typeof ProblemClient]; + +export const ProblemClient = { + web: "web", + desktop: "desktop", + mobile: "mobile", + recorder: "recorder", +} as const; + /** * RFC 9457 problem details, in the shape CopilotKit Intelligence's v2 API uses. status equals the HTTP status; code and type name the same stable error. detail is the sentence a person reads. */ @@ -289,6 +301,10 @@ export interface Problem { capability?: string; /** What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it. */ problems?: ProblemProblemsItem[]; + /** On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. */ + client?: ProblemClient; + /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ + minimumVersion?: string; } /** diff --git a/mobile/src/api/generated/model/clientRelease.ts b/mobile/src/api/generated/model/clientRelease.ts new file mode 100644 index 0000000000..45b5f0897a --- /dev/null +++ b/mobile/src/api/generated/model/clientRelease.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * An OpenBot release, such as 1.1.0. + * @pattern ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + */ +export type ClientRelease = string; diff --git a/mobile/src/api/generated/model/deployment.ts b/mobile/src/api/generated/model/deployment.ts index 30fdbaebc1..30cb696d50 100644 --- a/mobile/src/api/generated/model/deployment.ts +++ b/mobile/src/api/generated/model/deployment.ts @@ -4,6 +4,7 @@ import type { AttachmentLimits } from "./attachmentLimits"; import type { DeploymentAuthProvidersItem } from "./deploymentAuthProvidersItem"; import type { DeploymentEdition } from "./deploymentEdition"; +import type { MinimumClients } from "./minimumClients"; /** * What this OpenBot offers and how people sign in to it. @@ -36,4 +37,21 @@ export interface Deployment { /** Whether this OpenBot has computers for Bots at all. False, a Bot has no computer, browser or sign-in to a website, and the computers answer 503 to every call. Not isolatedBots: an OpenBot whose Bots share one computer has computers (true) and cannot give a Bot one of its own (isolatedBots false). */ botComputers: boolean; attachmentLimits?: AttachmentLimits; + /** + * The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2. + * @minItems 1 + * @items.pattern ^v[1-9][0-9]{0,3}$ + */ + api?: string[]; + minimumClients?: MinimumClients; + /** + * The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. + * @minimum 1 + */ + launcherApi?: number; + /** + * The version of what the OpenBot Recorder and this OpenBot exchange. + * @minimum 1 + */ + extensionApi?: number; } diff --git a/mobile/src/api/generated/model/index.ts b/mobile/src/api/generated/model/index.ts index 873836a52d..0203a3b519 100644 --- a/mobile/src/api/generated/model/index.ts +++ b/mobile/src/api/generated/model/index.ts @@ -165,6 +165,7 @@ export * from "./checkInSkipReason"; export * from "./checkInUsage"; export * from "./checkInUsageDays"; export * from "./checkInUsagePings"; +export * from "./clientRelease"; export * from "./computer"; export * from "./computerAction"; export * from "./computerActionConflictResponse"; @@ -378,6 +379,7 @@ export * from "./memorySourceTool"; export * from "./memorySourceToolInputSchema"; export * from "./memorySourceToolPage"; export * from "./memoryUnavailableResponse"; +export * from "./minimumClients"; export * from "./modelFailedResponse"; export * from "./modelNotConfiguredResponse"; export * from "./modelUsage"; @@ -420,6 +422,7 @@ export * from "./personNotFoundResponse"; export * from "./personRole"; export * from "./problem"; export * from "./problemCategory"; +export * from "./problemClient"; export * from "./problemProblemsItem"; export * from "./question"; export * from "./questionAnswer"; diff --git a/mobile/src/api/generated/model/minimumClients.ts b/mobile/src/api/generated/model/minimumClients.ts new file mode 100644 index 0000000000..26e1e29164 --- /dev/null +++ b/mobile/src/api/generated/model/minimumClients.ts @@ -0,0 +1,14 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { ClientRelease } from "./clientRelease"; + +/** + * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published. + */ +export interface MinimumClients { + web?: ClientRelease; + desktop?: ClientRelease; + mobile?: ClientRelease; + recorder?: ClientRelease; +} diff --git a/mobile/src/api/generated/model/problem.ts b/mobile/src/api/generated/model/problem.ts index 703b301dfb..6ed25de3a0 100644 --- a/mobile/src/api/generated/model/problem.ts +++ b/mobile/src/api/generated/model/problem.ts @@ -2,6 +2,7 @@ * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ import type { ProblemCategory } from "./problemCategory"; +import type { ProblemClient } from "./problemClient"; import type { ProblemProblemsItem } from "./problemProblemsItem"; /** @@ -31,4 +32,8 @@ export interface Problem { capability?: string; /** What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it. */ problems?: ProblemProblemsItem[]; + /** On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. */ + client?: ProblemClient; + /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ + minimumVersion?: string; } diff --git a/mobile/src/api/generated/model/problemClient.ts b/mobile/src/api/generated/model/problemClient.ts new file mode 100644 index 0000000000..b2d4bb76e5 --- /dev/null +++ b/mobile/src/api/generated/model/problemClient.ts @@ -0,0 +1,15 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. + */ +export type ProblemClient = (typeof ProblemClient)[keyof typeof ProblemClient]; + +export const ProblemClient = { + web: "web", + desktop: "desktop", + mobile: "mobile", + recorder: "recorder", +} as const; diff --git a/mobile/src/api/generated/organization-settings/organization-settings.ts b/mobile/src/api/generated/organization-settings/organization-settings.ts index afb6ea6047..13a9cd80ad 100644 --- a/mobile/src/api/generated/organization-settings/organization-settings.ts +++ b/mobile/src/api/generated/organization-settings/organization-settings.ts @@ -48,7 +48,7 @@ export const getGetDeploymentUrl = (organizationId: string) => { }; /** - * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required. + * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app's version, so an app reads it first to learn whether it, or the OpenBot, needs an update. * @summary Read what this OpenBot offers */ export const getDeployment = async ( diff --git a/shared/client-version.ts b/shared/client-version.ts new file mode 100644 index 0000000000..eb3aba188e --- /dev/null +++ b/shared/client-version.ts @@ -0,0 +1,220 @@ +/** + * Which OpenBot app is asking, and whether it and the OpenBot it talks to can work together. + * + * Every app sends `OpenBot-Client: /` on every request, so the server knows who is + * asking. Every server says on its `deployment` which API versions it serves and the oldest release + * of each app it still serves. When the two don't fit, the person reads one sentence: "Update + * OpenBot" when the app is too old, "Ask whoever runs your OpenBot to update it" when the server is. + * + * The web app, the Recorder and the server read this file. OpenBot Desktop (Rust) and the phone app + * carry the same few rules in their own code; their tests hold them to the cases in + * `shared/fixtures/client-version/`. + */ +import { version as RELEASE_VERSION } from "../package.json"; +import policy from "../release-policy.json"; + +/** The request header an app names itself in. */ +export const CLIENT_HEADER = "OpenBot-Client"; + +/** The apps that name themselves. A program of someone's own sends nothing, or its own name. */ +export const CLIENT_KINDS = ["web", "desktop", "mobile", "recorder"] as const; +export type ClientKind = (typeof CLIENT_KINDS)[number]; + +/** The OpenBot release this code is: the version every app built from it reports. */ +export const RELEASE = RELEASE_VERSION; + +/** The API versions this release serves, and the ones its apps speak. */ +export const API_VERSIONS: readonly string[] = ["v2"]; + +/** + * The oldest release of each app this release's server still serves. An older one is refused with + * CLIENT_UPDATE_REQUIRED. Proposal (API versioning design, section 6.3): the previous minor release + * in full. OpenBot Desktop goes back to 1.0.2, the first release whose window an OpenBot of today + * still starts; the phone app and the Recorder to 1.1.0, their first release that speaks this API. + * The web app is served by the server itself, so only a tab left open across an upgrade is older. + * An app from before this check sends no header and is never refused by it. + */ +export const MINIMUM_CLIENTS: Readonly> = { + web: "1.1.0", + desktop: "1.0.2", + mobile: "1.1.0", + recorder: "1.1.0", +}; + +/** The contract numbers `release-policy.json` keeps, which `deployment` publishes. */ +export const LAUNCHER_API: number = policy.compatibility.launcherApi; +export const EXTENSION_API: number = policy.compatibility.extensionApi; + +/** What a person reads when the app is older than the OpenBot it talks to serves. */ +export const APP_UPDATE_SENTENCE = "Update OpenBot"; +/** What a person reads when the OpenBot is older than the app can use. */ +export const SERVER_UPDATE_SENTENCE = + "Ask whoever runs your OpenBot to update it"; + +/** The problem code a server answers an app below its minimum with. */ +export const CLIENT_UPDATE_REQUIRED = "CLIENT_UPDATE_REQUIRED"; + +/** One app named in the header. */ +export type NamedClient = { kind: ClientKind; version: string }; + +/** `/`, as an app sends it. */ +export function clientToken(kind: ClientKind, version: string = RELEASE) { + return `${kind}/${version}`; +} + +/** + * The apps a header names. The header is a list of `/` separated by spaces, like a + * User-Agent: OpenBot Desktop adds its own to the one its window's page sent. A token whose kind is + * not an OpenBot app, or whose version is not one, is not read. + */ +export function parseClientHeader( + value: string | null | undefined, +): NamedClient[] { + if (!value) return []; + const named: NamedClient[] = []; + for (const token of value.trim().split(/\s+/).slice(0, 8)) { + const slash = token.indexOf("/"); + if (slash < 1) continue; + const kind = token.slice(0, slash).toLowerCase(); + const version = token.slice(slash + 1); + if (!(CLIENT_KINDS as readonly string[]).includes(kind)) continue; + if (!isVersion(version)) continue; + named.push({ kind: kind as ClientKind, version }); + } + return named; +} + +const VERSION = + /^v?(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?:-([0-9A-Za-z.-]{1,64}))?$/; + +/** Whether `value` is a release number: `1.2.0`, `1.2.0-rc.1`, with or without a leading v. */ +export function isVersion(value: unknown): value is string { + return typeof value === "string" && VERSION.test(value); +} + +/** + * Release order, by semantic versioning's rules (semver.org, section 11): numbers first, and a + * pre-release (`1.2.0-rc.1`) before its release. Undefined when either is not a release number. + */ +export function compareVersions(a: string, b: string): number | undefined { + const left = VERSION.exec(a); + const right = VERSION.exec(b); + if (!left || !right) return undefined; + for (const index of [1, 2, 3]) { + const difference = Number(left[index]) - Number(right[index]); + if (difference !== 0) return Math.sign(difference); + } + const [leftPre, rightPre] = [left[4], right[4]]; + if (leftPre === rightPre) return 0; + if (leftPre === undefined) return 1; + if (rightPre === undefined) return -1; + const leftParts = leftPre.split("."); + const rightParts = rightPre.split("."); + for (let i = 0; i < Math.max(leftParts.length, rightParts.length); i++) { + const l = leftParts[i]; + const r = rightParts[i]; + if (l === undefined) return -1; + if (r === undefined) return 1; + const ln = /^\d+$/.test(l) ? Number(l) : undefined; + const rn = /^\d+$/.test(r) ? Number(r) : undefined; + if (ln !== undefined && rn !== undefined) { + if (ln !== rn) return Math.sign(ln - rn); + } else if (ln !== undefined) return -1; + else if (rn !== undefined) return 1; + else if (l !== r) return l < r ? -1 : 1; + } + return 0; +} + +/** + * The app among `named` that the server's minimums refuse, with the minimum it is below, or + * undefined when every one may go on. + */ +export function belowMinimum( + named: readonly NamedClient[], + minimums: Readonly>>, +): (NamedClient & { minimum: string }) | undefined { + for (const client of named) { + const minimum = minimums[client.kind]; + if (!minimum) continue; + const order = compareVersions(client.version, minimum); + if (order !== undefined && order < 0) return { ...client, minimum }; + } + return undefined; +} + +/** + * The sentence a server refuses an app below its minimum with, as the problem's detail: what + * happened, then what to do (`.claude/skills/openbot-copy`). + */ +export function clientUpdateDetail(kind: ClientKind, minimum: string): string { + const version = minimum.replace(/^v/, ""); + switch (kind) { + case "web": + return "This page is from an older version of OpenBot. Update OpenBot to keep going."; + case "desktop": + return `This OpenBot needs OpenBot Desktop ${version} or later. Update OpenBot, then try again.`; + case "mobile": + return `This OpenBot needs the OpenBot phone app ${version} or later. Update OpenBot, then try again.`; + case "recorder": + return `This OpenBot needs the OpenBot Recorder ${version} or later. Update OpenBot, then try again.`; + } +} + +/** The major of an API version, `v2` as 2. */ +function major(version: string): number | undefined { + const match = /^v(\d{1,4})$/.exec(version); + return match ? Number(match[1]) : undefined; +} + +/** + * Whether an app and the OpenBot it talks to can work together, from that OpenBot's `deployment`. + * + * - `ok`: they can. Features the server lacks are hidden by the fields that offer them, never by a + * version. + * - `app`: the app is too old. The server serves no API version the app speaks and only newer ones, + * or it names a minimum for this app above the app's version. "Update OpenBot". + * - `server`: the server is too old. It serves only API versions older than any the app speaks. + * "Ask whoever runs your OpenBot to update it". + * + * A `deployment` that publishes no `api` is from a release before this check, and every such + * release that answers `deployment` serves v2. `"before-v2"` is an OpenBot that answers no + * `deployment` at all but still answers as an OpenBot: a release from before the v2 API. + */ +export type Compatibility = + | { fit: "ok" } + | { fit: "app"; minimum?: string } + | { fit: "server" }; + +export function compatibility( + deployment: { api?: unknown; minimumClients?: unknown } | "before-v2", + client: { kind: ClientKind; version: string; speaks?: readonly string[] }, +): Compatibility { + if (deployment === "before-v2") return { fit: "server" }; + const speaks = client.speaks ?? API_VERSIONS; + const served = Array.isArray(deployment.api) + ? deployment.api.filter( + (entry): entry is string => typeof entry === "string", + ) + : ["v2"]; + if (!served.some((version) => speaks.includes(version))) { + const newestServed = Math.max( + ...served.map(major).filter((n): n is number => n !== undefined), + ); + const newestSpoken = Math.max( + ...speaks.map(major).filter((n): n is number => n !== undefined), + ); + // Only newer versions than any the app speaks: the app is behind. Otherwise the server is. + return newestServed > newestSpoken ? { fit: "app" } : { fit: "server" }; + } + const minimums = + deployment.minimumClients && typeof deployment.minimumClients === "object" + ? (deployment.minimumClients as Record) + : {}; + const minimum = minimums[client.kind]; + if (isVersion(minimum)) { + const order = compareVersions(client.version, minimum); + if (order !== undefined && order < 0) return { fit: "app", minimum }; + } + return { fit: "ok" }; +} diff --git a/shared/fixtures/client-version/cases.json b/shared/fixtures/client-version/cases.json new file mode 100644 index 0000000000..799f70ff9a --- /dev/null +++ b/shared/fixtures/client-version/cases.json @@ -0,0 +1,192 @@ +{ + "$comment": "What each app decides from an OpenBot's deployment answer (shared/client-version.ts `compatibility`). The web app, the Recorder, OpenBot Desktop and the phone app each run every case. `deployments` are real answers: `current` is what this release's server answers (the back end's test holds its real answer to it), `v1.1.0` is what OpenBot 1.1.0 answers (no version fields), `raised` is this release with an admin's OPENBOT_MINIMUM_CLIENTS=desktop=1.2.0,mobile=1.2.0,recorder=1.2.0,web=1.2.0, and `v3-only` is a later OpenBot that serves only a new API. `before-v2` is an OpenBot from before the v2 API (1.0.3 and older): its deployment answers 404 and its /api/capabilities answers as `before-v2-capabilities` shows.", + "deployments": { + "current": { + "edition": "team", + "localEvaluation": false, + "generativeUi": true, + "selfHostBanner": false, + "transcription": false, + "voice": false, + "durableHistory": true, + "authProviders": ["okta"], + "ssoConfigured": false, + "ssoRequired": false, + "builtInBots": true, + "isolatedBots": false, + "botComputers": true, + "attachmentLimits": { + "imageBytes": 8388608, + "documentBytes": 8388608, + "fileBytes": 1048576 + }, + "api": ["v2"], + "minimumClients": { + "web": "1.1.0", + "desktop": "1.0.2", + "mobile": "1.1.0", + "recorder": "1.1.0" + }, + "launcherApi": 1, + "extensionApi": 1 + }, + "v1.1.0": { + "edition": "team", + "localEvaluation": false, + "generativeUi": true, + "selfHostBanner": false, + "transcription": false, + "voice": false, + "durableHistory": true, + "authProviders": ["okta"], + "ssoConfigured": false, + "ssoRequired": false, + "builtInBots": true, + "isolatedBots": false, + "botComputers": true + }, + "raised": { + "edition": "team", + "localEvaluation": false, + "generativeUi": true, + "selfHostBanner": false, + "transcription": false, + "voice": false, + "durableHistory": true, + "authProviders": ["okta"], + "ssoConfigured": false, + "ssoRequired": false, + "builtInBots": true, + "isolatedBots": false, + "botComputers": true, + "attachmentLimits": { + "imageBytes": 8388608, + "documentBytes": 8388608, + "fileBytes": 1048576 + }, + "api": ["v2"], + "minimumClients": { + "web": "1.2.0", + "desktop": "1.2.0", + "mobile": "1.2.0", + "recorder": "1.2.0" + }, + "launcherApi": 1, + "extensionApi": 1 + }, + "v3-only": { + "edition": "team", + "localEvaluation": false, + "generativeUi": true, + "selfHostBanner": false, + "transcription": false, + "voice": false, + "durableHistory": true, + "authProviders": ["okta"], + "ssoConfigured": false, + "ssoRequired": false, + "builtInBots": true, + "isolatedBots": false, + "botComputers": true, + "api": ["v3"], + "minimumClients": { "desktop": "2.0.0" }, + "launcherApi": 2, + "extensionApi": 2 + } + }, + "before-v2-capabilities": { + "mode": "intelligence", + "durableHistory": true, + "generativeUi": true, + "selfHostBanner": false, + "localEvaluation": false, + "edition": "team" + }, + "cases": [ + { + "deployment": "current", + "client": { "kind": "desktop", "version": "1.1.0" }, + "fit": "ok" + }, + { + "deployment": "current", + "client": { "kind": "web", "version": "1.1.0" }, + "fit": "ok" + }, + { + "deployment": "current", + "client": { "kind": "mobile", "version": "1.1.0" }, + "fit": "ok" + }, + { + "deployment": "current", + "client": { "kind": "recorder", "version": "1.1.0" }, + "fit": "ok" + }, + { + "deployment": "current", + "client": { "kind": "desktop", "version": "1.0.1" }, + "fit": "app", + "minimum": "1.0.2" + }, + { + "deployment": "current", + "client": { "kind": "mobile", "version": "1.0.9" }, + "fit": "app", + "minimum": "1.1.0" + }, + { + "deployment": "current", + "client": { "kind": "desktop", "version": "1.0.2-rc.3" }, + "fit": "app", + "minimum": "1.0.2" + }, + { + "deployment": "v1.1.0", + "client": { "kind": "desktop", "version": "1.1.0" }, + "fit": "ok" + }, + { + "deployment": "v1.1.0", + "client": { "kind": "web", "version": "1.2.0" }, + "fit": "ok" + }, + { + "deployment": "raised", + "client": { "kind": "desktop", "version": "1.1.0" }, + "fit": "app", + "minimum": "1.2.0" + }, + { + "deployment": "raised", + "client": { "kind": "web", "version": "1.1.0" }, + "fit": "app", + "minimum": "1.2.0" + }, + { + "deployment": "raised", + "client": { "kind": "desktop", "version": "1.2.0" }, + "fit": "ok" + }, + { + "deployment": "v3-only", + "client": { "kind": "desktop", "version": "1.1.0" }, + "fit": "app" + }, + { + "deployment": "current", + "client": { "kind": "desktop", "version": "2.0.0", "speaks": ["v3"] }, + "fit": "server" + }, + { + "deployment": "before-v2", + "client": { "kind": "desktop", "version": "1.1.0" }, + "fit": "server" + }, + { + "deployment": "before-v2", + "client": { "kind": "mobile", "version": "1.1.0" }, + "fit": "server" + } + ] +} diff --git a/shared/tests/client-version.test.ts b/shared/tests/client-version.test.ts new file mode 100644 index 0000000000..cba797b0a8 --- /dev/null +++ b/shared/tests/client-version.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, test } from "bun:test"; +import policy from "../../release-policy.json"; +import { version } from "../../package.json"; +import { + API_VERSIONS, + belowMinimum, + type ClientKind, + clientToken, + clientUpdateDetail, + compareVersions, + compatibility, + EXTENSION_API, + LAUNCHER_API, + MINIMUM_CLIENTS, + parseClientHeader, + RELEASE, +} from "../client-version"; +import cases from "../fixtures/client-version/cases.json"; + +describe("which app is asking", () => { + test("an app names itself as kind/version, and Desktop adds its own to its page's", () => { + expect(clientToken("desktop", "1.1.0")).toBe("desktop/1.1.0"); + expect(clientToken("web")).toBe(`web/${version}`); + expect(parseClientHeader("web/1.2.0 desktop/1.1.5")).toEqual([ + { kind: "web", version: "1.2.0" }, + { kind: "desktop", version: "1.1.5" }, + ]); + }); + + test("anything that is not an OpenBot app with a release number is not read", () => { + expect(parseClientHeader(null)).toEqual([]); + expect(parseClientHeader("")).toEqual([]); + expect( + parseClientHeader("curl/8.7.1 desktop/main-ci web/ /1.0.0 desktop"), + ).toEqual([]); + expect(parseClientHeader("Desktop/v1.0.3")).toEqual([ + { kind: "desktop", version: "v1.0.3" }, + ]); + }); +}); + +describe("release order", () => { + test("numbers in order, and a candidate before its release", () => { + const ordered = [ + "1.0.2-rc.1", + "1.0.2-rc.3", + "1.0.2", + "1.0.10", + "1.1.0-rc.2", + "1.1.0", + "v1.2.0", + "2.0.0", + ]; + for (let i = 0; i < ordered.length - 1; i++) { + expect( + compareVersions(ordered[i] as string, ordered[i + 1] as string), + ).toBe(-1); + expect( + compareVersions(ordered[i + 1] as string, ordered[i] as string), + ).toBe(1); + } + expect(compareVersions("1.1.0", "v1.1.0")).toBe(0); + expect(compareVersions("test-20261117-71", "1.1.0")).toBeUndefined(); + }); + + test("an app below a minimum is the one refused, and not one at it", () => { + const named = parseClientHeader("web/1.1.0 desktop/1.0.1"); + expect(belowMinimum(named, MINIMUM_CLIENTS)).toEqual({ + kind: "desktop", + version: "1.0.1", + minimum: "1.0.2", + }); + expect( + belowMinimum(parseClientHeader("desktop/1.0.2"), MINIMUM_CLIENTS), + ).toBeUndefined(); + }); +}); + +describe("what this release publishes", () => { + test("its own release, the API it serves, and release-policy's contract numbers", () => { + expect(RELEASE).toBe(version); + expect(API_VERSIONS).toEqual(["v2"]); + expect(LAUNCHER_API).toBe(policy.compatibility.launcherApi); + expect(EXTENSION_API).toBe(policy.compatibility.extensionApi); + expect(cases.deployments.current.minimumClients).toEqual({ + ...MINIMUM_CLIENTS, + }); + }); + + test("every app this release builds is at or above the minimum it serves", () => { + for (const minimum of Object.values(MINIMUM_CLIENTS)) + expect(compareVersions(RELEASE, minimum)).toBeGreaterThanOrEqual(0); + }); + + test("the sentence a refused app reads says to update OpenBot", () => { + for (const kind of Object.keys(MINIMUM_CLIENTS) as ClientKind[]) { + const detail = clientUpdateDetail(kind, "1.2.0"); + expect(detail).toContain("Update OpenBot"); + expect(detail).not.toMatch(/reload|refresh|—/i); + } + expect(clientUpdateDetail("desktop", "v1.2.0")).toBe( + "This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again.", + ); + }); +}); + +describe("each app's decision from real deployment answers", () => { + for (const each of cases.cases) { + const client = each.client as { + kind: ClientKind; + version: string; + speaks?: string[]; + }; + test(`${each.deployment}, ${client.kind}/${client.version}${client.speaks ? ` speaking ${client.speaks}` : ""}: ${each.fit}`, () => { + const deployment = + each.deployment === "before-v2" + ? ("before-v2" as const) + : cases.deployments[ + each.deployment as keyof typeof cases.deployments + ]; + const fit = compatibility(deployment, client); + expect(fit.fit).toBe(each.fit as "ok" | "app" | "server"); + if ("minimum" in each) + expect(fit).toEqual({ fit: "app", minimum: each.minimum as string }); + }); + } +}); From 707b6c7602ae8fac9bff35aeb7d95a83791e31d2 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 17 Nov 2026 20:04:46 -0800 Subject: [PATCH 02/12] Say the version refusal applies to /api/v2 operations only --- api/openapi.yaml | 2 +- api/openapi/common.yaml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/api/openapi.yaml b/api/openapi.yaml index 7b2758a3bf..16793fb01f 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -14,7 +14,7 @@ info: An install for one person on one computer has no sign-in. It signs nobody in, so it has neither OAuth nor API keys, and the operations that manage keys and sessions answer 503 with the code SIGN_IN_UNAVAILABLE. - OpenBot's own apps name themselves on every request in the header `OpenBot-Client`: `/`, where kind is web, desktop, mobile or recorder, such as `OpenBot-Client: desktop/1.1.0`. A header may name more than one, separated by spaces: OpenBot Desktop adds its own to the one its window's page sent. getDeployment says which API versions this OpenBot serves and the oldest release of each app it serves (minimumClients). Every other operation refuses an app older than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem names the app (client) and its minimum (minimumVersion) and whose detail tells the person to update OpenBot. A program of your own need not send the header; without it nothing is refused for a version. + OpenBot's own apps name themselves on every request in the header `OpenBot-Client`: `/`, where kind is web, desktop, mobile or recorder, such as `OpenBot-Client: desktop/1.1.0`. A header may name more than one, separated by spaces: OpenBot Desktop adds its own to the one its window's page sent. getDeployment says which API versions this OpenBot serves and the oldest release of each app it serves (minimumClients). Every other operation under /api/v2 refuses an app older than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem names the app (client) and its minimum (minimumVersion) and whose detail tells the person to update OpenBot. A program of your own need not send the header; without it nothing is refused for a version. This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. servers: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index c3dbbb2a9e..6547880741 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -63,8 +63,8 @@ info: may name more than one, separated by spaces: OpenBot Desktop adds its own to the one its window's page sent. getDeployment says which API versions this OpenBot serves and the oldest release of each app it - serves (minimumClients). Every other operation refuses an app older - than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem + serves (minimumClients). Every other operation under /api/v2 refuses + an app older than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem names the app (client) and its minimum (minimumVersion) and whose detail tells the person to update OpenBot. A program of your own need not send the header; without it nothing is refused for a version. From 3179768efc898bf76706b53178eabca92abcee5f Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 17 Nov 2026 20:09:02 -0800 Subject: [PATCH 03/12] Name the phone app and the Recorder on every request, and say Update OpenBot when OpenBot refuses them The phone app sends OpenBot-Client: mobile/ on every request it makes to OpenBot: the API calls, sign-in and the screen socket. The release is the root package.json version, which app.config.ts reads into extra.openbotRelease as the app is built; Expo's own app version is a store number and says nothing about which OpenBot this is. Before sign-in the root layout reads the deployment and decides with the app's own copy of the compatibility rule (Metro bundles only mobile/), held to every case in shared/fixtures/client-version. An app below the server's minimum, or a CLIENT_UPDATE_REQUIRED refusal on any request, covers the app with "Update OpenBot". An OpenBot that answers no deployment but answers /api/capabilities as an OpenBot is from before the v2 API, and covers it with "Ask whoever runs your OpenBot to update it". The Recorder sends OpenBot-Client: recorder/ from openbotRaw, which every request it makes to OpenBot goes through, from the service worker and the offscreen document. A CLIENT_UPDATE_REQUIRED refusal now reaches the popup, the Connect page and Connect with OpenBot Desktop as the Recorder's own update sentence, built from the app and release the refusal names. Before, the Connect page said the connect request had expired and the popup that OpenBot did not answer. --- extension/src/background/connection.ts | 17 +- extension/src/background/recording.ts | 8 +- extension/src/pages/popup/desktop-sentence.ts | 5 +- extension/src/shared/openbot-client.ts | 45 ++++- extension/tests/connection.test.ts | 50 +++++ extension/tests/openbot-client.test.ts | 37 ++++ extension/tests/recording.test.ts | 48 +++++ mobile/app.config.ts | 10 +- mobile/app/_layout.tsx | 34 ++-- mobile/app/computer.tsx | 3 +- mobile/src/api/request.ts | 28 ++- mobile/src/auth.ts | 3 + mobile/src/client-version.ts | 172 ++++++++++++++++++ mobile/src/release.ts | 19 ++ mobile/src/version-check.ts | 58 ++++++ mobile/src/version-gate.tsx | 103 +++++++++++ mobile/tests/client-version.test.ts | 70 +++++++ mobile/tests/generated-client.test.ts | 150 +++++++++++++++ 18 files changed, 834 insertions(+), 26 deletions(-) create mode 100644 mobile/src/client-version.ts create mode 100644 mobile/src/release.ts create mode 100644 mobile/src/version-check.ts create mode 100644 mobile/src/version-gate.tsx create mode 100644 mobile/tests/client-version.test.ts diff --git a/extension/src/background/connection.ts b/extension/src/background/connection.ts index 60ded7e0e6..4cccbbec9e 100644 --- a/extension/src/background/connection.ts +++ b/extension/src/background/connection.ts @@ -15,7 +15,11 @@ import { getRecorderIdentity, type RecorderConnectionGrant, } from "../shared/generated/recorder"; -import { OpenBotError, ORGANIZATION_ID } from "../shared/openbot-client"; +import { + OpenBotError, + ORGANIZATION_ID, + updateRequiredSentence, +} from "../shared/openbot-client"; import { normaliseOpenBotOrigin } from "../shared/origin"; import { allowsOpenBot, @@ -361,13 +365,14 @@ async function approve( ); } catch (error) { // The Recorder's own sentence for what OpenBot answered (EXCHANGE_REFUSED), or a plain one: a network failure's - // message ("Failed to fetch") means nothing here. + // message ("Failed to fetch") means nothing here. An OpenBot that serves only newer Recorders says to update. return { ok: false, error: - error instanceof OpenBotError + updateRequiredSentence(error) ?? + (error instanceof OpenBotError ? (EXCHANGE_REFUSED[error.status] ?? EXCHANGE_FAILED) - : UNREACHABLE, + : UNREACHABLE), }; } const connection: ConnectionRecord = { @@ -894,7 +899,9 @@ async function desktopConnect( } catch (error) { return refused( error instanceof OpenBotError - ? "exchange-refused" + ? error.updateRequired + ? "client-update-required" + : "exchange-refused" : "openbot-unreachable", ); } diff --git a/extension/src/background/recording.ts b/extension/src/background/recording.ts index 98f6dd9db9..9633aae797 100644 --- a/extension/src/background/recording.ts +++ b/extension/src/background/recording.ts @@ -46,7 +46,11 @@ import { KEPT_FOR_PERSON_MS, RECORDER_ACTION_NOTICE_AT, } from "../shared/limits"; -import { OpenBotError, ORGANIZATION_ID } from "../shared/openbot-client"; +import { + OpenBotError, + ORGANIZATION_ID, + updateRequiredSentence, +} from "../shared/openbot-client"; import { isRecordablePage } from "../shared/origin"; import { allowsOpenBot, @@ -573,6 +577,8 @@ const signedOutReason = (error: unknown): SignedOutReason | null => * text in its answer, which the popup would show in the Recorder's own voice. */ const sentenceFor = (error: unknown, fallback: string): string => { if (!(error instanceof OpenBotError)) return fallback; + const update = updateRequiredSentence(error); + if (update) return update; if (error.body?.code === RECORDER_AUTHORITY_UNAVAILABLE) return SENTENCES.authorityUnavailable; return error.status === 403 ? SENTENCES.forbidden : fallback; diff --git a/extension/src/pages/popup/desktop-sentence.ts b/extension/src/pages/popup/desktop-sentence.ts index 8be4805c07..fef200bdcb 100644 --- a/extension/src/pages/popup/desktop-sentence.ts +++ b/extension/src/pages/popup/desktop-sentence.ts @@ -1,5 +1,6 @@ /** Why Connect with OpenBot Desktop did not connect this browser, one plain sentence per code: OpenBot Desktop's own - * error codes, and the Recorder's (no answer, the policy, an address it cannot use, OpenBot not taking Desktop's code). */ + * error codes, and the Recorder's (no answer, the policy, an address it cannot use, OpenBot not taking Desktop's code, + * OpenBot serving only newer Recorders). */ const SENTENCES: Record = { "origin-not-allowed": "OpenBot Desktop does not recognise this copy of the Recorder. Connect from OpenBot in your browser instead.", @@ -27,6 +28,8 @@ const SENTENCES: Record = { "OpenBot Desktop answered with an address the Recorder cannot use. Connect from OpenBot in your browser instead.", "exchange-refused": "OpenBot did not accept the code OpenBot Desktop gave the Recorder. Try again.", + "client-update-required": + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", "openbot-unreachable": "OpenBot did not answer. Make sure OpenBot is running in OpenBot Desktop, then try again.", }; diff --git a/extension/src/shared/openbot-client.ts b/extension/src/shared/openbot-client.ts index c24220e1a9..9c1cd2f54c 100644 --- a/extension/src/shared/openbot-client.ts +++ b/extension/src/shared/openbot-client.ts @@ -1,3 +1,12 @@ +import { + CLIENT_HEADER, + CLIENT_KINDS, + CLIENT_UPDATE_REQUIRED, + type ClientKind, + clientToken, + clientUpdateDetail, + isVersion, +} from "@openbot/shared/client-version"; import { RECORDER_SIGNED_OUT, type RecorderErrorBody, @@ -17,11 +26,44 @@ export class OpenBotError extends Error { get signedOut(): boolean { return this.status === 401 && this.body?.code === RECORDER_SIGNED_OUT; } + + /** True when OpenBot refused this Recorder as older than it serves (CLIENT_UPDATE_REQUIRED). */ + get updateRequired(): boolean { + return this.body?.code === CLIENT_UPDATE_REQUIRED; + } +} + +/** What the person reads when OpenBot serves only newer Recorders and its answer names no release we can use. */ +export const RECORDER_UPDATE_REQUIRED = + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again."; + +/** + * The sentence for OpenBot refusing this Recorder as too old, or null for any other failure. It is the Recorder's own + * sentence, the same one OpenBot words its refusal with (`clientUpdateDetail`), built from the app and release the + * answer names. The text of the answer itself is never shown: any site can answer as OpenBot, and only a known app and a + * release number pass through. + */ +export function updateRequiredSentence(error: unknown): string | null { + if (!(error instanceof OpenBotError) || !error.updateRequired) return null; + const body = error.body as Record | null; + const named = body?.client; + const kind: ClientKind = (CLIENT_KINDS as readonly unknown[]).includes(named) + ? (named as ClientKind) + : "recorder"; + const minimum = body?.minimumVersion; + return isVersion(minimum) + ? clientUpdateDetail(kind, minimum) + : RECORDER_UPDATE_REQUIRED; } type OpenBotTarget = { openbotUrl: string; token?: string }; -/** Sends the request with the bearer when there is one, never with cookies, and never follows a redirect. */ +/** + * Sends the request with the bearer when there is one, never with cookies, and never follows a redirect. Every request + * names the Recorder and the OpenBot release it was built from (`OpenBot-Client: recorder/`), so OpenBot can + * refuse a Recorder older than it serves with a sentence. These requests run in the service worker and the offscreen + * document, which the install's host access lets reach any OpenBot without a CORS preflight; never from a content script. + */ export async function openbotRaw( target: OpenBotTarget, path: string, @@ -29,6 +71,7 @@ export async function openbotRaw( ): Promise { const headers = new Headers(init.headers); if (target.token) headers.set("Authorization", `Bearer ${target.token}`); + headers.set(CLIENT_HEADER, clientToken("recorder")); const url = new URL(path, target.openbotUrl); if (url.origin !== new URL(target.openbotUrl).origin) { throw new Error( diff --git a/extension/tests/connection.test.ts b/extension/tests/connection.test.ts index c9d48745df..064f27b438 100644 --- a/extension/tests/connection.test.ts +++ b/extension/tests/connection.test.ts @@ -17,6 +17,7 @@ import { installConnection, trustedConnectRule, } from "../src/background/connection"; +import { desktopSentence } from "../src/pages/popup/desktop-sentence"; import type { RecorderPolicy } from "../src/shared/policy"; import { installIdFor, @@ -35,6 +36,23 @@ const bea = { id: "u2", name: "Bea", email: "bea@example.test" }; const HOSTILE = "Your Recorder is out of date. Install the new one from https://evil.example.test/recorder.crx."; +/** OpenBot's refusal of a Recorder older than it serves, in the shape of api/openapi/common.yaml's clientUpdateRequired + * example, for the Recorder. */ +const TOO_OLD = { + type: "https://open.bot/errors/client-update-required", + title: "This app is too old for this OpenBot.", + status: 400, + detail: + "This OpenBot needs the OpenBot Recorder 1.2.0 or later. Update OpenBot, then try again.", + code: "CLIENT_UPDATE_REQUIRED", + category: "validation", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + client: "recorder", + minimumVersion: "1.2.0", +}; + let server: ReturnType; /** * The web OpenBot most tests connect: an https site, as a hosted OpenBot is. The Recorder takes a connect from OpenBot @@ -95,6 +113,11 @@ async function openbot(request: Request): Promise { await holdIfAsked(url.pathname); if (body.code === "obc_expired") return Response.json({ error: HOSTILE }, { status: 400 }); + if (body.code === "obc_too_old") + return Response.json(TOO_OLD, { + status: 400, + headers: { "content-type": "application/problem+json" }, + }); const refused = /^obc_refused_(\d{3})$/.exec(body.code); if (refused) return Response.json({ error: HOSTILE }, { status: Number(refused[1]) }); @@ -361,6 +384,19 @@ test("a code OpenBot refuses shows the Recorder's own sentence on the Connect pa expect(await readLocal("connection")).toBeUndefined(); }); +test("an OpenBot that serves only newer Recorders says so on the Connect page, Update OpenBot, and stores nothing", async () => { + await connect("obc_too_old"); + expect( + await handleConnectionMessage({ + type: "page.connect.decide", + approve: true, + label: "x", + origin, + }), + ).toEqual({ ok: false, error: TOO_OLD.detail }); + expect(await readLocal("connection")).toBeUndefined(); +}); + test("an approve that cannot reach OpenBot shows a plain sentence, not the browser's error, and stores nothing", async () => { await connect("obc_abc"); const unreachable = spyOn(globalThis, "fetch").mockImplementation( @@ -894,6 +930,20 @@ test("a code OpenBot refuses, or an OpenBot that does not answer, stores nothing expect(await readSession("pendingConnect")).toBeUndefined(); }); +test("an OpenBot that serves only newer Recorders refuses Desktop's code with its own reason, which the popup says as Update OpenBot", async () => { + expect( + await connectThroughDesktop({ + askDesktop: async () => ({ openbotUrl: loopback, code: "obc_too_old" }), + openTab, + readPolicy: async () => policy, + }), + ).toEqual({ connected: false, reason: "client-update-required" }); + expect(desktopSentence("client-update-required")).toBe( + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", + ); + expect(await currentConnection()).toBeNull(); +}); + test("a pin elsewhere that lands while Desktop's code is exchanged keeps the connection out and revokes its new token", async () => { const exchange = holdAnswer( "/api/v2/organizations/default/recorder-connections", diff --git a/extension/tests/openbot-client.test.ts b/extension/tests/openbot-client.test.ts index 14944caec4..6dae1ee9cd 100644 --- a/extension/tests/openbot-client.test.ts +++ b/extension/tests/openbot-client.test.ts @@ -1,4 +1,6 @@ import { afterAll, beforeAll, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { deleteCurrentRecorderConnection, exchangeRecorderConnectCode, @@ -27,8 +29,17 @@ type Seen = { key: string | null; contentType: string | null; body: unknown; + /** The OpenBot-Client header: which app is asking. */ + client: string | null; }; +/** The OpenBot release this Recorder is built from: the root package.json's version, read here on its own. */ +const RELEASE = ( + JSON.parse( + readFileSync(join(import.meta.dir, "../../package.json"), "utf8"), + ) as { version: string } +).version; + /** A refusal as OpenBot's API answers one: problem details (RFC 9457). */ function problem( status: number, @@ -99,6 +110,7 @@ beforeAll(() => { key: request.headers.get("idempotency-key"), contentType: request.headers.get("content-type"), body: text ? JSON.parse(text) : null, + client: request.headers.get("openbot-client"), }; const route = `${request.method} ${url.pathname}`; // OpenBot's API, at its addresses and in its shapes, for the Recorder's own operations. @@ -251,6 +263,31 @@ test("each of the Recorder's operations goes out through the mutator: its addres expect(seen?.key).toMatch(/^[0-9a-f]{32}$/); }); +test("every request names the Recorder and the OpenBot release it was built from, a read and a write, through the generated client and openbotRaw", async () => { + const target = { openbotUrl, token: "obr_t" }; + const named = `recorder/${RELEASE}`; + await getRecorderIdentity(ORGANIZATION_ID, { target }); + expect(seen).toMatchObject({ path: API.me, client: named }); + await reportRecorderActivity( + ORGANIZATION_ID, + { phase: "recording", actions: 1 }, + { target }, + ); + expect(seen).toMatchObject({ path: API.activity, client: named }); + await exchangeRecorderConnectCode( + ORGANIZATION_ID, + { + code: "obc_abc", + label: "Work laptop", + installId: "0123456789abcdef0123456789abcdef", + }, + { target: { openbotUrl } }, + ); + expect(seen).toMatchObject({ path: API.connections, client: named }); + await openbotRaw(target, "/ok", { method: "POST", body: "{}" }); + expect(seen).toMatchObject({ path: "/ok", client: named }); +}); + test("a call that names no OpenBot is refused before any request is made", async () => { const { urls } = await recordFetch(async () => { await expect(getRecorderIdentity(ORGANIZATION_ID)).rejects.toThrow( diff --git a/extension/tests/recording.test.ts b/extension/tests/recording.test.ts index fec3e83849..54246c9a68 100644 --- a/extension/tests/recording.test.ts +++ b/extension/tests/recording.test.ts @@ -3946,6 +3946,54 @@ test("a refusal from OpenBot reaches the popup in the Recorder's own sentence, n } }); +/** OpenBot's refusal of an app older than it serves, exactly as api/openapi/common.yaml's clientUpdateRequired example + * gives it. */ +const CLIENT_UPDATE_REQUIRED_EXAMPLE = { + type: "https://open.bot/errors/client-update-required", + title: "This app is too old for this OpenBot.", + status: 400, + detail: + "This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again.", + code: "CLIENT_UPDATE_REQUIRED", + category: "validation", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + client: "desktop", + minimumVersion: "1.0.2", +}; + +test("an OpenBot that serves only newer Recorders reaches the popup as its sentence: Update OpenBot, never a plain failure and never text the server made up", async () => { + for (const [body, sentence] of [ + [CLIENT_UPDATE_REQUIRED_EXAMPLE, CLIENT_UPDATE_REQUIRED_EXAMPLE.detail], + [ + { + ...CLIENT_UPDATE_REQUIRED_EXAMPLE, + detail: + "This OpenBot needs the OpenBot Recorder 1.2.0 or later. Update OpenBot, then try again.", + client: "recorder", + minimumVersion: "1.2.0", + }, + "This OpenBot needs the OpenBot Recorder 1.2.0 or later. Update OpenBot, then try again.", + ], + [ + { + ...CLIENT_UPDATE_REQUIRED_EXAMPLE, + detail: + "Your Recorder is out of date. Install the new one from https://evil.example.test.", + client: "evil", + minimumVersion: "see https://evil.example.test", + }, + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", + ], + ] as const) { + openbot.learningRefusal = { status: 400, body }; + const answer = await page({ type: "page.learning" }); + expect(answer).toEqual({ ok: false, error: sentence }); + expect(JSON.stringify(answer)).not.toContain("evil"); + } +}); + test("page.learning reads the person's own Learning space", async () => { expect(await page({ type: "page.learning" })).toEqual({ ok: true, diff --git a/mobile/app.config.ts b/mobile/app.config.ts index 79d2723342..bb520499ce 100644 --- a/mobile/app.config.ts +++ b/mobile/app.config.ts @@ -1,6 +1,14 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import type { ExpoConfig } from "expo/config"; const projectId = process.env.EXPO_PUBLIC_EAS_PROJECT_ID; +/** The OpenBot release this app is built from: the repository's own version, which the app names on every request. */ +const openbotRelease = ( + JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8")) as { + version: string; + } +).version; const config: ExpoConfig = { name: "OpenBot", slug: "openbot", @@ -13,6 +21,6 @@ const config: ExpoConfig = { "expo-secure-store", ["expo-notifications", { defaultChannel: "openbot" }], ], - extra: { ...(projectId ? { eas: { projectId } } : {}) }, + extra: { openbotRelease, ...(projectId ? { eas: { projectId } } : {}) }, }; export default config; diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index 30a86c1254..c4c891884e 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -1,8 +1,10 @@ import * as Notifications from "expo-notifications"; import { router, Stack } from "expo-router"; import { useEffect, useRef } from "react"; +import { View } from "react-native"; import { authClient } from "../src/auth"; import { notificationDestination } from "../src/links"; +import { useVersionVerdict, VersionGate } from "../src/version-gate"; Notifications.setNotificationHandler({ handleNotification: async () => ({ @@ -14,6 +16,9 @@ Notifications.setNotificationHandler({ }); export default function Layout() { const { data: session } = authClient.useSession(); + // Asked before sign-in: whether this app and its OpenBot can work together. When they can't, one sentence covers + // the app, so no screen behind it is seen failing. + const { verdict, check } = useVersionVerdict(); const pending = useRef(null); const handled = useRef(null); useEffect(() => { @@ -35,18 +40,21 @@ export default function Layout() { return () => subscription.remove(); }, [session]); return ( - - - - - - - - - - - - - + + + + + + + + + + + + + + + void check()} /> + ); } diff --git a/mobile/app/computer.tsx b/mobile/app/computer.tsx index fac9383fd5..89769c4ecd 100644 --- a/mobile/app/computer.tsx +++ b/mobile/app/computer.tsx @@ -25,6 +25,7 @@ import { } from "../src/api/generated/computers/computers"; import type { ComputerHumanInput } from "../src/api/generated/model"; import { authClient, serverUrl } from "../src/auth"; +import { clientHeaders } from "../src/release"; import { colors, input, muted, Problem, Screen, useAction } from "../src/ui"; type Frame = { uri: string; width: number; height: number }; @@ -59,7 +60,7 @@ function useLiveFrame(botId: string, enabled: boolean) { options: { headers: Record }, ) => WebSocket; socket = new Native(url, null, { - headers: cookie ? { Cookie: cookie } : {}, + headers: { ...clientHeaders(), ...(cookie ? { Cookie: cookie } : {}) }, }); socket.onmessage = (event) => { let message: unknown; diff --git a/mobile/src/api/request.ts b/mobile/src/api/request.ts index 82cebafccf..b769e12820 100644 --- a/mobile/src/api/request.ts +++ b/mobile/src/api/request.ts @@ -4,14 +4,22 @@ * Every operation the app uses calls this with the address, method, headers and serialised body the spec gives it. It * goes to the deployment the app was built for, in the organization the signed-in person is working in, with the * session's cookie and never the platform's own cookie jar, and a refusal is thrown as an {@link ApiError} in the server's own sentence. + * Every request names the app and the OpenBot release it was built from (`OpenBot-Client: mobile/`), and a + * refusal of this app as too old (CLIENT_UPDATE_REQUIRED) is also told to the root layout, which shows Update OpenBot. */ import * as Crypto from "expo-crypto"; import { authClient, serverUrl } from "../auth"; +import { + CLIENT_UPDATE_REQUIRED, + phoneUpdateDetail, + reportUpdateRequired, +} from "../client-version"; import { createOrganizationAddress, type ListedOrganization, ORGANIZATION, } from "../organization"; +import { clientHeaders } from "../release"; import { listOrganizations } from "./generated/organizations/organizations"; /** A refusal from the server, with its status and the API's problem code when it gave one. */ @@ -92,13 +100,21 @@ const apiWrite = (url: string, method: string) => url.startsWith("/api/v2/") && method !== "GET"; /** The server's sentence for a refusal: the API's problems say it in `detail`, older routes in `error`. */ -function refusal(body: unknown): { said?: string; code?: string } { +function refusal(body: unknown): { + said?: string; + code?: string; + minimumVersion?: string; +} { if (!body || typeof body !== "object") return {}; const field = (name: string) => { const value = (body as Record)[name]; return typeof value === "string" ? value : undefined; }; - return { said: field("detail") ?? field("error"), code: field("code") }; + return { + said: field("detail") ?? field("error"), + code: field("code"), + minimumVersion: field("minimumVersion"), + }; } export async function apiRequest( @@ -114,6 +130,7 @@ export async function apiRequest( // A new key for each write, unless the caller sends its own to retry with. if (apiWrite(url, method) && !headers["idempotency-key"]) headers["idempotency-key"] = Crypto.randomUUID(); + Object.assign(headers, clientHeaders()); const cookie = await authClient.getCookie(); if (cookie) headers.cookie = cookie; const address = await inOrganization(url, cookie); @@ -126,7 +143,12 @@ export async function apiRequest( if (response.status === 204) return undefined as T; const body: unknown = await response.json().catch(() => null); if (!response.ok) { - const { said, code } = refusal(body); + const { said, code, minimumVersion } = refusal(body); + if (code === CLIENT_UPDATE_REQUIRED) { + const detail = said ?? phoneUpdateDetail(minimumVersion); + reportUpdateRequired(detail); + throw new ApiError(detail, response.status, code); + } throw new ApiError( said ?? `Request failed (${response.status}).`, response.status, diff --git a/mobile/src/auth.ts b/mobile/src/auth.ts index ce7ceefa76..2ead6e5de2 100644 --- a/mobile/src/auth.ts +++ b/mobile/src/auth.ts @@ -2,6 +2,7 @@ import { expoClient } from "@better-auth/expo/client"; import { ssoClient } from "@better-auth/sso/client"; import { createAuthClient } from "better-auth/react"; import * as SecureStore from "expo-secure-store"; +import { clientHeaders } from "./release"; const configured = process.env.EXPO_PUBLIC_SERVER_URL; if (!configured) @@ -21,6 +22,8 @@ if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash) export const serverUrl = endpoint.origin; export const authClient = createAuthClient({ baseURL: serverUrl, + // Sign-in's own requests name the app too; the Expo plugin keeps these and adds the session's cookie. + fetchOptions: { headers: clientHeaders() }, plugins: [ expoClient({ scheme: "openbotmobile", diff --git a/mobile/src/client-version.ts b/mobile/src/client-version.ts new file mode 100644 index 0000000000..976bb024fb --- /dev/null +++ b/mobile/src/client-version.ts @@ -0,0 +1,172 @@ +/** + * Whether this phone app and the OpenBot it talks to can work together, and the header it names itself in. + * + * The phone app is bundled on its own (Metro serves only mobile/), so it carries its own copy of the few rules in + * shared/client-version.ts. tests/client-version.test.ts holds this copy to every case in + * shared/fixtures/client-version/cases.json, the same cases the web app, the Recorder and OpenBot Desktop run. It + * imports nothing, so it can be tested without a phone. + */ + +/** The request header an app names itself in: `OpenBot-Client: mobile/`. */ +export const CLIENT_HEADER = "OpenBot-Client"; + +/** The problem code an OpenBot answers an app below its minimum with. */ +export const CLIENT_UPDATE_REQUIRED = "CLIENT_UPDATE_REQUIRED"; + +/** The API versions this app speaks. */ +export const API_VERSIONS: readonly string[] = ["v2"]; + +/** What a person reads when the app is older than the OpenBot it talks to serves. */ +export const APP_UPDATE_SENTENCE = "Update OpenBot"; +/** What a person reads when the OpenBot is older than the app can use. */ +export const SERVER_UPDATE_SENTENCE = + "Ask whoever runs your OpenBot to update it"; + +/** The apps that name themselves, as the server's minimums list them. */ +type ClientKind = "web" | "desktop" | "mobile" | "recorder"; + +const VERSION = + /^v?(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?:-([0-9A-Za-z.-]{1,64}))?$/; + +/** Whether `value` is a release number: `1.2.0`, `1.2.0-rc.1`, with or without a leading v. */ +export function isVersion(value: unknown): value is string { + return typeof value === "string" && VERSION.test(value); +} + +/** `/`, as an app sends it. */ +export function clientToken(kind: ClientKind, version: string) { + return `${kind}/${version}`; +} + +/** + * Release order, by semantic versioning's rules (semver.org, section 11): numbers first, and a pre-release + * (`1.2.0-rc.1`) before its release. Undefined when either is not a release number. + */ +export function compareVersions(a: string, b: string): number | undefined { + const left = VERSION.exec(a); + const right = VERSION.exec(b); + if (!left || !right) return undefined; + for (const index of [1, 2, 3]) { + const difference = Number(left[index]) - Number(right[index]); + if (difference !== 0) return Math.sign(difference); + } + const [leftPre, rightPre] = [left[4], right[4]]; + if (leftPre === rightPre) return 0; + if (leftPre === undefined) return 1; + if (rightPre === undefined) return -1; + const leftParts = leftPre.split("."); + const rightParts = rightPre.split("."); + for (let i = 0; i < Math.max(leftParts.length, rightParts.length); i++) { + const l = leftParts[i]; + const r = rightParts[i]; + if (l === undefined) return -1; + if (r === undefined) return 1; + const ln = /^\d+$/.test(l) ? Number(l) : undefined; + const rn = /^\d+$/.test(r) ? Number(r) : undefined; + if (ln !== undefined && rn !== undefined) { + if (ln !== rn) return Math.sign(ln - rn); + } else if (ln !== undefined) return -1; + else if (rn !== undefined) return 1; + else if (l !== r) return l < r ? -1 : 1; + } + return 0; +} + +/** The major of an API version, `v2` as 2. */ +function major(version: string): number | undefined { + const match = /^v(\d{1,4})$/.exec(version); + return match ? Number(match[1]) : undefined; +} + +/** + * - `ok`: they can. Features the server lacks are hidden by the fields that offer them, never by a version. + * - `app`: the app is too old. "Update OpenBot". + * - `server`: the server is too old. "Ask whoever runs your OpenBot to update it". + */ +export type Compatibility = + | { fit: "ok" } + | { fit: "app"; minimum?: string } + | { fit: "server" }; + +/** + * Whether an app and the OpenBot it talks to can work together, from that OpenBot's `deployment`. A `deployment` that + * publishes no `api` is from a release before this check, and every such release serves v2. `"before-v2"` is an + * OpenBot that answers no `deployment` but still answers as an OpenBot: a release from before the v2 API. + */ +export function compatibility( + deployment: { api?: unknown; minimumClients?: unknown } | "before-v2", + client: { kind: ClientKind; version: string; speaks?: readonly string[] }, +): Compatibility { + if (deployment === "before-v2") return { fit: "server" }; + const speaks = client.speaks ?? API_VERSIONS; + const served = Array.isArray(deployment.api) + ? deployment.api.filter( + (entry): entry is string => typeof entry === "string", + ) + : ["v2"]; + if (!served.some((version) => speaks.includes(version))) { + const newestServed = Math.max( + ...served.map(major).filter((n): n is number => n !== undefined), + ); + const newestSpoken = Math.max( + ...speaks.map(major).filter((n): n is number => n !== undefined), + ); + return newestServed > newestSpoken ? { fit: "app" } : { fit: "server" }; + } + const minimums = + deployment.minimumClients && typeof deployment.minimumClients === "object" + ? (deployment.minimumClients as Record) + : {}; + const minimum = minimums[client.kind]; + if (isVersion(minimum)) { + const order = compareVersions(client.version, minimum); + if (order !== undefined && order < 0) return { fit: "app", minimum }; + } + return { fit: "ok" }; +} + +/** + * Whether an answer at `/api/capabilities` is an OpenBot's: every OpenBot release answers there with its edition and + * what it offers, and one from before the v2 API answers nowhere else. + */ +export function isOpenBotCapabilities(body: unknown): boolean { + if (!body || typeof body !== "object") return false; + const answer = body as Record; + return ( + typeof answer.edition === "string" && + typeof answer.generativeUi === "boolean" + ); +} + +/** + * What the update screen says under "Update OpenBot": OpenBot's own sentence for refusing this app (as + * shared/client-version.ts `clientUpdateDetail` words it for the phone app), with the release it needs when known. + */ +export function phoneUpdateDetail(minimum?: string): string { + return isVersion(minimum) + ? `This OpenBot needs the OpenBot phone app ${minimum.replace(/^v/, "")} or later. Update OpenBot, then try again.` + : "This OpenBot needs a newer OpenBot phone app. Update OpenBot, then try again."; +} + +/** What the root layout shows: the app, or one of the two sentences. */ +export type VersionVerdict = + | { kind: "ok" } + | { kind: "app"; detail: string } + | { kind: "server" }; + +/** + * Anything that learns OpenBot refused this app as too old (a request's CLIENT_UPDATE_REQUIRED) says so here, and the + * root layout, which listens, shows the update screen in place of whatever was open. + */ +const listeners = new Set<(detail: string) => void>(); +export function reportUpdateRequired(detail: string): void { + for (const listener of listeners) listener(detail); +} +export function onUpdateRequired( + listener: (detail: string) => void, +): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} diff --git a/mobile/src/release.ts b/mobile/src/release.ts new file mode 100644 index 0000000000..c09e422d93 --- /dev/null +++ b/mobile/src/release.ts @@ -0,0 +1,19 @@ +/** + * The OpenBot release this app was built from, and the header that names it on every request to OpenBot. + * + * It is the version in the repository's root package.json, which app.config.ts reads as the app is built into + * `extra.openbotRelease`. Expo's own app version is a store number and says nothing about which OpenBot this is. + */ +import Constants from "expo-constants"; +import { CLIENT_HEADER, clientToken, isVersion } from "./client-version"; + +const built = (Constants.expoConfig?.extra as { openbotRelease?: unknown }) + ?.openbotRelease; + +/** Undefined only for a build whose config was not read from this repository; such a build names no release. */ +export const RELEASE: string | undefined = isVersion(built) ? built : undefined; + +/** `OpenBot-Client: mobile/`, for every request this app sends to OpenBot. */ +export function clientHeaders(): Record { + return RELEASE ? { [CLIENT_HEADER]: clientToken("mobile", RELEASE) } : {}; +} diff --git a/mobile/src/version-check.ts b/mobile/src/version-check.ts new file mode 100644 index 0000000000..1ff0cf49c5 --- /dev/null +++ b/mobile/src/version-check.ts @@ -0,0 +1,58 @@ +/** + * Whether this phone app can work with the OpenBot it was built for, asked before anybody signs in. + * + * The app reads the OpenBot's `deployment` (which answers before sign-in) and decides by the rule in ./client-version. + * An OpenBot that answers no `deployment` but answers `/api/capabilities` as an OpenBot is from before the v2 API, and + * too old. Anything else that fails here decides nothing: the screens say what failed, as they always have. + */ +import { + ApiError, + DEPLOYMENT_ORGANIZATION_ID, + apiRequest, +} from "./api/request"; +import { getDeployment } from "./api/generated/organization-settings/organization-settings"; +import { + CLIENT_UPDATE_REQUIRED, + compatibility, + isOpenBotCapabilities, + phoneUpdateDetail, + type VersionVerdict, +} from "./client-version"; +import { RELEASE } from "./release"; + +/** Whether the server answers `/api/capabilities` as an OpenBot does. */ +async function answersAsOpenBot(): Promise { + try { + return isOpenBotCapabilities( + await apiRequest("/api/capabilities"), + ); + } catch { + return false; + } +} + +export async function checkVersion(): Promise { + let deployment: Awaited>; + try { + deployment = await getDeployment(DEPLOYMENT_ORGANIZATION_ID); + } catch (error) { + if (error instanceof ApiError && error.code === CLIENT_UPDATE_REQUIRED) + return { kind: "app", detail: error.message }; + if ( + error instanceof ApiError && + error.status === 404 && + (await answersAsOpenBot()) + ) + return { kind: "server" }; + return { kind: "ok" }; + } + // A build that names no release can still tell an API it doesn't speak; it is never refused for a version. + const fit = compatibility(RELEASE ? deployment : { api: deployment.api }, { + kind: "mobile", + version: RELEASE ?? "0.0.0", + }); + if (fit.fit === "app") + return { kind: "app", detail: phoneUpdateDetail(fit.minimum) }; + if (fit.fit === "server") return { kind: "server" }; + return { kind: "ok" }; +} diff --git a/mobile/src/version-gate.tsx b/mobile/src/version-gate.tsx new file mode 100644 index 0000000000..777584bd31 --- /dev/null +++ b/mobile/src/version-gate.tsx @@ -0,0 +1,103 @@ +/** + * The screen the root layout shows in place of the app when it and its OpenBot can't work together: the app is too old + * ("Update OpenBot") or the OpenBot is ("Ask whoever runs your OpenBot to update it"). It covers everything, headers + * included, so nothing behind it is shown failing. + */ +import { useCallback, useEffect, useState } from "react"; +import { + ActivityIndicator, + AppState, + Button, + StyleSheet, + Text, + View, +} from "react-native"; +import { serverUrl } from "./auth"; +import { + APP_UPDATE_SENTENCE, + onUpdateRequired, + SERVER_UPDATE_SENTENCE, + type VersionVerdict, +} from "./client-version"; +import { heading, muted } from "./ui"; +import { checkVersion } from "./version-check"; + +/** How long the check may hold the app before it opens anyway: a slow network decides nothing. */ +const CHECK_WAIT_MS = 8_000; + +/** The decision, asked as the app opens and each time it comes back to the front, and changed by any refusal. */ +export function useVersionVerdict() { + const [verdict, setVerdict] = useState( + "checking", + ); + const check = useCallback(async () => { + let timer: ReturnType | undefined; + const waited = new Promise((resolve) => { + timer = setTimeout(() => resolve({ kind: "ok" }), CHECK_WAIT_MS); + }); + const decided = await Promise.race([checkVersion(), waited]); + clearTimeout(timer); + setVerdict(decided); + }, []); + useEffect(() => { + void check(); + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") void check(); + }); + const stop = onUpdateRequired((detail) => + setVerdict({ kind: "app", detail }), + ); + return () => { + subscription.remove(); + stop(); + }; + }, [check]); + return { verdict, check }; +} + +export function VersionGate({ + verdict, + onRetry, +}: { + verdict: VersionVerdict | "checking"; + onRetry: () => void; +}) { + if (verdict !== "checking" && verdict.kind === "ok") return null; + return ( + + {verdict === "checking" ? ( + + ) : ( + + + {verdict.kind === "app" + ? APP_UPDATE_SENTENCE + : SERVER_UPDATE_SENTENCE} + + + {verdict.kind === "app" + ? verdict.detail + : `The OpenBot at ${new URL(serverUrl).host} is on a release this app can't connect to yet.`} + + {serverUrl} + + + + ); +} + +/** The OpenBot is older than this page can use. Loading again shows whether it has been updated. */ +function ServerUpdate() { + return ( + <> + {SERVER_UPDATE_SENTENCE} + This OpenBot is on a release this page can't use yet. + + + ); +} + +/** + * OpenBot Desktop is older than the OpenBot serves. Its own Update and restart, as the update banner + * offers it, with how far the download has got; or, on a build that never updates itself, what to + * do instead. + */ +function DesktopUpdate({ minimum }: { minimum?: string }) { + const offer = useQuery(desktopAppUpdateQueryOptions()); + const install = useMutation(installAppUpdateMutationOptions(queryClient)); + const updatesItself = offer.data?.updatesItself !== false; + const progress = offer.data?.installing ?? null; + const busy = install.isPending || progress !== null; + return ( + <> + {APP_UPDATE_SENTENCE} + + {minimum + ? `This OpenBot needs OpenBot Desktop ${minimum} or later.` + : "This OpenBot needs a newer OpenBot Desktop."} + + {offer.isLoading ? null : updatesItself ? ( + + ) : ( + {DOESNT_UPDATE_ITSELF} + )} + {install.error && !busy ? ( +

+ Couldn't install the update: {reason(install.error)} +

+ ) : null} + + ); +} + +/** The desktop app refuses with its own sentence, as a plain string. */ +function reason(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/app/src/lib/auth/client.ts b/app/src/lib/auth/client.ts index 90c438cb54..b656e31fef 100644 --- a/app/src/lib/auth/client.ts +++ b/app/src/lib/auth/client.ts @@ -1,13 +1,15 @@ import { ssoClient } from "@better-auth/sso/client"; import { createAuthClient } from "better-auth/react"; +import { withClientName } from "@/lib/client"; import type { AuthProviderId } from "./queries"; export const authClient = createAuthClient({ plugins: [ssoClient()], fetchOptions: { // The page's fetch at the time of each call, as every other request in the app uses it, rather - // than the one there was when this module loaded. - customFetchImpl: (input, init) => fetch(input, init), + // than the one there was when this module loaded. Naming this app, as every request does. + customFetchImpl: (input, init) => + fetch(input, { ...init, headers: withClientName(init?.headers) }), }, }); diff --git a/app/src/lib/client-version/refusal.ts b/app/src/lib/client-version/refusal.ts new file mode 100644 index 0000000000..1d756ee764 --- /dev/null +++ b/app/src/lib/client-version/refusal.ts @@ -0,0 +1,85 @@ +/** + * Whether the OpenBot this page talks to refused it for being too old an app. + * + * Every request names this app in the `OpenBot-Client` header (`lib/client.ts`). An OpenBot whose + * oldest served release of that app is newer than it refuses every request except its `deployment` + * with a 400 problem whose code is CLIENT_UPDATE_REQUIRED, naming the app (`client`) and the oldest + * release it serves (`minimumVersion`). Inside OpenBot Desktop's window the desktop app adds its own + * name to the page's header, so there the app named can be OpenBot Desktop rather than this page. + * + * `lib/client.ts` hands every 400 here before the caller sees it. The first refusal is kept until the + * page is loaded again, and the update screen reads it (`components/layout/client-version-gate.tsx`), + * so a tab left open across an upgrade shows "Update OpenBot" in place of a screen whose read failed. + * + * No imports from the app, so the transport can report to it without a cycle. + */ +import { + CLIENT_KINDS, + CLIENT_UPDATE_REQUIRED, + type ClientKind, + isVersion, +} from "@openbot/shared/client-version"; + +/** The app the OpenBot refused, and the oldest release of it that OpenBot serves. */ +export type ClientRefusal = { client: ClientKind; minimumVersion?: string }; + +let refused: ClientRefusal | null = null; +const listeners = new Set<() => void>(); + +/** The refusal a problem body is, or null when it is some other answer. */ +export function clientRefusalOf(body: unknown): ClientRefusal | null { + if (!body || typeof body !== "object" || Array.isArray(body)) return null; + const problem = body as { + code?: unknown; + client?: unknown; + minimumVersion?: unknown; + }; + if (problem.code !== CLIENT_UPDATE_REQUIRED) return null; + // A refusal that names no app we know is still this page's to act on: it is the page that asked. + const client = (CLIENT_KINDS as readonly unknown[]).includes(problem.client) + ? (problem.client as ClientKind) + : "web"; + return isVersion(problem.minimumVersion) + ? { client, minimumVersion: problem.minimumVersion } + : { client }; +} + +/** + * A request was answered 400. Its body is read from a copy, so the caller still reads its own; the + * promise settles once it has been, so the caller can fail knowing whether this was the reason. + */ +export function noteRefusal(response: Response): Promise { + if (response.status !== 400 || refused !== null) return Promise.resolve(); + const type = response.headers.get("content-type") ?? ""; + if (!type.includes("json")) return Promise.resolve(); + return response + .clone() + .json() + .then( + (body: unknown) => { + const refusal = clientRefusalOf(body); + if (refusal === null || refused !== null) return; + refused = refusal; + for (const listener of listeners) listener(); + }, + () => undefined, + ); +} + +/** For `useSyncExternalStore`. */ +export function subscribeClientRefusal(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** The refusal this page met, or null while it has met none. */ +export function clientRefusal(): ClientRefusal | null { + return refused; +} + +/** Forget the refusal, as loading the page again does. For tests, which share one module. */ +export function forgetClientRefusal(): void { + if (refused === null) return; + refused = null; + for (const listener of listeners) listener(); +} diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index 21e481ce2f..0fcbd820f8 100644 --- a/app/src/lib/client.ts +++ b/app/src/lib/client.ts @@ -12,8 +12,47 @@ * guessed the envelope would be a client that had to be argued with. */ +import { CLIENT_HEADER, clientToken } from "@openbot/shared/client-version"; +import { noteRefusal } from "@/lib/client-version/refusal"; import { noteAnswer, noteNoAnswer } from "@/lib/desktop/reachability"; +/** + * This app as it names itself to its OpenBot: `web/`, the release it was built from + * (shared/client-version.ts). The server refuses an app older than the oldest it serves. + */ +export const CLIENT_NAME = clientToken("web"); + +/** + * `headers` with this app named in them, in the same shape they were given: a record, a `Headers`, + * or a list of pairs. For the few requests the app makes to OpenBot without the client: the + * runtime's, sign-in's and finishing a consent. A file's own address is read like a picture's, + * which carries no header either, and can be sent on to wherever the file is kept. + */ +export function withClientName( + headers: Record, +): Record; +export function withClientName(headers?: HeadersInit): HeadersInit; +export function withClientName(headers?: HeadersInit): HeadersInit { + const header = CLIENT_HEADER.toLowerCase(); + if (headers instanceof Headers) { + const named = new Headers(headers); + named.set(CLIENT_HEADER, CLIENT_NAME); + return named; + } + if (Array.isArray(headers)) { + return [ + ...headers.filter(([name]) => name.toLowerCase() !== header), + [CLIENT_HEADER, CLIENT_NAME], + ]; + } + const named: Record = {}; + for (const [name, value] of Object.entries(headers ?? {})) { + if (name.toLowerCase() !== header) named[name] = value; + } + named[CLIENT_HEADER] = CLIENT_NAME; + return named; +} + export type ClientOptions = { /** Absent means GET. */ method?: string; @@ -41,17 +80,26 @@ export type ClientOptions = { * * A 502 is read before it is handed back, so a read failing on the relay's own answer fails with * the connection already known to be lost, and waits for OpenBot (`connection-lost.ts`). + * + * Every request names this app ({@link CLIENT_NAME}). A 400 is read before it is handed back too, so + * a refusal for being too old an app is known before the request fails, and the update screen shows + * in place of whatever failed (`lib/client-version/refusal.ts`). */ async function request(path: string, init: RequestInit): Promise { let response: Response; try { - response = await fetch(path, { ...init, credentials: "include" }); + response = await fetch(path, { + ...init, + headers: withClientName(init.headers), + credentials: "include", + }); } catch (error) { noteNoAnswer(error); throw error; } const noted = noteAnswer(response); if (response.status === 502) await noted; + if (response.status === 400) await noteRefusal(response); return response; } diff --git a/app/src/lib/copilot/provider.tsx b/app/src/lib/copilot/provider.tsx index 91b1533755..8e0b797814 100644 --- a/app/src/lib/copilot/provider.tsx +++ b/app/src/lib/copilot/provider.tsx @@ -5,6 +5,7 @@ import { } from "@openbot/shared/person-time-zone"; import { useQuery } from "@tanstack/react-query"; import { type ReactNode, useMemo } from "react"; +import { withClientName } from "@/lib/client"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { organizationHeaders, @@ -50,8 +51,9 @@ export function CopilotProvider({ children }: { children: ReactNode }) { * it in the one named, when the person is a member of it. */ const organization = useCurrentOrganizationId(); + // And this app, as every request to OpenBot names it (lib/client.ts). const headers = useMemo( - () => organizationHeaders(organization), + () => withClientName(organizationHeaders(organization)), [organization], ); diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index eb6dc99e5a..f8a35f8a60 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -1,3 +1,9 @@ +import { + type ClientKind, + type Compatibility, + compatibility, + RELEASE, +} from "@openbot/shared/client-version"; import { type QueryClient, queryOptions, @@ -103,12 +109,59 @@ export async function readDeployment(options: { } } +/** An app as `compatibility` reads it: its kind, its release, and the API versions it speaks. */ +export type CompatibleApp = { + kind: ClientKind; + version: string; + speaks?: readonly string[]; +}; + +/** This app: the web app, the release it was built from, speaking this release's API versions. */ +export const THIS_APP: CompatibleApp = { kind: "web", version: RELEASE }; + export const deploymentKeys = { all: ["deployment"] as const, capabilities: () => ["deployment", "capabilities"] as const, attachmentLimits: () => ["deployment", "attachment-limits"] as const, + compatibility: (app: CompatibleApp) => + [ + "deployment", + "compatibility", + { kind: app.kind, version: app.version, speaks: app.speaks ?? null }, + ] as const, }; +/** + * Whether this app and the OpenBot it talks to can work together, as that OpenBot's `deployment` + * says: the API versions it serves and the oldest release of each app it serves + * (`compatibility` in shared/client-version.ts, which every OpenBot app decides by). + * + * `deployment` is the one read an OpenBot never refuses for the app's version, so this is how a page + * finds out before anything else fails. Read again every so often and when the tab is looked at + * again, like the attachment limits, because the OpenBot can be upgraded while the tab stays open. + * Not answered (an OpenBot from before the v2 API, or one that failed to answer) is not a verdict: + * the screens say their own failures as they always did. + * + * `app` is this app; a test names another to see the other verdicts drawn. + */ +export function deploymentCompatibilityQueryOptions( + app: CompatibleApp = THIS_APP, +) { + return queryOptions({ + queryKey: deploymentKeys.compatibility(app), + staleTime: 60_000, + refetchOnWindowFocus: true, + queryFn: async ({ signal }): Promise => + compatibility( + await readDeployment({ + signal, + fallback: "Couldn't load which apps OpenBot serves.", + }), + app, + ), + }); +} + /** * How large an attached file may be, as this server says, read again every so often. * diff --git a/app/src/lib/plugins/finish-on-return.ts b/app/src/lib/plugins/finish-on-return.ts index 24bf46dc21..cb83b38e1f 100644 --- a/app/src/lib/plugins/finish-on-return.ts +++ b/app/src/lib/plugins/finish-on-return.ts @@ -1,4 +1,5 @@ import { VERIFIER_PATH } from "@/lib/auth/resume"; +import { withClientName } from "@/lib/client"; import { desktopShell } from "@/lib/desktop/shell"; /** The step waiting for the window to be back in front, while there is one. */ @@ -45,6 +46,7 @@ export async function finishInBackground(): Promise { await fetch(VERIFIER_PATH, { credentials: "same-origin", redirect: "manual", + headers: withClientName(), }); } catch { // Nothing to tell anybody: the connections read that follows says whether it was finished. diff --git a/app/src/routes/__root.tsx b/app/src/routes/__root.tsx index 7293d47cbd..90b7b76c64 100644 --- a/app/src/routes/__root.tsx +++ b/app/src/routes/__root.tsx @@ -4,6 +4,7 @@ import { Outlet, } from "@tanstack/react-router"; import { useEffect } from "react"; +import { ClientVersionGate } from "@/components/layout/client-version-gate"; import { ThemeProvider } from "@/components/theme-provider"; import { Toaster } from "@/components/ui/toast"; import { TooltipProvider } from "@/components/ui/tooltip"; @@ -126,7 +127,10 @@ function RootComponent() {
- + {/* In place of every route when this app and its OpenBot can't work together. */} + + + diff --git a/app/tests/client-name-header.test.ts b/app/tests/client-name-header.test.ts new file mode 100644 index 0000000000..f480e0e709 --- /dev/null +++ b/app/tests/client-name-header.test.ts @@ -0,0 +1,99 @@ +/** + * Every request this app makes to its OpenBot names the app: `OpenBot-Client: web/`. + * + * The server reads the header to refuse an app older than it serves (CLIENT_UPDATE_REQUIRED) and to + * count which apps still call what. These requests leave through the app's real transport + * (`lib/client.ts`, and the generated client's mutator on top of it) and reach a real HTTP server on + * this computer, which records what arrived. The page is addressed at that server, as a page is at + * the OpenBot that served it. + */ +import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + CLIENT_HEADER, + clientToken, + RELEASE, +} from "@openbot/shared/client-version"; +import { getDeployment } from "@/lib/api/generated/organization-settings/organization-settings"; +import { listOrganizations } from "@/lib/api/generated/organizations/organizations"; +import { client, tryClient } from "@/lib/client"; +import { nativeFetch, pageFetch } from "./page-fetch"; +import { settleReactWork } from "./settle-react-work"; + +type Seen = { path: string; headers: Headers }; +let seen: Seen[] = []; +let openbot: ReturnType; +// The server answers in the runtime's own Response, not the page's. +const NativeResponse = globalThis.Response; + +beforeAll(() => { + openbot = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request) { + const path = new URL(request.url).pathname; + seen.push({ path, headers: request.headers }); + if (path.endsWith("/deployment")) + return NativeResponse.json({ edition: "team", api: ["v2"] }); + if (path === "/api/v2/people/me/organizations") + return NativeResponse.json({ organizations: [], nextCursor: null }); + return NativeResponse.json({ thing: { id: "one" } }); + }, + }); + GlobalRegistrator.register({ url: `http://127.0.0.1:${openbot.port}/` }); + // The page is at the server. + globalThis.fetch = pageFetch(); +}); +beforeEach(() => { + seen = []; +}); +afterAll(async () => { + globalThis.fetch = nativeFetch; + await settleReactWork(); + await GlobalRegistrator.unregister(); + openbot.stop(true); +}); + +const NAMED = clientToken("web", RELEASE); + +function headerAt(path: string): string | null { + const request = seen.find((one) => one.path === path); + if (!request) throw new Error(`nothing reached ${path}`); + return request.headers.get(CLIENT_HEADER); +} + +test(`a request through the client says ${NAMED}`, async () => { + expect(NAMED).toBe(`web/${RELEASE}`); + await client("/api/things/one", "thing"); + expect(headerAt("/api/things/one")).toBe(NAMED); +}); + +test("a generated operation says it too", async () => { + await getDeployment("default", { fallback: "Couldn't load OpenBot." }); + expect(headerAt("/api/v2/organizations/default/deployment")).toBe(NAMED); +}); + +test("beside the headers a caller gives, as a record or as Headers", async () => { + await tryClient("/api/things/record", { + method: "POST", + body: { a: 1 }, + headers: { "OpenBot-Organization": "default" }, + }); + const record = seen.find((one) => one.path === "/api/things/record"); + expect(record?.headers.get(CLIENT_HEADER)).toBe(NAMED); + expect(record?.headers.get("OpenBot-Organization")).toBe("default"); + expect(record?.headers.get("content-type")).toBe("application/json"); + + // getDeployment hands its options' headers to the transport as they were given: here, Headers. + await getDeployment("given", { + headers: new Headers({ "OpenBot-Organization": "default" }), + }); + const given = seen.find( + (one) => one.path === "/api/v2/organizations/given/deployment", + ); + expect(given?.headers.get(CLIENT_HEADER)).toBe(NAMED); + expect(given?.headers.get("OpenBot-Organization")).toBe("default"); + + await listOrganizations({ limit: 1 }); + expect(headerAt("/api/v2/people/me/organizations")).toBe(NAMED); +}); diff --git a/app/tests/client-version-gate.test.tsx b/app/tests/client-version-gate.test.tsx new file mode 100644 index 0000000000..8013cdf6c7 --- /dev/null +++ b/app/tests/client-version-gate.test.tsx @@ -0,0 +1,368 @@ +/** + * When this app and the OpenBot it talks to can't work together, the person reads one sentence in + * place of the app: "Update OpenBot" when the app is too old, "Ask whoever runs your OpenBot to + * update it" when the OpenBot is. Before sign-in as well as after, and nothing that fails behind it. + * + * The app is the real one at its root: the root route's own component, the sign-in screen and the + * sign-in gate, the app's query client and its transport. The OpenBot is a real HTTP server on this + * computer answering `deployment` with the real answers in shared/fixtures/client-version/cases.json, + * and refusing every other v2 operation the way an OpenBot does: an app the header names below the + * minimum its `deployment` publishes gets 400 CLIENT_UPDATE_REQUIRED, with the rules the server uses + * (shared/client-version.ts). A tab left open across an upgrade meets that refusal on any request, + * and the screen comes up the same; the spec's own example of the refusal is served for that. + */ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + APP_UPDATE_SENTENCE, + belowMinimum, + CLIENT_HEADER, + CLIENT_UPDATE_REQUIRED, + type ClientKind, + clientUpdateDetail, + compatibility, + parseClientHeader, + RELEASE, + SERVER_UPDATE_SENTENCE, +} from "@openbot/shared/client-version"; +import { DOESNT_UPDATE_ITSELF } from "@openbot/shared/desktop-updates"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + type AnyRoute, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { ClientVersionGate } from "@/components/layout/client-version-gate"; +import { forgetClientRefusal } from "@/lib/client-version/refusal"; +import type { CompatibleApp } from "@/lib/deployment/queries"; +import { queryClient } from "@/query-client"; +import type { RouterContext } from "@/router-context"; +import { Route as RootRoute } from "@/routes/__root"; +import { Route as AuthedRoute } from "@/routes/_authed"; +import { Route as SignRoute } from "@/routes/sign"; +import cases from "../../shared/fixtures/client-version/cases.json"; +import { nativeFetch, pageFetch } from "./page-fetch"; +import { settleReactWork } from "./settle-react-work"; + +type DeploymentName = keyof typeof cases.deployments; + +/** This app, as it names itself. */ +const THIS_WEB = { kind: "web" as const, version: RELEASE }; + +/** The spec's example of the refusal (api/openapi/common.yaml, `clientUpdateRequired`), as is. */ +const SPEC_REFUSAL = { + type: "https://open.bot/errors/client-update-required", + title: "This app is too old for this OpenBot.", + status: 400, + detail: + "This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again.", + code: "CLIENT_UPDATE_REQUIRED", + category: "validation", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + client: "desktop", + minimumVersion: "1.0.2", +}; + +/** What the OpenBot answers: its `deployment`, and whether it refuses every other v2 operation. */ +let deployment: DeploymentName; +let refuseEverything: boolean; +const NativeResponse = globalThis.Response; +let openbot: ReturnType; + +function problem(status: number, body: Record): Response { + return new NativeResponse(JSON.stringify({ status, ...body }), { + status, + headers: { "content-type": "application/problem+json" }, + }); +} + +function answer(request: Request): Response { + const path = new URL(request.url).pathname; + const published = cases.deployments[deployment]; + if (/^\/api\/v2\/organizations\/[^/]+\/deployment$/.test(path)) + return NativeResponse.json(published); + if (refuseEverything) return problem(400, SPEC_REFUSAL); + // A later OpenBot that serves only v3 no longer answers at v2. One that names no API serves v2. + if ("api" in published && !published.api.includes("v2")) + return problem(404, { code: "NOT_FOUND" }); + // The server's own rule: an app below the minimum the deployment publishes is refused. + const minimums = + "minimumClients" in published + ? (published.minimumClients as Partial>) + : {}; + const below = belowMinimum( + parseClientHeader(request.headers.get(CLIENT_HEADER)), + minimums, + ); + if (below) + return problem(400, { + code: CLIENT_UPDATE_REQUIRED, + detail: clientUpdateDetail(below.kind, below.minimum), + client: below.kind, + minimumVersion: below.minimum, + }); + // Nobody is signed in. + return problem(401, { + code: "UNAUTHENTICATED", + detail: "Sign in to OpenBot.", + }); +} + +beforeAll(() => { + openbot = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: answer }); + GlobalRegistrator.register({ url: `http://127.0.0.1:${openbot.port}/` }); +}); +beforeEach(() => { + deployment = "current"; + refuseEverything = false; + queryClient.clear(); + // The page is at the server. + globalThis.fetch = pageFetch(); +}); +afterEach(async () => { + cleanup(); + await settleReactWork(); + queryClient.clear(); + forgetClientRefusal(); + delete (window as unknown as Record).__TAURI_INTERNALS__; + globalThis.fetch = nativeFetch; +}); +afterAll(async () => { + await settleReactWork(); + await GlobalRegistrator.unregister(); + openbot.stop(true); +}); + +/** + * The app at `/`: the root route's own component around the real sign-in gate and sign-in screen, + * on routes of this test's own (re-parenting the app's route objects would take them out of the + * app's tree for every test after this one). `app` replaces the root with the gate for another app. + */ +function openApp(app?: CompatibleApp) { + const root = createRootRouteWithContext()({ + component: app + ? () => ( + + + + ) + : (RootRoute.options.component as () => React.JSX.Element), + }); + const gate = AuthedRoute.options as unknown as Record; + const authed = createRoute({ + id: "_authed", + getParentRoute: () => root, + component: Outlet, + ...{ beforeLoad: gate.beforeLoad, errorComponent: gate.errorComponent }, + } as never) as unknown as AnyRoute; + const home = createRoute({ + getParentRoute: () => authed, + path: "/", + component: () =>

The app

, + } as never) as unknown as AnyRoute; + const sign = SignRoute.options as unknown as Record; + const signIn = createRoute({ + getParentRoute: () => root, + path: "/sign", + ...{ + validateSearch: sign.validateSearch, + beforeLoad: sign.beforeLoad, + component: sign.component, + }, + } as never) as unknown as AnyRoute; + const router = createRouter({ + routeTree: root.addChildren([authed.addChildren([home]), signIn]), + history: createMemoryHistory({ initialEntries: ["/"] }), + context: { queryClient }, + }); + return render( + + + , + ); +} + +/** A deployment answer, as `compatibility` reads one. */ +function publishedBy(name: DeploymentName): { + api?: unknown; + minimumClients?: unknown; +} { + const answer: Record = cases.deployments[name]; + return answer; +} + +/** The fixture's verdict for an app, so the screen is held to the same cases as every other app. */ +function expected( + name: DeploymentName, + client: { kind: ClientKind; version: string; speaks?: string[] }, +) { + const listed = cases.cases.find( + (one) => + one.deployment === name && + one.client.kind === client.kind && + one.client.version === client.version && + JSON.stringify(one.client.speaks ?? null) === + JSON.stringify(client.speaks ?? null), + ); + return listed?.fit ?? compatibility(publishedBy(name), client).fit; +} + +test("an OpenBot of today: the sign-in screen, and no update screen", async () => { + expect(RELEASE).toBe("1.1.0"); + expect(expected("current", THIS_WEB)).toBe("ok"); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: /Sign in to/ }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.queryByText(APP_UPDATE_SENTENCE)).toBeNull(); + expect(view.queryByText(SERVER_UPDATE_SENTENCE)).toBeNull(); +}, 15_000); + +test("an OpenBot whose oldest web app is newer than this one: Update OpenBot, before sign-in", async () => { + deployment = "raised"; + expect(expected("raised", THIS_WEB)).toBe("app"); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This page is from an older version of OpenBot."), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + // Nothing behind it: no sign-in screen, no error screen. + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); + expect(view.queryByRole("alert")).toBeNull(); +}, 15_000); + +test("an OpenBot that serves only a newer API: Update OpenBot", async () => { + deployment = "v3-only"; + expect(compatibility(cases.deployments["v3-only"], THIS_WEB).fit).toBe("app"); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("an app that speaks only a newer API than the OpenBot serves: ask whoever runs it", async () => { + const app = { kind: "web" as const, version: "2.0.0", speaks: ["v3"] }; + expect( + expected("current", { kind: "desktop", version: "2.0.0", speaks: ["v3"] }), + ).toBe("server"); + const view = openApp(app); + expect( + await view.findByRole( + "heading", + { name: SERVER_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This OpenBot is on a release this page can't use yet."), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Try again" })).toBeTruthy(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("any request refused with CLIENT_UPDATE_REQUIRED brings up Update OpenBot, in place of what failed", async () => { + refuseEverything = true; + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + expect(view.queryByText(SPEC_REFUSAL.detail)).toBeNull(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +/** OpenBot Desktop's window around the page, answering its plugin's update commands. */ +function insideDesktop(updatesItself: boolean, installed: string[]) { + (window as unknown as Record).__TAURI_INTERNALS__ = { + invoke: async (command: string) => { + if (command === "plugin:openbot-desktop|connection") + return { mode: "connected", address: openbot.url.origin }; + if (command === "plugin:openbot-desktop|update_offer") + return { + version: null, + current: "1.0.1", + installing: null, + updatesItself, + ready: null, + }; + if (command === "plugin:openbot-desktop|install_update") { + installed.push(command); + throw "No update is available right now."; + } + throw `command ${command} not found`; + }, + transformCallback: () => 0, + }; +} + +test("inside OpenBot Desktop, a refusal naming OpenBot Desktop offers its own Update and restart", async () => { + refuseEverything = true; + const installed: string[] = []; + insideDesktop(true, installed); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This OpenBot needs OpenBot Desktop 1.0.2 or later."), + ).toBeTruthy(); + const update = await view.findByRole( + "button", + { name: "Update and restart" }, + { timeout: 5_000 }, + ); + await userEvent.click(update); + await waitFor(() => expect(installed).toHaveLength(1)); + expect( + (await view.findByRole("alert", {}, { timeout: 5_000 })).textContent, + ).toBe("Couldn't install the update: No update is available right now."); +}, 15_000); + +test("inside an OpenBot Desktop that never updates itself, it says what to do instead", async () => { + refuseEverything = true; + insideDesktop(false, []); + const view = openApp(); + expect( + await view.findByText(DOESNT_UPDATE_ITSELF, {}, { timeout: 5_000 }), + ).toBeTruthy(); + expect(view.queryByRole("button", { name: "Update and restart" })).toBeNull(); +}, 15_000); diff --git a/app/tests/connect-app-card.test.tsx b/app/tests/connect-app-card.test.tsx index abf2736d66..a6b24b230b 100644 --- a/app/tests/connect-app-card.test.tsx +++ b/app/tests/connect-app-card.test.tsx @@ -1,5 +1,6 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { CLIENT_HEADER } from "@openbot/shared/client-version"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { createMemoryHistory, @@ -11,6 +12,7 @@ import { } from "@tanstack/react-router"; import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; import { ConnectAppCard } from "@/components/channels/connect-app-card"; +import { CLIENT_NAME } from "@/lib/client"; import { carryOnMessage } from "@/lib/copilot/carry-on"; import { ConversationProvider } from "@/lib/copilot/conversation"; import { settleReactWork } from "./settle-react-work"; @@ -402,7 +404,12 @@ test("in OpenBot Desktop, coming back finishes a held consent in the background, await comeBack(card); expect(card.verifierCalls).toEqual([ - { credentials: "same-origin", redirect: "manual" }, + { + credentials: "same-origin", + redirect: "manual", + // Naming this app, as every request to OpenBot does. + headers: { [CLIENT_HEADER]: CLIENT_NAME }, + }, ]); expect(window.location.href).toBe(before); } finally { diff --git a/app/tests/page-fetch.ts b/app/tests/page-fetch.ts new file mode 100644 index 0000000000..d7ce6369a7 --- /dev/null +++ b/app/tests/page-fetch.ts @@ -0,0 +1,33 @@ +/** + * The page's `fetch`, for a test whose page is addressed at a real HTTP server on this computer. + * + * A browser resolves a request's path against the page's address and aborts it on the page's own + * signal. Under happy-dom the page's `AbortSignal` is happy-dom's, which the runtime's `fetch` + * refuses, so the abort is carried over to one of the runtime's own. Everything else is the + * runtime's real request, on the real network stack. + * + * Captured when this module loads, before a test file registers happy-dom. + */ +const nativeFetch = globalThis.fetch; +const NativeAbortController = globalThis.AbortController; + +export function pageFetch(): typeof fetch { + return Object.assign( + (input: RequestInfo | URL, init?: RequestInit) => { + const target = + typeof input === "string" ? new URL(input, location.href) : input; + const given = init?.signal; + if (!given) return nativeFetch(target, init); + const controller = new NativeAbortController(); + if (given.aborted) controller.abort(); + else + given.addEventListener("abort", () => controller.abort(), { + once: true, + }); + return nativeFetch(target, { ...init, signal: controller.signal }); + }, + { preconnect: nativeFetch.preconnect }, + ) as typeof fetch; +} + +export { nativeFetch }; From a04650c9fe3e8aeb86ccd1f9b56528703f1e2470 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 17 Nov 2026 20:18:59 -0800 Subject: [PATCH 05/12] Keep the fixture's admin raise within what a server can serve its own pages at An admin can't raise the web app's minimum above the server's own release, since every page it serves would then be refused. The raised answer now names web 1.1.0, and a separate next answer is what a tab left open across an upgrade to a 1.2.0 server meets. --- app/tests/client-version-gate.test.tsx | 4 +- shared/fixtures/client-version/cases.json | 126 ++++++++++++++++++---- 2 files changed, 109 insertions(+), 21 deletions(-) diff --git a/app/tests/client-version-gate.test.tsx b/app/tests/client-version-gate.test.tsx index 8013cdf6c7..e0392a1e24 100644 --- a/app/tests/client-version-gate.test.tsx +++ b/app/tests/client-version-gate.test.tsx @@ -238,8 +238,8 @@ test("an OpenBot of today: the sign-in screen, and no update screen", async () = }, 15_000); test("an OpenBot whose oldest web app is newer than this one: Update OpenBot, before sign-in", async () => { - deployment = "raised"; - expect(expected("raised", THIS_WEB)).toBe("app"); + deployment = "next"; + expect(expected("next", THIS_WEB)).toBe("app"); const view = openApp(); expect( await view.findByRole( diff --git a/shared/fixtures/client-version/cases.json b/shared/fixtures/client-version/cases.json index 799f70ff9a..5b2e905585 100644 --- a/shared/fixtures/client-version/cases.json +++ b/shared/fixtures/client-version/cases.json @@ -1,5 +1,5 @@ { - "$comment": "What each app decides from an OpenBot's deployment answer (shared/client-version.ts `compatibility`). The web app, the Recorder, OpenBot Desktop and the phone app each run every case. `deployments` are real answers: `current` is what this release's server answers (the back end's test holds its real answer to it), `v1.1.0` is what OpenBot 1.1.0 answers (no version fields), `raised` is this release with an admin's OPENBOT_MINIMUM_CLIENTS=desktop=1.2.0,mobile=1.2.0,recorder=1.2.0,web=1.2.0, and `v3-only` is a later OpenBot that serves only a new API. `before-v2` is an OpenBot from before the v2 API (1.0.3 and older): its deployment answers 404 and its /api/capabilities answers as `before-v2-capabilities` shows.", + "$comment": "What each app decides from an OpenBot's deployment answer (shared/client-version.ts `compatibility`). The web app, the Recorder, OpenBot Desktop and the phone app each run every case. `deployments` are real answers: `current` is what this release's server answers (the back end's test holds its real answer to it), `v1.1.0` is what OpenBot 1.1.0 answers (no version fields; captured from a running v1.1.0 server), `raised` is this release with an admin's OPENBOT_MINIMUM_CLIENTS=desktop=1.2.0,mobile=1.2.0,recorder=1.2.0,web=1.1.0 (an admin can't raise the web app above the server's own release, whose pages it serves), `next` is a 1.2.0 server whose admin raised every app to 1.2.0, as a tab left open across that upgrade meets it, and `v3-only` is a later OpenBot that serves only a new API. `before-v2` is an OpenBot from before the v2 API (1.0.3 and older): its deployment answers 404 and its /api/capabilities answers as `before-v2-capabilities` shows.", "deployments": { "current": { "edition": "team", @@ -46,6 +46,35 @@ "botComputers": true }, "raised": { + "edition": "team", + "localEvaluation": false, + "generativeUi": true, + "selfHostBanner": false, + "transcription": false, + "voice": false, + "durableHistory": true, + "authProviders": ["okta"], + "ssoConfigured": false, + "ssoRequired": false, + "builtInBots": true, + "isolatedBots": false, + "botComputers": true, + "attachmentLimits": { + "imageBytes": 8388608, + "documentBytes": 8388608, + "fileBytes": 1048576 + }, + "api": ["v2"], + "minimumClients": { + "web": "1.1.0", + "desktop": "1.2.0", + "mobile": "1.2.0", + "recorder": "1.2.0" + }, + "launcherApi": 1, + "extensionApi": 1 + }, + "next": { "edition": "team", "localEvaluation": false, "generativeUi": true, @@ -89,7 +118,9 @@ "isolatedBots": false, "botComputers": true, "api": ["v3"], - "minimumClients": { "desktop": "2.0.0" }, + "minimumClients": { + "desktop": "2.0.0" + }, "launcherApi": 2, "extensionApi": 2 } @@ -105,88 +136,145 @@ "cases": [ { "deployment": "current", - "client": { "kind": "desktop", "version": "1.1.0" }, + "client": { + "kind": "desktop", + "version": "1.1.0" + }, "fit": "ok" }, { "deployment": "current", - "client": { "kind": "web", "version": "1.1.0" }, + "client": { + "kind": "web", + "version": "1.1.0" + }, "fit": "ok" }, { "deployment": "current", - "client": { "kind": "mobile", "version": "1.1.0" }, + "client": { + "kind": "mobile", + "version": "1.1.0" + }, "fit": "ok" }, { "deployment": "current", - "client": { "kind": "recorder", "version": "1.1.0" }, + "client": { + "kind": "recorder", + "version": "1.1.0" + }, "fit": "ok" }, { "deployment": "current", - "client": { "kind": "desktop", "version": "1.0.1" }, + "client": { + "kind": "desktop", + "version": "1.0.1" + }, "fit": "app", "minimum": "1.0.2" }, { "deployment": "current", - "client": { "kind": "mobile", "version": "1.0.9" }, + "client": { + "kind": "mobile", + "version": "1.0.9" + }, "fit": "app", "minimum": "1.1.0" }, { "deployment": "current", - "client": { "kind": "desktop", "version": "1.0.2-rc.3" }, + "client": { + "kind": "desktop", + "version": "1.0.2-rc.3" + }, "fit": "app", "minimum": "1.0.2" }, { "deployment": "v1.1.0", - "client": { "kind": "desktop", "version": "1.1.0" }, + "client": { + "kind": "desktop", + "version": "1.1.0" + }, "fit": "ok" }, { "deployment": "v1.1.0", - "client": { "kind": "web", "version": "1.2.0" }, + "client": { + "kind": "web", + "version": "1.2.0" + }, "fit": "ok" }, { "deployment": "raised", - "client": { "kind": "desktop", "version": "1.1.0" }, + "client": { + "kind": "desktop", + "version": "1.1.0" + }, "fit": "app", "minimum": "1.2.0" }, { - "deployment": "raised", - "client": { "kind": "web", "version": "1.1.0" }, + "deployment": "next", + "client": { + "kind": "web", + "version": "1.1.0" + }, "fit": "app", "minimum": "1.2.0" }, { "deployment": "raised", - "client": { "kind": "desktop", "version": "1.2.0" }, + "client": { + "kind": "desktop", + "version": "1.2.0" + }, "fit": "ok" }, { "deployment": "v3-only", - "client": { "kind": "desktop", "version": "1.1.0" }, + "client": { + "kind": "desktop", + "version": "1.1.0" + }, "fit": "app" }, { "deployment": "current", - "client": { "kind": "desktop", "version": "2.0.0", "speaks": ["v3"] }, + "client": { + "kind": "desktop", + "version": "2.0.0", + "speaks": ["v3"] + }, "fit": "server" }, { "deployment": "before-v2", - "client": { "kind": "desktop", "version": "1.1.0" }, + "client": { + "kind": "desktop", + "version": "1.1.0" + }, "fit": "server" }, { "deployment": "before-v2", - "client": { "kind": "mobile", "version": "1.1.0" }, + "client": { + "kind": "mobile", + "version": "1.1.0" + }, "fit": "server" + }, + { + "deployment": "raised", + "client": { + "kind": "web", + "version": "1.1.0" + }, + "fit": "ok" } ] } From 00c38b22003faefba4d0b4ad3a168b340c93c6c3 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 17 Nov 2026 20:27:57 -0800 Subject: [PATCH 06/12] Desktop names itself to every OpenBot and says when it or the OpenBot needs an update Every request the shell makes to an OpenBot now carries OpenBot-Client: desktop/: the connect check, sign-in, refresh and revocation, the readiness and capability pings, host access, the connection watcher and the Recorder handoff. The relay adds desktop/ after whatever the window's page named, so the OpenBot sees both apps a request came through. The version is the one the app was packaged as (package_info), set at launch. Connected to a company's OpenBot, the deployment answer is now read with the shared contract's rules (client_version.rs, a port of shared/client-version.ts tested against every case in shared/fixtures/client-version/cases.json), when the person connects and on every launch: - This app too old (the OpenBot's minimum for desktop is above it, or it serves only a newer API): a new app-too-old problem, "The OpenBot at needs a newer version of this app. Update OpenBot, then connect again.", and the screen offers this app's own Update and restart. - The OpenBot too old: the existing too-old problem now says "Ask whoever runs your OpenBot to update it, or open it in your browser." An address with no deployment that still answers /api/capabilities as an OpenBot (1.0.3 and older, before the v2 API) is too old, not "no OpenBot". With its own OpenBot on this computer, the window reads that OpenBot's deployment before opening it. When it needs a newer app, the window says "Update OpenBot" with Update and restart instead of opening it, and Show Window keeps setup. An OpenBot from an older release, such as 1.1.0 with no version fields, opens exactly as before. Wherever setup shows a problem, app-too-old is drawn as a calm notice with the update, not as a failure, and the update offer at the top stands back while it shows so the window offers one Update and restart. The Desktop workflow now runs when the shared fixture changes. --- .github/workflows/desktop.yml | 4 +- api/client-boundary.allow.ts | 6 + desktop/src-tauri/src/client_version.rs | 481 ++++++++++++++++++ desktop/src-tauri/src/connected/address.rs | 147 +++++- .../src/connected/fake_openbot_tests.rs | 47 +- desktop/src-tauri/src/connected/mod.rs | 32 +- desktop/src-tauri/src/connected/relay.rs | 39 ++ desktop/src-tauri/src/connected/sign_in.rs | 43 ++ desktop/src-tauri/src/desktop_connection.rs | 1 + desktop/src-tauri/src/host_access.rs | 7 +- desktop/src-tauri/src/lib.rs | 1 + desktop/src-tauri/src/main.rs | 116 +++++ desktop/src-tauri/src/recorder_host.rs | 1 + desktop/src-tauri/src/stack.rs | 2 + desktop/src/App.test.tsx | 92 +++- desktop/src/App.tsx | 21 +- desktop/src/ConnectToOpenBot.tsx | 58 ++- desktop/src/Problem.test.tsx | 75 ++- desktop/src/Problem.tsx | 5 + desktop/src/UpdateOffer.tsx | 4 + desktop/src/UpdateOpenBot.tsx | 192 +++++++ desktop/src/setupLayout.browser.test.ts | 177 ++++++- desktop/src/styles.css | 6 + 23 files changed, 1495 insertions(+), 62 deletions(-) create mode 100644 desktop/src-tauri/src/client_version.rs create mode 100644 desktop/src/UpdateOpenBot.tsx diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index b492ff884b..2e047eb6e4 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -9,10 +9,10 @@ name: Desktop # it at runtime with an `expect`, so a bad row panics the window rather than failing a type check. on: pull_request: - paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] + paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] push: branches: [main] - paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] + paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] workflow_call: secrets: OPENBOT_GOOGLE_MODEL_OAUTH_CLIENT_SECRET: diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index 7dd7aa1964..a45ff984a8 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -340,6 +340,12 @@ export const ALLOWED: Allowed[] = [ rule: "hand-built-v2", why: "whether the address a person typed is an OpenBot, asked from Rust before anybody signs in", }, + { + file: "desktop/src-tauri/src/connected/address.rs", + what: "/api/capabilities", + rule: "before-sign-in", + why: "whether an address with no deployment is an OpenBot from before the v2 API, too old for this app, asked with no credential", + }, { file: "desktop/src-tauri/src/connected/address.rs", what: "/.well-known/oauth-authorization-server/api/auth", diff --git a/desktop/src-tauri/src/client_version.rs b/desktop/src-tauri/src/client_version.rs new file mode 100644 index 0000000000..68376f8736 --- /dev/null +++ b/desktop/src-tauri/src/client_version.rs @@ -0,0 +1,481 @@ +/*! +Which OpenBot app this is, said on every request the shell makes to an OpenBot, and whether this app +and the OpenBot it talks to can work together. + +Every OpenBot app names itself in `OpenBot-Client: /`, and every OpenBot says on its +`deployment` which API versions it serves and the oldest release of each app it still serves. When +the two don't fit, the person reads one sentence: "Update OpenBot" when this app is too old, "Ask +whoever runs your OpenBot to update it" when that OpenBot is. + +The rules are `shared/client-version.ts`'s, carried here in Rust. The tests hold them to every case +in `shared/fixtures/client-version/cases.json`, the same cases the web app, the Recorder and the +phone app run. +*/ + +use crate::problem::Problem; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; +use std::sync::OnceLock; + +/// The request header an app names itself in. +pub const HEADER: &str = "OpenBot-Client"; + +/// What this app is called in that header. +pub const KIND: &str = "desktop"; + +/// The API versions this app speaks. +pub const API_VERSIONS: &[&str] = &["v2"]; + +/// The `kind` a problem carries when this app is too old for the OpenBot it talks to. The window +/// offers this app's own update for it, wherever it shows. +pub const APP_TOO_OLD: &str = "app-too-old"; + +static VERSION: OnceLock = OnceLock::new(); + +/** +The version this app was packaged as: the one the installer, the update check and About name. Set +once at launch from the Tauri configuration (`package_info`), which is the root package.json's +version, or an internal build's own. Until then, and in a process that never starts the app (the +Recorder's native host), Cargo's, which names the same release for every released build. +*/ +pub fn set_app_version(version: impl Into) { + let _ = VERSION.set(version.into()); +} + +/// This app's version, as it names itself. +pub fn app_version() -> String { + #[cfg(test)] + if let Some(version) = TEST_VERSION.with(|version| version.borrow().clone()) { + return version; + } + VERSION + .get() + .cloned() + .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_owned()) +} + +/// `desktop/`, as this app sends it. +pub fn token() -> String { + format!("{KIND}/{}", app_version()) +} + +fn header_name() -> HeaderName { + HeaderName::from_static("openbot-client") +} + +/// The header, for a client every request of which goes to an OpenBot. +pub fn headers() -> HeaderMap { + let mut headers = HeaderMap::new(); + if let Ok(value) = HeaderValue::from_str(&token()) { + headers.insert(header_name(), value); + } + headers +} + +/** +The header the relay passes on: the one the window's page sent, with this app added after it, as a +User-Agent lists the programs a request went through. `shared/client-version.ts` reads every name in +it. When the page sent none, this app alone. +*/ +pub fn added_to(sent: &HeaderMap) -> Option { + let page: Vec<&str> = sent + .get_all(header_name()) + .iter() + .filter_map(|value| value.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .collect(); + let mine = token(); + let joined = if page.is_empty() { + mine + } else { + format!("{} {mine}", page.join(" ")) + }; + HeaderValue::from_str(&joined).ok() +} + +/// Whether an app and the OpenBot it talks to can work together. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fit { + /// They can. Features that OpenBot lacks are hidden by the fields that offer them. + Ok, + /// The app is too old: that OpenBot serves only newer API versions, or names a minimum for + /// this app above its version (`minimum`). "Update OpenBot". + App { minimum: Option }, + /// That OpenBot is too old: it serves only API versions older than any the app speaks, or it is + /// from before the v2 API. "Ask whoever runs your OpenBot to update it". + Server, +} + +/// What an OpenBot answered about itself. +#[derive(Clone, Copy, Debug)] +pub enum Deployment<'a> { + /// Its `deployment`, as it answered it. + Answered(&'a serde_json::Map), + /// No `deployment` at all, while it still answers as an OpenBot (`/api/capabilities`): a release + /// from before the v2 API, such as 1.0.3. + BeforeV2, +} + +/// The major of an API version, `v2` as 2. +fn major(version: &str) -> Option { + let digits = version.strip_prefix('v')?; + (!digits.is_empty() && digits.len() <= 4 && digits.bytes().all(|b| b.is_ascii_digit())) + .then(|| digits.parse().ok()) + .flatten() +} + +/// A release number's parts: `1.2.0-rc.1` as (1, 2, 0) and `rc.1`, with or without a leading v. +fn release(value: &str) -> Option<([u64; 3], Option<&str>)> { + let value = value.strip_prefix('v').unwrap_or(value); + let (core, pre) = match value.split_once('-') { + Some((core, pre)) => (core, Some(pre)), + None => (value, None), + }; + if let Some(pre) = pre { + let allowed = |b: u8| b.is_ascii_alphanumeric() || b == b'.' || b == b'-'; + if pre.is_empty() || pre.len() > 64 || !pre.bytes().all(allowed) { + return None; + } + } + let mut parts = [0u64; 3]; + let mut pieces = core.split('.'); + for part in &mut parts { + let piece = pieces.next()?; + if piece.is_empty() || piece.len() > 6 || !piece.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + *part = piece.parse().ok()?; + } + pieces.next().is_none().then_some((parts, pre)) +} + +/// Whether `value` is a release number: `1.2.0`, `1.2.0-rc.1`, with or without a leading v. +pub fn is_version(value: &str) -> bool { + release(value).is_some() +} + +/** +Release order, by semantic versioning's rules (semver.org, section 11): numbers first, and a +pre-release (`1.2.0-rc.1`) before its release. None when either is not a release number. +*/ +pub fn compare_versions(a: &str, b: &str) -> Option { + use std::cmp::Ordering; + let (left, left_pre) = release(a)?; + let (right, right_pre) = release(b)?; + let order = left.cmp(&right); + if order != Ordering::Equal { + return Some(order); + } + Some(match (left_pre, right_pre) { + (None, None) => Ordering::Equal, + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(left), Some(right)) => { + let (mut left, mut right) = (left.split('.'), right.split('.')); + loop { + match (left.next(), right.next()) { + (None, None) => break Ordering::Equal, + (None, Some(_)) => break Ordering::Less, + (Some(_), None) => break Ordering::Greater, + (Some(l), Some(r)) => { + let number = |s: &str| { + (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) + .then(|| s.parse::().ok()) + .flatten() + }; + let order = match (number(l), number(r)) { + (Some(l), Some(r)) => l.cmp(&r), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => l.cmp(r), + }; + if order != Ordering::Equal { + break order; + } + } + } + } + } + }) +} + +/** +Whether an app of `kind` at `version`, speaking `speaks`, and the OpenBot that answered `deployment` +can work together. A `deployment` that publishes no `api` is from a release before it was +published, and every such release that answers `deployment` serves v2. +*/ +pub fn compatibility(deployment: Deployment, kind: &str, version: &str, speaks: &[&str]) -> Fit { + let Deployment::Answered(deployment) = deployment else { + return Fit::Server; + }; + let served: Vec<&str> = match deployment.get("api") { + Some(serde_json::Value::Array(api)) => { + api.iter().filter_map(serde_json::Value::as_str).collect() + } + _ => vec!["v2"], + }; + if !served.iter().any(|version| speaks.contains(version)) { + // None is below every major, as an empty list's largest is. + let newest_served = served.iter().filter_map(|v| major(v)).max(); + let newest_spoken = speaks.iter().filter_map(|v| major(v)).max(); + // Only newer versions than any the app speaks: the app is behind. Otherwise the server is. + return if newest_served > newest_spoken { + Fit::App { minimum: None } + } else { + Fit::Server + }; + } + let minimum = deployment + .get("minimumClients") + .and_then(serde_json::Value::as_object) + .and_then(|minimums| minimums.get(kind)) + .and_then(serde_json::Value::as_str) + .filter(|minimum| is_version(minimum)); + if let Some(minimum) = minimum { + if compare_versions(version, minimum) == Some(std::cmp::Ordering::Less) { + return Fit::App { + minimum: Some(minimum.to_owned()), + }; + } + } + Fit::Ok +} + +/// [`compatibility`] for this app. +pub fn fit(deployment: Deployment) -> Fit { + compatibility(deployment, KIND, &app_version(), API_VERSIONS) +} + +/// Why it doesn't fit, for the log: what that OpenBot said, against this app. +pub fn why(deployment: Deployment, fit: &Fit) -> String { + let this = format!( + "this app is {} and speaks {}", + token(), + API_VERSIONS.join(", ") + ); + let served = match deployment { + Deployment::BeforeV2 => { + return format!("the OpenBot answers no deployment, from before the v2 API; {this}") + } + Deployment::Answered(deployment) => deployment + .get("api") + .map_or_else(|| "no api (v2)".to_owned(), |api| format!("api {api}")), + }; + match fit { + Fit::App { + minimum: Some(minimum), + } => format!("the deployment's minimumClients.{KIND} is {minimum}; {this}"), + _ => format!("the deployment says {served}; {this}"), + } +} + +/// What the person reads when the OpenBot on this computer needs a newer version of this app. +pub const LOCAL_APP_TOO_OLD: &str = + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going."; + +/** +Whether the OpenBot on this computer, at `base` (`http://127.0.0.1:` of its server), needs a +newer version of this app: its `deployment` read the way every app reads it, with the install's +token when it has one. Only that is a problem. An OpenBot from an older release, one that answers +no `deployment`, or one that does not answer at all, starts and opens exactly as before: Start +upgrades an older one, and a missing answer is the readiness check's to report, not this one's. +*/ +pub fn local_problem(base: &str, install_token: Option<&str>) -> Option { + let client = reqwest::blocking::Client::builder() + .timeout(std::time::Duration::from_secs(3)) + .redirect(reqwest::redirect::Policy::none()) + .default_headers(headers()) + .build() + .ok()?; + let mut request = client + .get(format!( + "{}{}", + base.trim_end_matches('/'), + crate::connected::address::DEPLOYMENT + )) + .header(reqwest::header::ACCEPT, "application/json"); + if let Some(token) = install_token.filter(|token| !token.trim().is_empty()) { + request = request.header(crate::install_token::HEADER, token); + } + let answered = request.send().ok()?; + if !answered.status().is_success() { + return None; + } + let serde_json::Value::Object(deployment) = answered.json::().ok()? else { + return None; + }; + let read = Deployment::Answered(&deployment); + let decided = fit(read); + let Fit::App { .. } = decided else { + return None; + }; + let mut problem = Problem::with(LOCAL_APP_TOO_OLD, why(read, &decided)); + problem.kind = Some(APP_TOO_OLD); + Some(problem) +} + +#[cfg(test)] +thread_local! { + static TEST_VERSION: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// This app is `version` on this thread until the guard goes, so a test reads the fixture's real +/// answers against the release they were written for, whatever this build's version is. +#[cfg(test)] +pub(crate) fn as_version(version: &str) -> impl Drop { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + let earlier = self.0.take(); + TEST_VERSION.with(|version| *version.borrow_mut() = earlier); + } + } + let earlier = TEST_VERSION.with(|current| current.borrow_mut().replace(version.to_owned())); + Restore(earlier) +} + +/// The shared fixture: real deployment answers, and what each app decides from them. +#[cfg(test)] +pub(crate) const CASES: &str = include_str!("../../../shared/fixtures/client-version/cases.json"); + +/// One of the fixture's real deployment answers, by name. +#[cfg(test)] +pub(crate) fn fixture_deployment(name: &str) -> serde_json::Value { + let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); + if name == "before-v2-capabilities" { + return cases["before-v2-capabilities"].clone(); + } + let found = cases["deployments"][name].clone(); + assert!(found.is_object(), "the fixture has no deployment {name}"); + found +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every case the shared fixture lists, decided as `shared/client-version.ts` decides it. + #[test] + fn every_case_in_the_shared_fixture_is_decided_as_the_contract_says() { + let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); + let list = cases["cases"].as_array().unwrap(); + assert!(list.len() >= 16, "the fixture lost its cases"); + for case in list { + let name = case["deployment"].as_str().unwrap(); + let client = &case["client"]; + let speaks: Vec<&str> = client["speaks"] + .as_array() + .map(|speaks| speaks.iter().filter_map(|v| v.as_str()).collect()) + .unwrap_or_else(|| API_VERSIONS.to_vec()); + let answered = (name != "before-v2") + .then(|| cases["deployments"][name].as_object().unwrap().clone()); + let deployment = answered + .as_ref() + .map_or(Deployment::BeforeV2, Deployment::Answered); + let decided = compatibility( + deployment, + client["kind"].as_str().unwrap(), + client["version"].as_str().unwrap(), + &speaks, + ); + let expected = match case["fit"].as_str().unwrap() { + "ok" => Fit::Ok, + "server" => Fit::Server, + "app" => Fit::App { + minimum: case["minimum"].as_str().map(str::to_owned), + }, + other => panic!("an unknown fit {other}"), + }; + assert_eq!(decided, expected, "{case}"); + } + } + + /// Release order as semver.org section 11 has it, which the TypeScript rule follows. + #[test] + fn releases_are_ordered_as_semantic_versioning_orders_them() { + use std::cmp::Ordering::*; + for (a, b, order) in [ + ("1.0.2", "1.0.2", Equal), + ("v1.0.2", "1.0.2", Equal), + ("1.0.1", "1.0.2", Less), + ("1.10.0", "1.9.9", Greater), + ("1.0.2-rc.3", "1.0.2", Less), + ("1.0.0-alpha", "1.0.0-alpha.1", Less), + ("1.0.0-alpha.1", "1.0.0-alpha.beta", Less), + ("1.0.0-alpha.beta", "1.0.0-beta", Less), + ("1.0.0-beta.2", "1.0.0-beta.11", Less), + ("1.0.0-rc.1", "1.0.0", Less), + ("1.1.0-internal.892.g0c140734ecf0", "1.1.0", Less), + ] { + assert_eq!(compare_versions(a, b), Some(order), "{a} {b}"); + } + for not_a_release in [ + "", + "1.2", + "1.2.3.4", + "1.2.x", + "1.2.3-", + "1234567.0.0", + "1.2.3-a b", + ] { + assert!(!is_version(not_a_release), "{not_a_release}"); + assert_eq!(compare_versions(not_a_release, "1.0.0"), None); + } + } + + /// The OpenBot on this computer, read as every app reads it, through the real HTTP path with + /// the fixture's real answers. Only an OpenBot that needs a newer app is a problem: one of this + /// release, one left at 1.1.0 (no version fields), one from before the v2 API and one that is + /// not answering all start and open as before, with no sentence. + #[test] + fn the_openbot_on_this_computer_says_update_openbot_only_when_it_needs_a_newer_app() { + use crate::connected::fake_openbot::{FakeOpenBot, Shape}; + let _version = as_version("1.1.0"); + for (shape, too_old) in [ + (Shape::Answers("raised"), true), + (Shape::Answers("v3-only"), true), + (Shape::Answers("current"), false), + (Shape::Answers("v1.1.0"), false), + (Shape::BeforeV2, false), + ] { + let server = FakeOpenBot::start(shape.clone()); + let problem = local_problem(&server.address(), Some("install-token-abc")); + assert_eq!(problem.is_some(), too_old, "{shape:?}: {problem:?}"); + if let Some(problem) = problem { + assert_eq!(problem.kind, Some(APP_TOO_OLD)); + assert_eq!( + problem.said, + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going." + ); + } + let asked = server.seen_at(crate::connected::address::DEPLOYMENT); + assert_eq!(asked.len(), 1, "{shape:?}"); + assert_eq!(asked[0].header("openbot-client"), Some("desktop/1.1.0")); + assert_eq!( + asked[0].header(crate::install_token::HEADER), + Some("install-token-abc") + ); + } + // Nothing listening: the readiness check says that, not this. + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + assert!(local_problem(&format!("http://127.0.0.1:{port}"), None).is_none()); + } + + /// The relay names this app after whatever the page named, and only this app when it named none. + #[test] + fn the_header_names_this_app_after_the_page() { + let _version = as_version("1.1.0"); + assert_eq!(token(), "desktop/1.1.0"); + assert_eq!(headers()["openbot-client"], "desktop/1.1.0"); + let mut sent = HeaderMap::new(); + assert_eq!(added_to(&sent).unwrap(), "desktop/1.1.0"); + sent.insert(header_name(), HeaderValue::from_static("web/1.1.0")); + assert_eq!(added_to(&sent).unwrap(), "web/1.1.0 desktop/1.1.0"); + sent.insert(header_name(), HeaderValue::from_static(" ")); + assert_eq!(added_to(&sent).unwrap(), "desktop/1.1.0"); + } +} diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs index 0782f5542d..11544a8e3d 100644 --- a/desktop/src-tauri/src/connected/address.rs +++ b/desktop/src-tauri/src/connected/address.rs @@ -3,13 +3,20 @@ //! //! Two questions are asked of the address, both public: what it offers //! (`/api/v2/organizations/default/deployment`, which every OpenBot answers before sign-in) and -//! how an app signs in to it (its authorization server metadata, RFC 8414). Each way that can go -//! wrong is one `Kind`, so the window can say what to do next. +//! how an app signs in to it (its authorization server metadata, RFC 8414). What it offers says +//! whether this app and that OpenBot fit (`client_version`). An address with no `deployment` is +//! asked one more: whether it is an OpenBot from before the v2 API. Each way that can go wrong is +//! one `Kind`, so the window can say what to do next. use super::{host_of, http, transport, Kind}; +use crate::client_version; use crate::problem::Problem; -const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment"; +/// What an OpenBot offers, which every OpenBot answers before sign-in. Read here, and of the OpenBot +/// on this computer (`client_version::local_problem`). +pub const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment"; +/// What an OpenBot from before the v2 API answers in place of `DEPLOYMENT`, before sign-in. +const CAPABILITIES: &str = "/api/capabilities"; const METADATA: &str = "/.well-known/oauth-authorization-server/api/auth"; /// What keeps a sign-in going after its first hour: a refresh token. const OFFLINE_ACCESS: &str = "offline_access"; @@ -90,21 +97,53 @@ pub fn probe(address: &str) -> Result { .as_ref() .and_then(|deployment| deployment.get("edition")) .and_then(serde_json::Value::as_str); - let Some(edition) = edition else { - return Err(Kind::NotOpenBot.problem( - &host, - format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"), - )); + let (Some(deployment), Some(edition)) = (deployment.as_ref(), edition) else { + // No `deployment`. An OpenBot from before the v2 API (1.0.3 and older) still answers what + // it offers at `/api/capabilities`: that one is too old for this app, not missing. + let missing = format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"); + let before_v2 = get(CAPABILITIES).ok().is_some_and(|older| { + let answered = older.status().is_success(); + json_object(older) + .filter(|_| answered) + .is_some_and(|capabilities| { + capabilities.get("edition").is_some_and(|e| e.is_string()) + }) + }); + return Err(if before_v2 { + let fit = client_version::Fit::Server; + Kind::TooOld.problem( + &host, + format!( + "{missing}; GET {CAPABILITIES} answered as an OpenBot does: {}", + client_version::why(client_version::Deployment::BeforeV2, &fit) + ), + ) + } else { + Kind::NotOpenBot.problem(&host, missing) + }); }; let on_its_own_computer = deployment - .as_ref() - .and_then(|deployment| deployment.get("localEvaluation")) + .get("localEvaluation") .and_then(serde_json::Value::as_bool) .unwrap_or(false); if on_its_own_computer { return Err(Kind::SinglePerson.problem(&host, "the deployment says localEvaluation")); } + // Which API versions it serves and the oldest release of this app it serves, decided as every + // OpenBot app decides it (`client_version`): asked when the person connects and on every + // launch, so an OpenBot upgraded past this app since, or moved back, is caught. + let read = client_version::Deployment::Answered(deployment); + match client_version::fit(read) { + client_version::Fit::Ok => {} + fit @ client_version::Fit::App { .. } => { + return Err(Kind::AppTooOld.problem(&host, client_version::why(read, &fit))); + } + fit @ client_version::Fit::Server => { + return Err(Kind::TooOld.problem(&host, client_version::why(read, &fit))); + } + } + let answered = get(METADATA)?; let status = answered.status(); let Some(document) = json_object(answered).filter(|_| status.is_success()) else { @@ -315,6 +354,94 @@ mod tests { assert_eq!(kind(&server.address()), Some(Kind::TooOld)); } + /// OpenBot 1.0.3 and older, from before the v2 API: no `deployment` (404), but + /// `/api/capabilities` answers as an OpenBot does. That is an OpenBot too old for this app, and + /// the person is told so, not that there is no OpenBot at the address they typed. + #[test] + fn an_openbot_from_before_the_v2_api_is_too_old_not_missing() { + let server = FakeOpenBot::start(Shape::BeforeV2); + let problem = check(&server.address()).expect_err("too old"); + assert_eq!(kind_of(&problem), Some(Kind::TooOld)); + assert_eq!( + problem.said, + format!( + "The OpenBot at {} is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser.", + host_of(&server.address()) + ) + ); + // What the log says beside it. + assert_eq!( + problem.detail, + Some(format!( + "GET {DEPLOYMENT} answered 404 Not Found, not as an OpenBot does; GET {CAPABILITIES} answered as an OpenBot does: the OpenBot answers no deployment, from before the v2 API; this app is {} and speaks v2", + crate::client_version::token() + )) + ); + // Not a sign-in it can't do: nothing past the two questions is asked. + assert!(server.seen_at(METADATA).is_empty()); + // Something else that answers JSON at both addresses is still not an OpenBot. + let other = FakeOpenBot::start(Shape::OtherJson); + assert_eq!(kind(&other.address()), Some(Kind::NotOpenBot)); + } + + /// The fixture's real answers (`shared/fixtures/client-version/cases.json`), as this release's + /// app reads them through the real HTTP path. An OpenBot of this release, and one of 1.1.0 + /// (which publishes no version fields), connect. One whose admin raised the oldest app it + /// serves above this one, and one that serves only a newer API, say "Update OpenBot", and the + /// app asks nothing more of them. + #[test] + fn an_openbot_this_app_is_too_old_for_says_update_openbot_and_the_rest_connect() { + let _version = crate::client_version::as_version("1.1.0"); + for name in ["current", "v1.1.0"] { + let server = FakeOpenBot::start(Shape::Answers(name)); + let (address, metadata) = check(&server.address()).unwrap_or_else(|problem| { + panic!("{name}: {problem:?}"); + }); + assert_eq!(address, server.address(), "{name}"); + assert!(metadata + .scopes + .iter() + .any(|scope| scope == "offline_access")); + } + for name in ["raised", "v3-only"] { + let server = FakeOpenBot::start(Shape::Answers(name)); + let problem = check(&server.address()).expect_err(name); + assert_eq!(kind_of(&problem), Some(Kind::AppTooOld), "{name}"); + assert_eq!( + problem.said, + format!( + "The OpenBot at {} needs a newer version of this app. Update OpenBot, then connect again.", + host_of(&server.address()) + ), + "{name}" + ); + assert!(server.seen_at(METADATA).is_empty(), "{name}"); + } + // What the log says beside the sentence: what that OpenBot asked for, against this app. + let raised = FakeOpenBot::start(Shape::Answers("raised")); + let problem = check(&raised.address()).expect_err("raised"); + assert_eq!( + problem.detail.as_deref(), + Some("the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2") + ); + } + + /// The check runs on every launch while connected (`probe`, before the saved sign-in is used), + /// not only when the person connects: an OpenBot upgraded past the app since, or moved back, + /// is caught the next time the app opens. + #[test] + fn the_launch_check_catches_an_openbot_that_moved_since_the_app_connected() { + let _version = crate::client_version::as_version("1.1.0"); + for (name, kind) in [("raised", Kind::AppTooOld), ("v3-only", Kind::AppTooOld)] { + let server = FakeOpenBot::start(Shape::Answers(name)); + let problem = probe(&server.address()).expect_err(name); + assert_eq!(kind_of(&problem), Some(kind), "{name}"); + } + let older = FakeOpenBot::start(Shape::BeforeV2); + let problem = probe(&older.address()).expect_err("before v2"); + assert_eq!(kind_of(&problem), Some(Kind::TooOld)); + } + /// The browser is sent to the authorization endpoint and the code is posted to the token /// endpoint. Metadata that names another host for either is not followed there. #[test] diff --git a/desktop/src-tauri/src/connected/fake_openbot_tests.rs b/desktop/src-tauri/src/connected/fake_openbot_tests.rs index 7f25660f84..c2081fe177 100644 --- a/desktop/src-tauri/src/connected/fake_openbot_tests.rs +++ b/desktop/src-tauri/src/connected/fake_openbot_tests.rs @@ -2,7 +2,9 @@ A stand-in for an OpenBot that runs elsewhere, for this module's tests: a real HTTP server on a loopback port that answers the addresses the app uses as the real one does. -- the public deployment answer and the authorization server metadata (RFC 8414), at the real paths; +- the public deployment answer and the authorization server metadata (RFC 8414), at the real paths, + the deployment as one of the real answers in `shared/fixtures/client-version/cases.json` when + asked (`Shape::Answers`), and `/api/capabilities` as an OpenBot from before the v2 API answers it; - the authorization endpoint, which accepts only the public client, `response_type=code`, an S256 challenge and a redirect of exactly `http://127.0.0.1:/callback`, and sends the browser back with a code or with `error=access_denied`; @@ -60,6 +62,13 @@ pub enum Shape { InfoAnswers(u16), /// Its revocation endpoint fails with a 500 whatever it is sent. RevokeBroken, + /// Signs in as `Current` does, and answers `deployment` with one of the real answers in + /// `shared/fixtures/client-version/cases.json`, by name: `current`, `v1.1.0`, `raised` or + /// `v3-only`. + Answers(&'static str), + /// An OpenBot from before the v2 API, as 1.0.3 answers: `deployment` is 404, `/api/capabilities` + /// answers as the fixture's `before-v2-capabilities`, and apps can't sign in to it. + BeforeV2, } const SCOPES: [&str; 4] = ["openid", "profile", "offline_access", "openbot"]; @@ -416,21 +425,37 @@ async fn answer( ) }; Ok(match (method.as_str(), path.as_str()) { - ("GET", "/api/v2/organizations/default/deployment") => json( + ("GET", "/api/v2/organizations/default/deployment") => match &shape { + Shape::Answers(name) => json( + StatusCode::OK, + crate::client_version::fixture_deployment(name), + ), + Shape::BeforeV2 => json( + StatusCode::NOT_FOUND, + serde_json::json!({ "error": "not_found" }), + ), + _ => json( + StatusCode::OK, + serde_json::json!({ + "edition": if shape == Shape::Personal { "personal" } else { "team" }, + "localEvaluation": shape == Shape::LocalEvaluation, + "generativeUi": true, + "authProviders": ["google"], + "ssoConfigured": false, + "ssoRequired": false, + }), + ), + }, + // Every OpenBot answers what it offers here, before sign-in, the releases from before the + // v2 API included. + ("GET", "/api/capabilities") => json( StatusCode::OK, - serde_json::json!({ - "edition": if shape == Shape::Personal { "personal" } else { "team" }, - "localEvaluation": shape == Shape::LocalEvaluation, - "generativeUi": true, - "authProviders": ["google"], - "ssoConfigured": false, - "ssoRequired": false, - }), + crate::client_version::fixture_deployment("before-v2-capabilities"), ), ("GET", "/.well-known/oauth-authorization-server/api/auth") => { if matches!( shape, - Shape::NoMetadata | Shape::Personal | Shape::LocalEvaluation + Shape::NoMetadata | Shape::Personal | Shape::LocalEvaluation | Shape::BeforeV2 ) { return Ok(json( StatusCode::NOT_FOUND, diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs index 2af37736c4..b68e143674 100644 --- a/desktop/src-tauri/src/connected/mod.rs +++ b/desktop/src-tauri/src/connected/mod.rs @@ -40,7 +40,10 @@ pub enum Kind { Unreachable, NotOpenBot, SinglePerson, + /// That OpenBot is older than this app can use: the window offers it in the browser. TooOld, + /// This app is older than that OpenBot serves: the window offers this app's own update. + AppTooOld, SignInCancelled, SignInFailed, /// Signed in, and then the OpenBot refused the new sign-in on the app's screens (401 or 403). @@ -57,6 +60,7 @@ impl Kind { Kind::NotOpenBot => "not-openbot", Kind::SinglePerson => "single-person", Kind::TooOld => "too-old", + Kind::AppTooOld => crate::client_version::APP_TOO_OLD, Kind::SignInCancelled => "sign-in-cancelled", Kind::SignInFailed => "sign-in-failed", Kind::AccessRefused => "access-refused", @@ -83,7 +87,11 @@ impl Kind { ), Kind::TooOld => format!( "The OpenBot at {host} is on a release this app can't connect to yet. Ask whoever \ - runs it to update OpenBot, or open it in your browser." + runs your OpenBot to update it, or open it in your browser." + ), + Kind::AppTooOld => format!( + "The OpenBot at {host} needs a newer version of this app. Update OpenBot, then \ + connect again." ), Kind::SignInCancelled => "Sign-in didn't finish. Try again when you're ready.".into(), Kind::SignInFailed => format!( @@ -124,6 +132,7 @@ pub fn kind_of(problem: &Problem) -> Option { Kind::NotOpenBot, Kind::SinglePerson, Kind::TooOld, + Kind::AppTooOld, Kind::SignInCancelled, Kind::SignInFailed, Kind::AccessRefused, @@ -149,8 +158,9 @@ pub fn host_of(address: &str) -> String { .unwrap_or_else(|| address.to_owned()) } -/// A client for the few requests the shell itself makes to that OpenBot: short timeouts, and a -/// redirect followed only while it stays on the same host. +/// A client for the few requests the shell itself makes to that OpenBot: short timeouts, a +/// redirect followed only while it stays on the same host, and this app named on every one +/// (`client_version`). pub(crate) fn http() -> Result { reqwest::blocking::Client::builder() .connect_timeout(std::time::Duration::from_secs(10)) @@ -168,6 +178,7 @@ pub(crate) fn http() -> Result { } })) .user_agent("OpenBot/desktop") + .default_headers(crate::client_version::headers()) .build() .map_err(|error| error.to_string()) } @@ -208,9 +219,22 @@ mod tests { Kind::SessionEnded.said("openbot.example.com"), "Your sign-in to openbot.example.com has ended. Sign in again to keep going." ); + // The two sentences every OpenBot app says when it and the OpenBot don't fit + // (`shared/client-version.ts`): "Ask whoever runs your OpenBot to update it" when that + // OpenBot is too old, "Update OpenBot" when this app is. assert_eq!( Kind::TooOld.said("127.0.0.1:4000"), - "The OpenBot at 127.0.0.1:4000 is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser." + "The OpenBot at 127.0.0.1:4000 is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser." + ); + assert_eq!( + Kind::AppTooOld.said("openbot.example.com"), + "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again." + ); + let too_old = Kind::AppTooOld.problem("openbot.example.com", "minimum 1.2.0"); + assert_eq!(kind_of(&too_old), Some(Kind::AppTooOld)); + assert_eq!( + serde_json::to_value(&too_old).unwrap()["kind"], + "app-too-old" ); let refused = Kind::AccessRefused.problem("openbot.example.com", "answered 403"); assert_eq!(kind_of(&refused), Some(Kind::AccessRefused)); diff --git a/desktop/src-tauri/src/connected/relay.rs b/desktop/src-tauri/src/connected/relay.rs index 1caf8215ae..9d1289f759 100644 --- a/desktop/src-tauri/src/connected/relay.rs +++ b/desktop/src-tauri/src/connected/relay.rs @@ -25,6 +25,9 @@ What keeps it to that: - On the way out it drops `Origin`, `Cookie`, `Referer`, `Forwarded` and `X-Forwarded-*`, and any `Authorization` the page sent. On the way back it drops `Set-Cookie`. +It adds this app to the `OpenBot-Client` header the page sent, or sends this app's alone, so the +OpenBot knows which apps a request came through (`client_version`). + Bodies are passed on as they arrive, both ways, so a chat answer streams. A WebSocket upgrade is passed on and the two connections are joined. @@ -317,6 +320,8 @@ fn dropped_on_the_way_out(name: &HeaderName) -> bool { || name.starts_with("sec-fetch-") // The shell names the organisation, not the page. || name.eq_ignore_ascii_case(ORGANIZATION_HEADER) + // Passed on with this app added after it (`client_version::added_to`). + || name.eq_ignore_ascii_case(crate::client_version::HEADER) } /// Whether a request for `path` is one of OpenBot's own that takes the person's sign-in: its API, @@ -431,6 +436,14 @@ async fn answer(mut request: Request, shared: Arc) -> Response } headers.append(name.clone(), value.clone()); } + // Which apps the request came through: the page's own name, then this app's. On everything it + // passes on, so OpenBot knows this app is asking whatever the page is. + if let (Ok(name), Some(named)) = ( + HeaderName::from_bytes(crate::client_version::HEADER.as_bytes()), + crate::client_version::added_to(request.headers()), + ) { + headers.insert(name, named); + } // The person's sign-in and their organisation, for OpenBot's own API only. let signed_in = carries_the_sign_in(request.uri().path()); let organization = shared @@ -1004,6 +1017,32 @@ mod tests { assert!(!sent.to_string().contains(&window.cookie)); } + /// OpenBot hears which apps a request came through: the name the window's page gave, then this + /// app's, on OpenBot's API and on its pages alike. A page that names none is this app alone. + #[test] + fn openbot_hears_the_pages_app_and_then_this_one() { + let rig = rig(); + let window = rig.window(); + let mine = format!("desktop/{}", crate::client_version::app_version()); + let sent = window.echo(window.get(ECHO).header("openbot-client", "web/1.1.0")); + assert_eq!( + sent["headers"]["openbot-client"], + format!("web/1.1.0 {mine}") + ); + let sent = window.echo(window.get(ECHO)); + assert_eq!(sent["headers"]["openbot-client"], mine.as_str()); + let page = window + .get("/landing") + .header("openbot-client", "web/1.1.0") + .send() + .unwrap(); + assert_eq!(page.status(), 200); + assert_eq!( + rig.openbot.seen_at("/landing")[0].header("openbot-client"), + Some(format!("web/1.1.0 {mine}").as_str()) + ); + } + #[test] fn a_cookie_openbot_sets_does_not_come_back() { let rig = rig(); diff --git a/desktop/src-tauri/src/connected/sign_in.rs b/desktop/src-tauri/src/connected/sign_in.rs index 8b4bf83b76..567fd41e2d 100644 --- a/desktop/src-tauri/src/connected/sign_in.rs +++ b/desktop/src-tauri/src/connected/sign_in.rs @@ -1279,6 +1279,49 @@ mod tests { assert!(session.access().is_err()); } + /// Every request the shell itself makes to the OpenBot names this app, `OpenBot-Client: + /// desktop/`: the two questions before sign-in, the code exchange, the first call + /// after it, a refresh, and sign-out's revocations. Only the person's browser, which opens the + /// authorization address, is not the app. + #[test] + fn every_request_the_shell_makes_names_this_app() { + let openbot = FakeOpenBot::start(Shape::Current); + let session = openbot.sign_in(in_memory()); + let access = session.access().unwrap(); + openbot.expire_access_tokens(); + session.after_refused(&access).unwrap(); + session.sign_out().unwrap(); + + let named = format!("desktop/{}", crate::client_version::app_version()); + let shells: Vec<_> = openbot + .seen() + .into_iter() + .filter(|seen| seen.path != "/api/auth/oauth2/authorize") + .collect(); + let asked: Vec = shells + .iter() + .map(|seen| format!("{} {}", seen.method, seen.path)) + .collect(); + for path in [ + "GET /api/v2/organizations/default/deployment", + "GET /.well-known/oauth-authorization-server/api/auth", + "POST /api/auth/oauth2/token", + "GET /api/copilotkit/info", + "POST /api/auth/oauth2/revoke", + ] { + assert!(asked.iter().any(|seen| seen == path), "{path}: {asked:?}"); + } + for seen in &shells { + assert_eq!( + seen.header("openbot-client"), + Some(named.as_str()), + "{} {}", + seen.method, + seen.path + ); + } + } + /// Nothing shaped like a token reaches a file under the app's configuration folder or a line /// of the log, through a sign-in, a refresh, a refused refresh and a sign-out. #[test] diff --git a/desktop/src-tauri/src/desktop_connection.rs b/desktop/src-tauri/src/desktop_connection.rs index 313ccc2521..84e2d79272 100644 --- a/desktop/src-tauri/src/desktop_connection.rs +++ b/desktop/src-tauri/src/desktop_connection.rs @@ -14,6 +14,7 @@ pub fn client() -> Result { Client::builder() .timeout(std::time::Duration::from_secs(1)) .redirect(reqwest::redirect::Policy::none()) + .default_headers(openbot_desktop_lib::client_version::headers()) .build() .map_err(|error| format!("Could not create connection status client: {error}")) } diff --git a/desktop/src-tauri/src/host_access.rs b/desktop/src-tauri/src/host_access.rs index 8f4c1fe6b6..eca969fa51 100644 --- a/desktop/src-tauri/src/host_access.rs +++ b/desktop/src-tauri/src/host_access.rs @@ -611,7 +611,11 @@ impl Drop for HostAccess { } fn broker_loop(inner: Arc) { - let client = match Client::builder().timeout(Duration::from_secs(15)).build() { + let client = match Client::builder() + .timeout(Duration::from_secs(15)) + .default_headers(crate::client_version::headers()) + .build() + { Ok(client) => client, Err(error) => { log::error!("[host access] could not create its HTTP client: {error}"); @@ -1225,6 +1229,7 @@ impl Inner { .spawn(move || { let sent = Client::builder() .timeout(Duration::from_secs(5)) + .default_headers(crate::client_version::headers()) .build() .and_then(|client| { client diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index f1bed2e9aa..862cb6622e 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ pub mod acquire; pub mod ai_connection; pub mod app_update; pub mod cli_release; +pub mod client_version; pub mod composio; pub mod connected; pub mod deployment; diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 915b902a12..34533e5ad4 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -6825,6 +6825,11 @@ fn show_openbot_on( let (url, address) = owned_app(&shell, &root, ports).ok_or_else(|| { format!("OpenBot could not verify its app on port {port} belongs to this installation. Try starting OpenBot again.") })?; + // An OpenBot that needs a newer app is not shown: the window says "Update OpenBot" instead. + if let Some(problem) = local_app_too_old(&shell, &root, &address, ports) { + log::warn!("[show] {}", logging::Failure::described(&problem)); + return Err(problem); + } hold_shown_deployment(&app, &shell, &root, address.clone(), ports.server); refresh_menus(&app); // Only the owned app itself. @@ -8955,6 +8960,7 @@ fn show_setup_and_focus(app: tauri::AppHandle) -> Result<( fn server_capabilities_answer(port: u16) -> bool { reqwest::blocking::Client::builder() .timeout(std::time::Duration::from_secs(2)) + .default_headers(openbot_desktop_lib::client_version::headers()) .build() .ok() .and_then(|client| { @@ -9015,6 +9021,26 @@ fn owned_app_url(shell: &Shell, root: &Path, ports: &openbot_env::Ports) -> Opti owned_app(shell, root, ports).map(|(url, _)| url) } +/** +Whether this app is too old for the OpenBot `root`'s server runs, read from its `deployment` as every +OpenBot app reads it (`client_version::local_problem`), with the install's token. "Update OpenBot", +with this app's update, is the only thing that stops the window from opening it: an OpenBot from an +older release opens exactly as before (Start upgrades it), and one that does not answer is the +readiness check's to report. +*/ +fn local_app_too_old( + shell: &Shell, + root: &Path, + address: &engine::Address, + ports: &openbot_env::Ports, +) -> Option { + let token = install_token_for(shell, root, address); + openbot_desktop_lib::client_version::local_problem( + &format!("http://127.0.0.1:{}", ports.server), + token.as_deref(), + ) +} + /// [`owned_app_url`], with the engine whose `server` container publishes it. fn owned_app( shell: &Shell, @@ -11330,6 +11356,8 @@ fn restore_window_on(app: &tauri::AppHandle, ports: &openb if let Some((url, address)) = (!recovery_required_or_pending_quit_notice(&shell, &root)) .then(|| owned_app(&shell, &root, ports)) .flatten() + // One that needs a newer app stays on setup, which says so. + .filter(|(_, address)| local_app_too_old(&shell, &root, address, ports).is_none()) { hold_shown_deployment(app, &shell, &root, address.clone(), ports.server); refresh_menus(app); @@ -12649,6 +12677,11 @@ fn main() { // After an in-app update, or from the installer's last page: in front as the window first shows. let from_installer = started_by_installer(&args); let context = side_by_side(tauri::generate_context!()); + // The version every request to an OpenBot names this app with (`client_version`): the one the + // installer, the update check and About name. + openbot_desktop_lib::client_version::set_app_version( + context.package_info().version.to_string(), + ); // A `shell-updater` build with compiled trust supplies `plugins.updater` when no bundled block // (such as the signed Mac overlay) already does. Registration itself happens once, in `setup`. #[cfg(feature = "shell-updater")] @@ -23816,6 +23849,16 @@ fn serve(listener: TcpListener) { // token it was started with (`server-host-token`), and each request recorded as one or the other. fn desktop_answer(request: &str) -> Option<(&'static str, String)> { let path = request.split_whitespace().nth(1)?; + // Which app asked for what, as the OpenBot-Client header named it. + let named = request.lines().filter_map(|line| line.split_once(':')).find_map(|(name, value)| { + name.eq_ignore_ascii_case("openbot-client").then(|| value.trim().to_owned()) + }).unwrap_or_else(|| "-".into()); + let mut asked = std::fs::OpenOptions::new().create(true).append(true).open("client-headers.log").unwrap(); + writeln!(asked, "{path} {named}").unwrap(); + // What it offers, when the test gave it a deployment answer to give. + if path == "/api/v2/organizations/default/deployment" { + return std::fs::read_to_string("deployment.json").ok().map(|body| ("200 OK", body)); + } let empty = match path { "/api/host-access/desktop/next" => "{\"operations\":[],\"leaseMs\":30000}", "/api/desktop/connection-failure" => "null", @@ -24244,6 +24287,79 @@ fn main() { assert_eq!(window_url(&app), shown); } + /// The OpenBot on this computer is read as every app reads it before the window opens it + /// (API versioning design, 7.1). One whose admin raised the oldest app it serves above this + /// one, or one that serves only a newer API, is not shown: the window says "Update OpenBot" + /// and offers this app's update, and Show Window keeps it on setup. One left at 1.1.0, which + /// publishes no version fields, opens exactly as before. Every request names this app. + #[test] + fn the_openbot_on_this_computer_opens_only_when_this_app_is_new_enough_for_it() { + let f = RestoreFixture::new(); + openbot_env::write( + &f.owned.join(".env"), + &f.ports.settings(), + &std::collections::BTreeMap::new(), + ) + .unwrap(); + let root = f.owned.to_string_lossy().into_owned(); + let shown = format!("http://127.0.0.1:{}/", f.ports.app); + let version = openbot_desktop_lib::client_version::app_version(); + let window_url = |app: &tauri::App| { + app.get_webview_window("main") + .unwrap() + .url() + .unwrap() + .to_string() + }; + let cases: serde_json::Value = serde_json::from_str(include_str!( + "../../../shared/fixtures/client-version/cases.json" + )) + .unwrap(); + let answer = |name: &str| cases["deployments"][name].clone(); + // The fixture's `raised`, its minimum for this app above whatever this build is. + let mut raised = answer("raised"); + let major: u64 = version.split('.').next().unwrap().parse().unwrap(); + raised["minimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); + + for too_new in [raised, answer("v3-only")] { + std::fs::write(f.owned.join("deployment.json"), too_new.to_string()).unwrap(); + let app = f.app(&f.owned, "tauri://localhost/"); + assert!(already_running_now(app.handle(), &root)); + let problem = show_openbot_on(app.handle().clone(), &f.ports).unwrap_err(); + assert_eq!(problem.kind, Some("app-too-old"), "{too_new}"); + assert_eq!( + problem.said, + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going." + ); + assert_eq!(window_url(&app), "http://127.0.0.1:9/stale-page"); + restore_window_on(app.handle(), &f.ports); + assert_eq!(window_url(&app), "tauri://localhost/"); + } + + // Left at 1.1.0: the server left at an older version, which starts and opens as today. + std::fs::write( + f.owned.join("deployment.json"), + answer("v1.1.0").to_string(), + ) + .unwrap(); + let app = f.app(&f.owned, "tauri://localhost/"); + show_openbot_on(app.handle().clone(), &f.ports).unwrap(); + assert_eq!(window_url(&app), shown); + + let asked = std::fs::read_to_string(f.owned.join("client-headers.log")).unwrap(); + for path in [ + "/api/capabilities", + "/api/v2/organizations/default/deployment", + ] { + assert!( + asked + .lines() + .any(|line| line == format!("{path} desktop/{version}")), + "{path}: {asked}" + ); + } + } + /// A deployment shown as the window's own is this session's, as one Start raised is: the menus /// say it is running, local folder access and the connection watcher answer to its server, and /// Quit takes its containers down. Shown and not held, the tray said "Not running", Quit left diff --git a/desktop/src-tauri/src/recorder_host.rs b/desktop/src-tauri/src/recorder_host.rs index 7107041802..d0f068d0aa 100644 --- a/desktop/src-tauri/src/recorder_host.rs +++ b/desktop/src-tauri/src/recorder_host.rs @@ -448,6 +448,7 @@ fn client() -> reqwest::Result { Client::builder() .timeout(DEADLINES.handoff) .redirect(reqwest::redirect::Policy::none()) + .default_headers(crate::client_version::headers()) .build() } diff --git a/desktop/src-tauri/src/stack.rs b/desktop/src-tauri/src/stack.rs index 0396cf2033..3e15130f97 100644 --- a/desktop/src-tauri/src/stack.rs +++ b/desktop/src-tauri/src/stack.rs @@ -4190,6 +4190,7 @@ pub fn answering_at(port: u16, path: &str) -> Option { pub fn answering_within(port: u16, path: &str, patience: std::time::Duration) -> Option { let client = reqwest::blocking::Client::builder() .timeout(patience) + .default_headers(crate::client_version::headers()) .build() .ok()?; LOOPBACKS.iter().find_map(|host| { @@ -4248,6 +4249,7 @@ pub fn wait_until_healthy_saying( ); let client = reqwest::blocking::Client::builder() .timeout(std::time::Duration::from_secs(3)) + .default_headers(crate::client_version::headers()) .build() .map_err(|error| format!("could not ask OpenBot's services: {error}"))?; let mut api_up = false; diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 90ab9289e4..32f14cebe5 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -886,7 +886,12 @@ const CONNECT_PROBLEMS: Array<{ kind: string; said: string; at: "check" | "connect"; - offer: "field" | "Try again" | "Sign in again" | "Open in browser"; + offer: + | "field" + | "Try again" + | "Sign in again" + | "Open in browser" + | "Update and restart"; }> = [ { kind: "address-invalid", @@ -916,7 +921,13 @@ const CONNECT_PROBLEMS: Array<{ kind: "too-old", at: "check", offer: "Open in browser", - said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser.", + said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser.", + }, + { + kind: "app-too-old", + at: "check", + offer: "Update and restart", + said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", }, { kind: "sign-in-cancelled", @@ -1115,6 +1126,19 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { throw { said, kind }; }, "plugin:opener|open_url": null, + // This app's own update, as the shell offers it. + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }, + check_app_update: { + found: "available", + version: "1.2.0", + current: "1.1.0", + }, + install_app_update: () => new Promise(() => {}), }); const field = view.getByLabelText("OpenBot address") as HTMLInputElement; await userEvent.type(field, `${ELSEWHERE}{Enter}`); @@ -1151,6 +1175,22 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { args: { url: ELSEWHERE }, }); expect(view.getByRole("button", { name: "Connect" })).toBeTruthy(); + } else if (offer === "Update and restart") { + // This app is what is too old: the way on is its own update, not another try. + expect(alert.textContent).toBe(said); + expect(view.queryByRole("button", { name: "Connect" })).toBeNull(); + const update = view.getByRole("button", { name: offer }); + await waitFor(() => expect(update).toHaveProperty("disabled", false)); + await userEvent.click(update); + await waitFor(() => + expect(invokeCalls.map((call) => call.command)).toContain( + "install_app_update", + ), + ); + expect(checks).toBe(1); + // Another address is another OpenBot: Connect is back once it changes. + await userEvent.type(field, "x"); + expect(view.getByRole("button", { name: "Connect" })).toBeTruthy(); } else { // One way on, and it says what it does. expect(alert.textContent).toBe(said); @@ -3887,6 +3927,54 @@ test("the running screen opens on its heading, with Updates under the buttons, w ); }); +/* + * The OpenBot on this computer started, and needs a newer version of this app (its admin's minimum, + * or only a newer API). The window does not open it, and does not say it stopped or failed: it says + * "Update OpenBot" with the shell's sentence and Update and restart. Stop is still there. + */ +test("an OpenBot on this computer that needs a newer app says Update OpenBot, not that it stopped", async () => { + setupConnectedLocalStack( + "/tmp/local-eval-app-too-old", + localStatus("ready", "valid"), + ); + const said = + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going."; + const previous = invokeHandler; + invokeHandler = async (command, args) => { + if (command === "show_openbot") + throw { + said, + detail: + "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", + }; + if (command === "app_update_offer") + return { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }; + return previous(command, args); + }; + const view = await renderApp(); + await waitFor(() => expect(localSequence()).toContain("start_stack")); + const heading = await view.findByRole("heading", { + level: 1, + name: "Update OpenBot", + }); + expect(view.queryByRole("heading", { name: "OpenBot stopped" })).toBeNull(); + expect(view.queryByText("That didn’t finish")).toBeNull(); + expect(view.queryByRole("list", { name: "Setup progress" })).toBeNull(); + const card = view.getByRole("alert"); + expect(card.textContent).toContain(said); + // One heading says it: the card under it does not say it again. + expect(within(card).queryByRole("heading")).toBeNull(); + expect(heading.closest(".sheet")?.contains(card)).toBe(true); + expect(view.getByRole("button", { name: "Update and restart" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Stop OpenBot" })).toBeTruthy(); +}); + test("relaunch says when Docker Desktop did not start, and Retry opens it again", async () => { setupConnectedLocalStack( "/tmp/local-eval-docker-never", diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index f871c7738d..32894d4743 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -63,6 +63,7 @@ import { type SetupStep, } from "./telemetry"; import { choseThisComputer, rememberThisComputer } from "./thisComputer"; +import { AppTooOld, appTooOld } from "./UpdateOpenBot"; import { UsageDataChoice } from "./UsageDataChoice"; import { type Hosting, Welcome } from "./Welcome"; import { @@ -1749,7 +1750,15 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { {/* A failure outranks `running`. The supervisor gives up on a process and sends the window back here, and a heading that still says everything is running while the box underneath names the process that stopped is a screen arguing with itself. */} -

{displayedFailure ? "OpenBot stopped" : "OpenBot is running"}

+ {/* Running, and needing a newer version of this app: nothing stopped, so the heading says + what to do and the card under it offers the update. */} +

+ {appTooOld(displayedFailure) + ? "Update OpenBot" + : displayedFailure + ? "OpenBot stopped" + : "OpenBot is running"} +

{/* The back end runs the release it had: information, said where the lede goes. Nothing failed, so it is not drawn as a failure and offers no help. */} {!displayedFailure && backEndNotice && ( @@ -1770,8 +1779,14 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { {/* The start's rows only when something failed, to show where. Once OpenBot runs they are all done, and they flashed for the moment before it opened with the native side's own words ("settings written, credentials stored"). */} - {displayedFailure && } - {displayedFailure && } + {appTooOld(displayedFailure) && displayedFailure ? ( + + ) : ( + <> + {displayedFailure && } + {displayedFailure && } + + )} {stopping && Stopping OpenBot…} {showing && Loading OpenBot…}
diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index 8f0dec1971..b4cb29ec4e 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -3,6 +3,7 @@ import { useEffect, useId, useRef, useState } from "react"; import { ExternalLink } from "./ExternalLink"; import { asProblem, type Problem } from "./Problem"; import { StatusLine } from "./SetupProgress"; +import { APP_TOO_OLD, UpdateOpenBot } from "./UpdateOpenBot"; /** * What the screen offers after something went wrong, chosen by the problem's `kind`. The sentence @@ -10,10 +11,11 @@ import { StatusLine } from "./SetupProgress"; * * `field`: the address is what to fix, so the sentence sits under the field and the field has the * focus. `sign-in` and `retry`: the screen's one button says Sign in again or Try again. `browser`: - * this app can't connect to that OpenBot, and a link opens it in the browser. A kind this app does - * not know is offered Try again. + * that OpenBot is too old for this app, and a link opens it in the browser. `update`: this app is + * too old for that OpenBot, and the way on is this app's own update. A kind this app does not know + * is offered Try again. */ -type Offer = "field" | "retry" | "sign-in" | "browser"; +type Offer = "field" | "retry" | "sign-in" | "browser" | "update"; function offerFor(kind: string | null | undefined): Offer { switch (kind) { @@ -23,6 +25,8 @@ function offerFor(kind: string | null | undefined): Offer { return "field"; case "too-old": return "browser"; + case APP_TOO_OLD: + return "update"; case "sign-in-cancelled": case "sign-in-failed": case "access-refused": @@ -142,7 +146,7 @@ export function useConnectToOpenBot({ if (offer !== "retry") setReopens(false); setPhase("idle"); // To the field when the address is what to fix, to the button when it is the way on. - if (offer !== "browser") + if (offer !== "browser" && offer !== "update") setFocus({ on: offer === "field" ? "field" : "action" }); } } @@ -257,27 +261,33 @@ export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) { computer.

{trouble && !underField && } -
- - {trouble?.offer === "browser" && address.trim() && ( - + ) : ( +
+
+ {trouble?.offer === "sign-in" + ? "Sign in again" + : trouble?.offer === "retry" + ? "Try again" + : "Connect"} + + {trouble?.offer === "browser" && address.trim() && ( + + Open in browser + + )} +
+ )} {phase === "checking" && ( Checking the address… )} diff --git a/desktop/src/Problem.test.tsx b/desktop/src/Problem.test.tsx index 2050df2af1..49638524fb 100644 --- a/desktop/src/Problem.test.tsx +++ b/desktop/src/Problem.test.tsx @@ -4,12 +4,14 @@ import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; let invokeCalls: Array<{ command: string; args?: unknown }> = []; let invokeFailure: string | null = null; +/** What the shell answers a command, where a test needs more than nothing. */ +let answers: Record = {}; mock.module("@tauri-apps/api/core", () => ({ invoke: (command: string, args?: unknown) => { invokeCalls.push({ command, args }); if (invokeFailure) return Promise.reject(invokeFailure); - return Promise.resolve(null); + return Promise.resolve(answers[command] ?? null); }, })); @@ -27,6 +29,7 @@ beforeAll(() => afterEach(() => { invokeCalls = []; invokeFailure = null; + answers = {}; if (previousSupportUrl === undefined) delete process.env.VITE_OPENBOT_SUPPORT_URL; else process.env.VITE_OPENBOT_SUPPORT_URL = previousSupportUrl; @@ -34,6 +37,76 @@ afterEach(() => { }); afterAll(() => GlobalRegistrator.unregister()); +/** What the shell says when the OpenBot on this computer needs a newer app (`client_version.rs`). */ +const LOCAL_APP_TOO_OLD = { + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + detail: + "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", +}; + +/* + * An OpenBot that needs a newer version of this app is not a failure. Wherever setup shows a + * problem, it says "Update OpenBot" with the shell's sentence, and Update and restart reads the + * update feed and installs what it finds: no failure heading, no technical details, no logs. + */ +test("an OpenBot that needs a newer app says Update OpenBot and Update and restart installs the update", async () => { + answers = { + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }, + check_app_update: { + found: "available", + version: "1.2.0", + current: "1.1.0", + }, + // On success the app restarts into the new version, and never answers. + install_app_update: new Promise(() => {}), + }; + const view = render(); + const card = view.getByRole("alert"); + expect(view.getByRole("heading", { name: "Update OpenBot" })).toBeTruthy(); + expect(card.textContent).toContain(LOCAL_APP_TOO_OLD.said); + expect(view.queryByText("That didn’t finish")).toBeNull(); + expect(view.queryByText("Technical details")).toBeNull(); + expect(view.queryByRole("button", { name: "Copy logs" })).toBeNull(); + // Drawn as a notice, not as the failure card. + expect(card.classList.contains("blocker")).toBe(false); + const update = view.getByRole("button", { name: "Update and restart" }); + await waitFor(() => expect(update).toHaveProperty("disabled", false)); + fireEvent.click(update); + await waitFor(() => + expect(invokeCalls.map((call) => call.command)).toEqual([ + "app_update_offer", + "check_app_update", + "install_app_update", + ]), + ); + await waitFor(() => expect(update.textContent).toBe("Downloading…")); +}); + +// A build that never updates itself has nothing to press: it says how to get one that does. +test("an OpenBot that needs a newer app, on a build that doesn't update itself, says how to get one", async () => { + answers = { + app_update_offer: { + version: null, + current: "1.1.0-internal.12.gabc", + installing: null, + updatesItself: false, + }, + }; + const view = render(); + await waitFor(() => + expect(view.getByRole("alert").textContent).toContain( + "This version of OpenBot doesn't update itself. Install a released version of OpenBot to get updates.", + ), + ); + expect(view.queryByRole("button", { name: "Update and restart" })).toBeNull(); +}); + /* * The card a Mac showed when its disk filled mid-update: containerd's input/output errors and * nothing about disk space. The native side recognises the full disk in that output diff --git a/desktop/src/Problem.tsx b/desktop/src/Problem.tsx index 63cfc899f4..d21facf47e 100644 --- a/desktop/src/Problem.tsx +++ b/desktop/src/Problem.tsx @@ -3,6 +3,7 @@ import { useState } from "react"; import { ExternalLink } from "./ExternalLink"; import type { Shortfall } from "./localEvalCli"; import { resourcesShortSaid } from "./localReadiness"; +import { AppTooOld, appTooOld } from "./UpdateOpenBot"; /** * A failure, in both registers, wherever one happens. @@ -179,6 +180,9 @@ export function TroubleshootingLogs({ /** * `onRetry`, where the screen has no other way to run what failed again: Try again, in the card. * The install behind the account step had none, and its failure sat there with nothing to press. + * + * An OpenBot that needs a newer version of this app is not a failure: wherever one shows, it says + * "Update OpenBot" with this app's update (`AppTooOld`). */ export function Failure({ problem, @@ -187,6 +191,7 @@ export function Failure({ problem: Problem; onRetry?: () => void; }) { + if (appTooOld(problem)) return ; return (

That didn’t finish

diff --git a/desktop/src/UpdateOffer.tsx b/desktop/src/UpdateOffer.tsx index a4d611655f..6a2572b826 100644 --- a/desktop/src/UpdateOffer.tsx +++ b/desktop/src/UpdateOffer.tsx @@ -2,6 +2,7 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; import type { UpdateReadiness } from "../../shared/desktop-updates"; import { asProblem } from "./Problem"; +import { useUpdateOpenBotShowing } from "./UpdateOpenBot"; /** * What the shell offers. The same answer OpenBot's own page reads for its update banner, so the @@ -54,6 +55,7 @@ export function UpdateOffer() { const [declined, setDeclined] = useState(null); const [installing, setInstalling] = useState(false); const [failure, setFailure] = useState(null); + const standingBack = useUpdateOpenBotShowing(); useEffect(() => { let current = true; @@ -101,6 +103,8 @@ export function UpdateOffer() { }, []); const version = offer?.version; + // The window says an OpenBot needs this update, with its own Update and restart: one is enough. + if (standingBack) return null; if (!offer || !version || version === declined) return null; const progress = offer.installing; const ready = offer.ready; diff --git a/desktop/src/UpdateOpenBot.tsx b/desktop/src/UpdateOpenBot.tsx new file mode 100644 index 0000000000..d683c86e70 --- /dev/null +++ b/desktop/src/UpdateOpenBot.tsx @@ -0,0 +1,192 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useEffect, useState, useSyncExternalStore } from "react"; +import { DOESNT_UPDATE_ITSELF } from "../../shared/desktop-updates"; +import type { Checked } from "./CheckForUpdates"; +import { asProblem, InlineFailure, type Problem } from "./Problem"; +import { type AppUpdate, describe } from "./UpdateOffer"; + +/** + * The `kind` the shell gives a problem when this app is older than the OpenBot it talks to serves + * (`client_version::APP_TOO_OLD`): connected to a company's OpenBot whose admin raised the oldest + * app it serves, or with an OpenBot on this computer that needs a newer app. + */ +export const APP_TOO_OLD = "app-too-old"; + +/** Whether a problem is this app being too old for its OpenBot. */ +export function appTooOld(problem: Problem | null | undefined): boolean { + return problem?.kind === APP_TOO_OLD; +} + +/** How often to ask the shell how an install is going, as Check for updates does. */ +const PROGRESS_EVERY_MS = 500; + +/** How many Update and restart buttons of this kind are on screen, and who wants to know. */ +let showing = 0; +const watchers = new Set<() => void>(); +function told() { + for (const watcher of watchers) watcher(); +} + +/** + * Whether an OpenBot that needs a newer app is being said on screen with its Update and restart. + * The offer at the top of the window stands back while it is, so the window offers the update + * once, in the card that says why. + */ +export function useUpdateOpenBotShowing(): boolean { + return useSyncExternalStore( + (changed) => { + watchers.add(changed); + return () => { + watchers.delete(changed); + }; + }, + () => showing > 0, + ); +} + +/** + * Update and restart, for an OpenBot that needs a newer version of this app. The same feed and the + * same install as the update offer at the top of this window and Check for updates: the feed is read + * now, and a newer version found is installed, and OpenBot restarts into it. A version the person + * closed the offer on before is still installed: they asked. + * + * A build that never updates itself (internal, candidate, or without the updater) says so, with + * nothing to press. When the feed has nothing newer, it says so and the button stays to try later. + */ +export function UpdateOpenBot() { + const [updatesItself, setUpdatesItself] = useState(null); + const [phase, setPhase] = useState<"idle" | "checking" | "installing">( + "idle", + ); + const [progress, setProgress] = useState(null); + const [found, setFound] = useState(null); + const [failure, setFailure] = useState(null); + const [installFailure, setInstallFailure] = useState(null); + + useEffect(() => { + showing += 1; + told(); + return () => { + showing -= 1; + told(); + }; + }, []); + + useEffect(() => { + let current = true; + invoke("app_update_offer") + .then((offer) => { + if (current) setUpdatesItself(offer.updatesItself !== false); + }) + // A shell that doesn't say still offers the update: the install says what it can't do. + .catch(() => { + if (current) setUpdatesItself(true); + }); + return () => { + current = false; + }; + }, []); + + useEffect(() => { + if (phase !== "installing") return; + let current = true; + const timer = setInterval(async () => { + try { + const offer = await invoke("app_update_offer"); + if (current) setProgress(offer.installing); + } catch { + // Progress is a courtesy. The button already says it is downloading. + } + }, PROGRESS_EVERY_MS); + return () => { + current = false; + clearInterval(timer); + }; + }, [phase]); + + async function update() { + setFailure(null); + setInstallFailure(null); + setFound(null); + setPhase("checking"); + let checked: Checked; + try { + checked = await invoke("check_app_update"); + } catch (error) { + setFailure(asProblem(error)); + setPhase("idle"); + return; + } + setFound(checked); + if (checked.found !== "available" && checked.found !== "installing") { + setPhase("idle"); + return; + } + setPhase("installing"); + try { + // Returns only when it failed: on success the app restarts into the new version. + await invoke("install_app_update"); + } catch (error) { + setInstallFailure(asProblem(error).said); + setPhase("idle"); + setProgress(null); + } + } + + if (updatesItself === false || found?.found === "notOffered") { + return

{DOESNT_UPDATE_ITSELF}

; + } + return ( + <> +
+ +
+ {found?.found === "upToDate" && ( +

+ OpenBot {found.current} is the newest version available. Check again + later. +

+ )} + {installFailure && ( +

+ OpenBot could not install the update: {installFailure} +

+ )} + {failure && } + + ); +} + +/** + * An OpenBot that needs a newer version of this app, wherever setup shows a problem: the shell's + * sentence, which says "Update OpenBot", and Update and restart. Nothing failed, so it is not drawn as + * a failure: no "That didn't finish", no technical details, no troubleshooting logs. + */ +export function AppTooOld({ + problem, + headed = true, +}: { + problem: Problem; + /** False where the screen's own heading already says "Update OpenBot". */ + headed?: boolean; +}) { + return ( + // The calm notice the connect screen uses for a connection that didn't work, not the failure + // card: nothing failed. +
+ {headed &&

Update OpenBot

} +

{problem.said}

+ +
+ ); +} diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts index b73c5aba14..be55fd2eb9 100644 --- a/desktop/src/setupLayout.browser.test.ts +++ b/desktop/src/setupLayout.browser.test.ts @@ -87,7 +87,23 @@ fake.emit = emit; // the back end's, which the window runs first (a Mac at 8.2 GB). const updateShort = location.hash === "#update-short"; const backEndShort = location.hash === "#backend-short"; -const relaunch = location.hash === "#start" || updateShort || backEndShort; +// An OpenBot and this app that don't fit, as the shell says it: connected to a company's OpenBot +// that needs a newer app, or that is too old for this one; one whose sign-in ended, as it always +// was; and the OpenBot on this computer needing a newer app once Start has it running. +const CONNECTED_PROBLEMS = { + "#connect-app-too-old": { said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", kind: "app-too-old" }, + "#connect-too-old": { said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser.", kind: "too-old" }, + "#connect-session-ended": { said: "Your sign-in to openbot.example.com has ended. Sign in again to keep going.", kind: "session-ended" }, +}; +const connectedProblem = CONNECTED_PROBLEMS[location.hash]; +const localTooOld = location.hash === "#local-app-too-old"; +// A launch that finds this computer's OpenBot already running, and that it needs a newer app. +const runningTooOld = location.hash === "#local-app-too-old-running"; +// The same launch, where showing it fails as it could before: the slot the card above lands in. +const runningFails = location.hash === "#local-running-fails"; +// The update feed has a newer version, so the offer at the top shows too. +const offered = location.search === "?offer"; +const relaunch = location.hash === "#start" || updateShort || backEndShort || localTooOld; const signingIn = location.hash === "#signin"; const installing = location.hash === "#licence-installing"; const pausing = location.hash === "#pause-podman"; @@ -123,6 +139,20 @@ fake.opened = []; export async function invoke(command, args) { fake.calls.push(command); if (command === "plugin:opener|open_url") fake.opened.push(args.url); + if (connectedProblem && command === "connection") + return { mode: "connected", address: "https://openbot.example.com", signedIn: true }; + if (connectedProblem && command === "show_connected") throw connectedProblem; + if ((runningTooOld || runningFails) && command === "already_running") return true; + if (runningFails && command === "show_openbot") + throw { said: "Part of OpenBot needs recovery. Try starting OpenBot once more." }; + if ((localTooOld || runningTooOld) && command === "show_openbot") + throw { + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + detail: "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", + }; + if ((connectedProblem || localTooOld || runningTooOld) && command === "app_update_offer") + return { version: offered ? "1.2.0" : null, current: "1.1.0", installing: null, updatesItself: true, ready: null }; switch (command) { case "windows_restart_pending": case "take_ai_connection_change": @@ -140,7 +170,7 @@ export async function invoke(command, args) { } : { values: {}, saved: { modelApiKeys: none, modelSessions: none } }; case "upgrade_due": - return relaunch ? { from: "1.0.0", to: "1.0.1" } : null; + return relaunch && !localTooOld ? { from: "1.0.0", to: "1.0.1" } : null; case "upgrade_and_start": if (updateShort) throw { @@ -194,9 +224,10 @@ export async function invoke(command, args) { }; if (backEndShort) return { ...status("ready", "valid"), updateTo: "0.16.0-rc.13" }; return status("ready", "valid"); - // OpenBot's own start, the step's last row: it stays there for the test to look at. + // OpenBot's own start, the step's last row: it stays there for the test to look at. Running, + // when the window is about to find it needs a newer app. case "start_stack": - return new Promise(() => {}); + return localTooOld ? null : new Promise(() => {}); // Usage data as a first run finds it: shared until the person says otherwise. case "plugin:openbot-desktop|usage_data": return { shared: true, offByEnvironment: false }; @@ -2136,3 +2167,141 @@ describe.skipIf(!asked)( }, 30_000); }, ); + +/* + * When this app and its OpenBot don't fit (`client_version.rs`), the window says the shell's + * sentence and offers its one way on, in view and uncovered, without outgrowing the window: Update + * and restart when this app is too old, Open in browser when that OpenBot is. Beside them a problem + * the screen always had, a sign-in that ended, for comparison. With `OPENBOT_SHOTS_DIR` set, each is + * saved there in light and dark, at the window's default size. + */ +describe.skipIf(!asked)("an OpenBot and this app that don't fit", () => { + const shots = process.env.OPENBOT_SHOTS_DIR; + const states: { + name: string; + at: string; + said: string; + way: { role: "button" | "link"; name: string }; + }[] = [ + { + name: "connected-app-too-old", + at: "#connect-app-too-old", + said: "needs a newer version of this app. Update OpenBot, then connect again.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "connected-app-too-old-with-offer", + at: "?offer#connect-app-too-old", + said: "needs a newer version of this app. Update OpenBot, then connect again.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "connected-server-too-old", + at: "#connect-too-old", + said: "Ask whoever runs your OpenBot to update it, or open it in your browser.", + way: { role: "link", name: "Open in browser" }, + }, + { + name: "local-app-too-old", + at: "#local-app-too-old", + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "local-app-too-old-found-running", + at: "?offer#local-app-too-old-running", + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "existing-found-running-fails", + at: "#local-running-fails", + said: "Part of OpenBot needs recovery. Try starting OpenBot once more.", + way: { role: "button", name: "Install" }, + }, + { + name: "existing-session-ended", + at: "#connect-session-ended", + said: "Your sign-in to openbot.example.com has ended.", + way: { role: "button", name: "Sign in again" }, + }, + ]; + for (const state of states) { + for (const [width, height] of [ + [1000, 800], + [720, 560], + ] as const) { + test(`${state.name} at ${width}x${height}: the sentence and its way on are in view`, async () => { + for (const colorScheme of ["light", "dark"] as const) { + const page = await browser.newPage({ + viewport: { width, height }, + colorScheme, + }); + try { + await open(page, state.at); + await page.getByText(state.said, { exact: false }).waitFor(); + // The card's entrance, and the update offer's first answer, settled. + await page.waitForTimeout(1200); + // The card's own way on: the last of its name, under the offer at the top when there is one. + const way = await page.evaluate(({ role, name }) => { + const found = [ + ...document.querySelectorAll(role === "link" ? "a" : "button"), + ].filter((element) => element.textContent?.trim() === name); + const element = found.at(-1); + if (!element) return null; + // A step taller than the window scrolls inside its card: there, it is reached so. + element.scrollIntoView({ block: "nearest" }); + const box = element.getBoundingClientRect(); + const top = document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ); + return { + y: box.top, + bottom: box.bottom, + covered: !(top && (top === element || element.contains(top))), + enabled: !(element as HTMLButtonElement).disabled, + }; + }, state.way); + expect({ state: state.name, found: way !== null }).toEqual({ + state: state.name, + found: true, + }); + expect(way?.y ?? -1).toBeGreaterThanOrEqual(0); + expect(way?.bottom ?? height + 1).toBeLessThanOrEqual(height); + expect({ state: state.name, covered: way?.covered }).toEqual({ + state: state.name, + covered: false, + }); + expect(way?.enabled).toBe(true); + // One Update and restart: the offer at the top stands back while the card says why. + if (state.way.name === "Update and restart") + expect( + await page.evaluate( + () => + [...document.querySelectorAll("button")].filter( + (button) => + button.textContent?.trim() === "Update and restart", + ).length, + ), + ).toBe(1); + const fits = await page.evaluate(() => ({ + page: document.documentElement.scrollHeight, + window: window.innerHeight, + wide: document.documentElement.scrollWidth, + across: window.innerWidth, + })); + expect(fits.page).toBeLessThanOrEqual(fits.window); + expect(fits.wide).toBeLessThanOrEqual(fits.across); + if (shots && width === 1000) + await page.screenshot({ + path: `${shots}/${state.name}-${colorScheme}.png`, + }); + } finally { + await page.close(); + } + } + }, 30_000); + } + } +}); diff --git a/desktop/src/styles.css b/desktop/src/styles.css index 2e3e139b28..78c50d4409 100644 --- a/desktop/src/styles.css +++ b/desktop/src/styles.css @@ -456,6 +456,12 @@ button.text-link:hover:not(:disabled) { background: color-mix(in srgb, var(--ring) 7%, var(--card)); } +/* "Update OpenBot" sits where a failure card would, so it keeps that card's place: apart from what + is above it, and the next row's own gap below. */ +.local-alert.app-too-old { + margin: 20px 0 0; +} + .local-alert h2 { display: flex; align-items: center; From db0eb6a5712dba93ee49cea3e9602450f65f0de5 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 17 Nov 2026 20:46:28 -0800 Subject: [PATCH 07/12] Serve every app from the last 12 months, and add nothing for an OpenBot older than the app A server serves every app released in the last 12 months, and every OpenBot release is younger than that, so no release may be named a built-in minimum yet. MINIMUM_CLIENTS is now empty; an admin of a server, such as OpenBot Cloud's, raises it with OPENBOT_MINIMUM_CLIENTS. The fixture's `current` answer names no minimum, the cases that expected `app` from it now expect `ok`, and `raised` and `next` keep app-too-old covered. The spec examples read as a server whose admin raised Desktop to 1.2.0. An OpenBot older than the app only happens with a company's own OpenBot, and the company keeps its apps and server matched, so nothing is added for it. Removed: the "before-v2" deployment from compatibility() in shared and the phone app, its fixture cases and capabilities answer, Desktop's and the phone app's /api/capabilities probe and its boundary allowance, the phone app's "ask whoever runs your OpenBot" screen, and Desktop's server-too-old layout state. Desktop's too-old sentence is back to its earlier words, and an OpenBot that serves only an older API maps to it as before. The app-too-old checks, the OpenBot-Client header and the API-majors rule stay. --- api/client-boundary.allow.ts | 6 -- api/openapi.yaml | 11 +-- api/openapi/admin-settings.yaml | 11 ++- api/openapi/common.yaml | 4 +- .../lib/api/generated/model/minimumClients.ts | 2 +- .../organization-settings.msw.ts | 7 +- .../organization-settings.zod.ts | 2 +- desktop/src-tauri/src/client_version.rs | 59 ++++--------- desktop/src-tauri/src/connected/address.rs | 85 ++++--------------- .../src/connected/fake_openbot_tests.rs | 17 +--- desktop/src-tauri/src/connected/mod.rs | 9 +- desktop/src/App.test.tsx | 2 +- desktop/src/ConnectToOpenBot.tsx | 2 +- desktop/src/UpdateOpenBot.tsx | 4 +- desktop/src/setupLayout.browser.test.ts | 23 ++--- .../src/api/generated/model/minimumClients.ts | 2 +- mobile/src/client-version.ts | 32 ++----- mobile/src/version-check.ts | 31 +------ mobile/src/version-gate.tsx | 16 +--- mobile/tests/client-version.test.ts | 23 +---- mobile/tests/generated-client.test.ts | 27 ++---- shared/client-version.ts | 27 +++--- shared/fixtures/client-version/cases.json | 42 ++------- shared/tests/client-version.test.ts | 31 ++++--- 24 files changed, 121 insertions(+), 354 deletions(-) diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index a45ff984a8..7dd7aa1964 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -340,12 +340,6 @@ export const ALLOWED: Allowed[] = [ rule: "hand-built-v2", why: "whether the address a person typed is an OpenBot, asked from Rust before anybody signs in", }, - { - file: "desktop/src-tauri/src/connected/address.rs", - what: "/api/capabilities", - rule: "before-sign-in", - why: "whether an address with no deployment is an OpenBot from before the v2 API, too old for this app, asked with no credential", - }, { file: "desktop/src-tauri/src/connected/address.rs", what: "/.well-known/oauth-authorization-server/api/auth", diff --git a/api/openapi.yaml b/api/openapi.yaml index 16793fb01f..c6d1d8c3ad 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -23856,7 +23856,7 @@ components: - 1.1.0 MinimumClients: type: object - description: The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published. + description: The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published. properties: web: $ref: '#/components/schemas/ClientRelease' @@ -37134,14 +37134,14 @@ components: type: https://open.bot/errors/client-update-required title: This app is too old for this OpenBot. status: 400 - detail: This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again. + detail: This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again. code: CLIENT_UPDATE_REQUIRED category: validation retryable: false requestId: req_example traceId: trace_example client: desktop - minimumVersion: 1.0.2 + minimumVersion: 1.2.0 ConversationNotFound: description: The conversation does not exist, was removed, or the caller is not in it, or the organization does not exist. content: @@ -41933,10 +41933,7 @@ components: api: - v2 minimumClients: - web: 1.1.0 - desktop: 1.0.2 - mobile: 1.1.0 - recorder: 1.1.0 + desktop: 1.2.0 launcherApi: 1 extensionApi: 1 OrganizationSettingsExample: diff --git a/api/openapi/admin-settings.yaml b/api/openapi/admin-settings.yaml index 909d2b1759..9430388f77 100644 --- a/api/openapi/admin-settings.yaml +++ b/api/openapi/admin-settings.yaml @@ -1120,8 +1120,10 @@ components: The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but - this deployment answer. An app not listed has no minimum. Absent from - a release before it was published. + this deployment answer. An app not listed has no minimum. An OpenBot + serves every app released in the last 12 months, so it names one only + where its administrator raised it. Absent from a release before it was + published. properties: web: $ref: '#/components/schemas/ClientRelease' @@ -2225,10 +2227,7 @@ components: fileBytes: 104857600 api: [v2] minimumClients: - web: 1.1.0 - desktop: 1.0.2 - mobile: 1.1.0 - recorder: 1.1.0 + desktop: 1.2.0 launcherApi: 1 extensionApi: 1 OrganizationSettingsExample: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index 6547880741..e69104e421 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -1329,14 +1329,14 @@ components: type: https://open.bot/errors/client-update-required title: This app is too old for this OpenBot. status: 400 - detail: This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again. + detail: This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again. code: CLIENT_UPDATE_REQUIRED category: validation retryable: false requestId: req_example traceId: trace_example client: desktop - minimumVersion: 1.0.2 + minimumVersion: 1.2.0 ConversationNotFound: description: >- The conversation does not exist, was removed, or the caller is not in diff --git a/app/src/lib/api/generated/model/minimumClients.ts b/app/src/lib/api/generated/model/minimumClients.ts index 26e1e29164..bedba5d4b8 100644 --- a/app/src/lib/api/generated/model/minimumClients.ts +++ b/app/src/lib/api/generated/model/minimumClients.ts @@ -4,7 +4,7 @@ import type { ClientRelease } from "./clientRelease"; /** - * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published. + * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published. */ export interface MinimumClients { web?: ClientRelease; diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts index af2dc5a7d4..c97029e75a 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts @@ -34,12 +34,7 @@ export const getGetDeploymentResponseMock = (): Deployment => ({ fileBytes: 104857600, }, api: ["v2"], - minimumClients: { - web: "1.1.0", - desktop: "1.0.2", - mobile: "1.1.0", - recorder: "1.1.0", - }, + minimumClients: { desktop: "1.2.0" }, launcherApi: 1, extensionApi: 1, }); diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts index 0db9bb4821..0ee9a86730 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts @@ -132,7 +132,7 @@ export const GetDeploymentResponse = zod }) .optional() .describe( - "The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published.", + "The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published.", ), launcherApi: zod .int() diff --git a/desktop/src-tauri/src/client_version.rs b/desktop/src-tauri/src/client_version.rs index 68376f8736..dc8bc1d479 100644 --- a/desktop/src-tauri/src/client_version.rs +++ b/desktop/src-tauri/src/client_version.rs @@ -4,8 +4,8 @@ and the OpenBot it talks to can work together. Every OpenBot app names itself in `OpenBot-Client: /`, and every OpenBot says on its `deployment` which API versions it serves and the oldest release of each app it still serves. When -the two don't fit, the person reads one sentence: "Update OpenBot" when this app is too old, "Ask -whoever runs your OpenBot to update it" when that OpenBot is. +this app is too old for that OpenBot, the person reads "Update OpenBot" and is offered this app's +update. An OpenBot too old for this app is told as it always was (`connected::Kind::TooOld`). The rules are `shared/client-version.ts`'s, carried here in Rust. The tests hold them to every case in `shared/fixtures/client-version/cases.json`, the same cases the web app, the Recorder and the @@ -101,20 +101,12 @@ pub enum Fit { /// The app is too old: that OpenBot serves only newer API versions, or names a minimum for /// this app above its version (`minimum`). "Update OpenBot". App { minimum: Option }, - /// That OpenBot is too old: it serves only API versions older than any the app speaks, or it is - /// from before the v2 API. "Ask whoever runs your OpenBot to update it". + /// That OpenBot is too old: it serves only API versions older than any the app speaks. Server, } -/// What an OpenBot answered about itself. -#[derive(Clone, Copy, Debug)] -pub enum Deployment<'a> { - /// Its `deployment`, as it answered it. - Answered(&'a serde_json::Map), - /// No `deployment` at all, while it still answers as an OpenBot (`/api/capabilities`): a release - /// from before the v2 API, such as 1.0.3. - BeforeV2, -} +/// An OpenBot's `deployment`, as it answered it. +pub type Deployment = serde_json::Map; /// The major of an API version, `v2` as 2. fn major(version: &str) -> Option { @@ -204,10 +196,7 @@ Whether an app of `kind` at `version`, speaking `speaks`, and the OpenBot that a can work together. A `deployment` that publishes no `api` is from a release before it was published, and every such release that answers `deployment` serves v2. */ -pub fn compatibility(deployment: Deployment, kind: &str, version: &str, speaks: &[&str]) -> Fit { - let Deployment::Answered(deployment) = deployment else { - return Fit::Server; - }; +pub fn compatibility(deployment: &Deployment, kind: &str, version: &str, speaks: &[&str]) -> Fit { let served: Vec<&str> = match deployment.get("api") { Some(serde_json::Value::Array(api)) => { api.iter().filter_map(serde_json::Value::as_str).collect() @@ -242,25 +231,20 @@ pub fn compatibility(deployment: Deployment, kind: &str, version: &str, speaks: } /// [`compatibility`] for this app. -pub fn fit(deployment: Deployment) -> Fit { +pub fn fit(deployment: &Deployment) -> Fit { compatibility(deployment, KIND, &app_version(), API_VERSIONS) } /// Why it doesn't fit, for the log: what that OpenBot said, against this app. -pub fn why(deployment: Deployment, fit: &Fit) -> String { +pub fn why(deployment: &Deployment, fit: &Fit) -> String { let this = format!( "this app is {} and speaks {}", token(), API_VERSIONS.join(", ") ); - let served = match deployment { - Deployment::BeforeV2 => { - return format!("the OpenBot answers no deployment, from before the v2 API; {this}") - } - Deployment::Answered(deployment) => deployment - .get("api") - .map_or_else(|| "no api (v2)".to_owned(), |api| format!("api {api}")), - }; + let served = deployment + .get("api") + .map_or_else(|| "no api (v2)".to_owned(), |api| format!("api {api}")); match fit { Fit::App { minimum: Some(minimum), @@ -304,12 +288,11 @@ pub fn local_problem(base: &str, install_token: Option<&str>) -> Option let serde_json::Value::Object(deployment) = answered.json::().ok()? else { return None; }; - let read = Deployment::Answered(&deployment); - let decided = fit(read); + let decided = fit(&deployment); let Fit::App { .. } = decided else { return None; }; - let mut problem = Problem::with(LOCAL_APP_TOO_OLD, why(read, &decided)); + let mut problem = Problem::with(LOCAL_APP_TOO_OLD, why(&deployment, &decided)); problem.kind = Some(APP_TOO_OLD); Some(problem) } @@ -342,9 +325,6 @@ pub(crate) const CASES: &str = include_str!("../../../shared/fixtures/client-ver #[cfg(test)] pub(crate) fn fixture_deployment(name: &str) -> serde_json::Value { let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); - if name == "before-v2-capabilities" { - return cases["before-v2-capabilities"].clone(); - } let found = cases["deployments"][name].clone(); assert!(found.is_object(), "the fixture has no deployment {name}"); found @@ -359,7 +339,7 @@ mod tests { fn every_case_in_the_shared_fixture_is_decided_as_the_contract_says() { let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); let list = cases["cases"].as_array().unwrap(); - assert!(list.len() >= 16, "the fixture lost its cases"); + assert!(list.len() >= 15, "the fixture lost its cases"); for case in list { let name = case["deployment"].as_str().unwrap(); let client = &case["client"]; @@ -367,11 +347,7 @@ mod tests { .as_array() .map(|speaks| speaks.iter().filter_map(|v| v.as_str()).collect()) .unwrap_or_else(|| API_VERSIONS.to_vec()); - let answered = (name != "before-v2") - .then(|| cases["deployments"][name].as_object().unwrap().clone()); - let deployment = answered - .as_ref() - .map_or(Deployment::BeforeV2, Deployment::Answered); + let deployment = cases["deployments"][name].as_object().unwrap(); let decided = compatibility( deployment, client["kind"].as_str().unwrap(), @@ -425,8 +401,8 @@ mod tests { /// The OpenBot on this computer, read as every app reads it, through the real HTTP path with /// the fixture's real answers. Only an OpenBot that needs a newer app is a problem: one of this - /// release, one left at 1.1.0 (no version fields), one from before the v2 API and one that is - /// not answering all start and open as before, with no sentence. + /// release, one left at 1.1.0 (no version fields) and one that is not answering all start and + /// open as before, with no sentence. #[test] fn the_openbot_on_this_computer_says_update_openbot_only_when_it_needs_a_newer_app() { use crate::connected::fake_openbot::{FakeOpenBot, Shape}; @@ -436,7 +412,6 @@ mod tests { (Shape::Answers("v3-only"), true), (Shape::Answers("current"), false), (Shape::Answers("v1.1.0"), false), - (Shape::BeforeV2, false), ] { let server = FakeOpenBot::start(shape.clone()); let problem = local_problem(&server.address(), Some("install-token-abc")); diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs index 11544a8e3d..96a6daee4e 100644 --- a/desktop/src-tauri/src/connected/address.rs +++ b/desktop/src-tauri/src/connected/address.rs @@ -4,9 +4,8 @@ //! Two questions are asked of the address, both public: what it offers //! (`/api/v2/organizations/default/deployment`, which every OpenBot answers before sign-in) and //! how an app signs in to it (its authorization server metadata, RFC 8414). What it offers says -//! whether this app and that OpenBot fit (`client_version`). An address with no `deployment` is -//! asked one more: whether it is an OpenBot from before the v2 API. Each way that can go wrong is -//! one `Kind`, so the window can say what to do next. +//! whether this app is new enough for that OpenBot (`client_version`). Each way that can go wrong +//! is one `Kind`, so the window can say what to do next. use super::{host_of, http, transport, Kind}; use crate::client_version; @@ -15,8 +14,6 @@ use crate::problem::Problem; /// What an OpenBot offers, which every OpenBot answers before sign-in. Read here, and of the OpenBot /// on this computer (`client_version::local_problem`). pub const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment"; -/// What an OpenBot from before the v2 API answers in place of `DEPLOYMENT`, before sign-in. -const CAPABILITIES: &str = "/api/capabilities"; const METADATA: &str = "/.well-known/oauth-authorization-server/api/auth"; /// What keeps a sign-in going after its first hour: a refresh token. const OFFLINE_ACCESS: &str = "offline_access"; @@ -98,29 +95,10 @@ pub fn probe(address: &str) -> Result { .and_then(|deployment| deployment.get("edition")) .and_then(serde_json::Value::as_str); let (Some(deployment), Some(edition)) = (deployment.as_ref(), edition) else { - // No `deployment`. An OpenBot from before the v2 API (1.0.3 and older) still answers what - // it offers at `/api/capabilities`: that one is too old for this app, not missing. - let missing = format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"); - let before_v2 = get(CAPABILITIES).ok().is_some_and(|older| { - let answered = older.status().is_success(); - json_object(older) - .filter(|_| answered) - .is_some_and(|capabilities| { - capabilities.get("edition").is_some_and(|e| e.is_string()) - }) - }); - return Err(if before_v2 { - let fit = client_version::Fit::Server; - Kind::TooOld.problem( - &host, - format!( - "{missing}; GET {CAPABILITIES} answered as an OpenBot does: {}", - client_version::why(client_version::Deployment::BeforeV2, &fit) - ), - ) - } else { - Kind::NotOpenBot.problem(&host, missing) - }); + return Err(Kind::NotOpenBot.problem( + &host, + format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"), + )); }; let on_its_own_computer = deployment .get("localEvaluation") @@ -132,15 +110,15 @@ pub fn probe(address: &str) -> Result { // Which API versions it serves and the oldest release of this app it serves, decided as every // OpenBot app decides it (`client_version`): asked when the person connects and on every - // launch, so an OpenBot upgraded past this app since, or moved back, is caught. - let read = client_version::Deployment::Answered(deployment); - match client_version::fit(read) { + // launch, so an OpenBot that raised its minimum past this app since is caught. One that serves + // only an older API is told as an OpenBot this app can't connect to always was. + match client_version::fit(deployment) { client_version::Fit::Ok => {} fit @ client_version::Fit::App { .. } => { - return Err(Kind::AppTooOld.problem(&host, client_version::why(read, &fit))); + return Err(Kind::AppTooOld.problem(&host, client_version::why(deployment, &fit))); } fit @ client_version::Fit::Server => { - return Err(Kind::TooOld.problem(&host, client_version::why(read, &fit))); + return Err(Kind::TooOld.problem(&host, client_version::why(deployment, &fit))); } } @@ -354,36 +332,6 @@ mod tests { assert_eq!(kind(&server.address()), Some(Kind::TooOld)); } - /// OpenBot 1.0.3 and older, from before the v2 API: no `deployment` (404), but - /// `/api/capabilities` answers as an OpenBot does. That is an OpenBot too old for this app, and - /// the person is told so, not that there is no OpenBot at the address they typed. - #[test] - fn an_openbot_from_before_the_v2_api_is_too_old_not_missing() { - let server = FakeOpenBot::start(Shape::BeforeV2); - let problem = check(&server.address()).expect_err("too old"); - assert_eq!(kind_of(&problem), Some(Kind::TooOld)); - assert_eq!( - problem.said, - format!( - "The OpenBot at {} is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser.", - host_of(&server.address()) - ) - ); - // What the log says beside it. - assert_eq!( - problem.detail, - Some(format!( - "GET {DEPLOYMENT} answered 404 Not Found, not as an OpenBot does; GET {CAPABILITIES} answered as an OpenBot does: the OpenBot answers no deployment, from before the v2 API; this app is {} and speaks v2", - crate::client_version::token() - )) - ); - // Not a sign-in it can't do: nothing past the two questions is asked. - assert!(server.seen_at(METADATA).is_empty()); - // Something else that answers JSON at both addresses is still not an OpenBot. - let other = FakeOpenBot::start(Shape::OtherJson); - assert_eq!(kind(&other.address()), Some(Kind::NotOpenBot)); - } - /// The fixture's real answers (`shared/fixtures/client-version/cases.json`), as this release's /// app reads them through the real HTTP path. An OpenBot of this release, and one of 1.1.0 /// (which publishes no version fields), connect. One whose admin raised the oldest app it @@ -427,19 +375,16 @@ mod tests { } /// The check runs on every launch while connected (`probe`, before the saved sign-in is used), - /// not only when the person connects: an OpenBot upgraded past the app since, or moved back, - /// is caught the next time the app opens. + /// not only when the person connects: an OpenBot that raised its minimum past the app since, + /// as OpenBot Cloud does, is caught the next time the app opens. #[test] fn the_launch_check_catches_an_openbot_that_moved_since_the_app_connected() { let _version = crate::client_version::as_version("1.1.0"); - for (name, kind) in [("raised", Kind::AppTooOld), ("v3-only", Kind::AppTooOld)] { + for name in ["raised", "v3-only"] { let server = FakeOpenBot::start(Shape::Answers(name)); let problem = probe(&server.address()).expect_err(name); - assert_eq!(kind_of(&problem), Some(kind), "{name}"); + assert_eq!(kind_of(&problem), Some(Kind::AppTooOld), "{name}"); } - let older = FakeOpenBot::start(Shape::BeforeV2); - let problem = probe(&older.address()).expect_err("before v2"); - assert_eq!(kind_of(&problem), Some(Kind::TooOld)); } /// The browser is sent to the authorization endpoint and the code is posted to the token diff --git a/desktop/src-tauri/src/connected/fake_openbot_tests.rs b/desktop/src-tauri/src/connected/fake_openbot_tests.rs index c2081fe177..5a1dcfa4fb 100644 --- a/desktop/src-tauri/src/connected/fake_openbot_tests.rs +++ b/desktop/src-tauri/src/connected/fake_openbot_tests.rs @@ -4,7 +4,7 @@ loopback port that answers the addresses the app uses as the real one does. - the public deployment answer and the authorization server metadata (RFC 8414), at the real paths, the deployment as one of the real answers in `shared/fixtures/client-version/cases.json` when - asked (`Shape::Answers`), and `/api/capabilities` as an OpenBot from before the v2 API answers it; + asked (`Shape::Answers`); - the authorization endpoint, which accepts only the public client, `response_type=code`, an S256 challenge and a redirect of exactly `http://127.0.0.1:/callback`, and sends the browser back with a code or with `error=access_denied`; @@ -66,9 +66,6 @@ pub enum Shape { /// `shared/fixtures/client-version/cases.json`, by name: `current`, `v1.1.0`, `raised` or /// `v3-only`. Answers(&'static str), - /// An OpenBot from before the v2 API, as 1.0.3 answers: `deployment` is 404, `/api/capabilities` - /// answers as the fixture's `before-v2-capabilities`, and apps can't sign in to it. - BeforeV2, } const SCOPES: [&str; 4] = ["openid", "profile", "offline_access", "openbot"]; @@ -430,10 +427,6 @@ async fn answer( StatusCode::OK, crate::client_version::fixture_deployment(name), ), - Shape::BeforeV2 => json( - StatusCode::NOT_FOUND, - serde_json::json!({ "error": "not_found" }), - ), _ => json( StatusCode::OK, serde_json::json!({ @@ -446,16 +439,10 @@ async fn answer( }), ), }, - // Every OpenBot answers what it offers here, before sign-in, the releases from before the - // v2 API included. - ("GET", "/api/capabilities") => json( - StatusCode::OK, - crate::client_version::fixture_deployment("before-v2-capabilities"), - ), ("GET", "/.well-known/oauth-authorization-server/api/auth") => { if matches!( shape, - Shape::NoMetadata | Shape::Personal | Shape::LocalEvaluation | Shape::BeforeV2 + Shape::NoMetadata | Shape::Personal | Shape::LocalEvaluation ) { return Ok(json( StatusCode::NOT_FOUND, diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs index b68e143674..db90ce0a31 100644 --- a/desktop/src-tauri/src/connected/mod.rs +++ b/desktop/src-tauri/src/connected/mod.rs @@ -40,7 +40,6 @@ pub enum Kind { Unreachable, NotOpenBot, SinglePerson, - /// That OpenBot is older than this app can use: the window offers it in the browser. TooOld, /// This app is older than that OpenBot serves: the window offers this app's own update. AppTooOld, @@ -87,7 +86,7 @@ impl Kind { ), Kind::TooOld => format!( "The OpenBot at {host} is on a release this app can't connect to yet. Ask whoever \ - runs your OpenBot to update it, or open it in your browser." + runs it to update OpenBot, or open it in your browser." ), Kind::AppTooOld => format!( "The OpenBot at {host} needs a newer version of this app. Update OpenBot, then \ @@ -219,13 +218,11 @@ mod tests { Kind::SessionEnded.said("openbot.example.com"), "Your sign-in to openbot.example.com has ended. Sign in again to keep going." ); - // The two sentences every OpenBot app says when it and the OpenBot don't fit - // (`shared/client-version.ts`): "Ask whoever runs your OpenBot to update it" when that - // OpenBot is too old, "Update OpenBot" when this app is. assert_eq!( Kind::TooOld.said("127.0.0.1:4000"), - "The OpenBot at 127.0.0.1:4000 is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser." + "The OpenBot at 127.0.0.1:4000 is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser." ); + // This app too old for that OpenBot, as every OpenBot app says it (`shared/client-version.ts`). assert_eq!( Kind::AppTooOld.said("openbot.example.com"), "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again." diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 32f14cebe5..96d1f586bf 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -921,7 +921,7 @@ const CONNECT_PROBLEMS: Array<{ kind: "too-old", at: "check", offer: "Open in browser", - said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser.", + said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser.", }, { kind: "app-too-old", diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index b4cb29ec4e..2645b7375f 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -11,7 +11,7 @@ import { APP_TOO_OLD, UpdateOpenBot } from "./UpdateOpenBot"; * * `field`: the address is what to fix, so the sentence sits under the field and the field has the * focus. `sign-in` and `retry`: the screen's one button says Sign in again or Try again. `browser`: - * that OpenBot is too old for this app, and a link opens it in the browser. `update`: this app is + * this app can't connect to that OpenBot, and a link opens it in the browser. `update`: this app is * too old for that OpenBot, and the way on is this app's own update. A kind this app does not know * is offered Try again. */ diff --git a/desktop/src/UpdateOpenBot.tsx b/desktop/src/UpdateOpenBot.tsx index d683c86e70..2acf1fe4f1 100644 --- a/desktop/src/UpdateOpenBot.tsx +++ b/desktop/src/UpdateOpenBot.tsx @@ -7,8 +7,8 @@ import { type AppUpdate, describe } from "./UpdateOffer"; /** * The `kind` the shell gives a problem when this app is older than the OpenBot it talks to serves - * (`client_version::APP_TOO_OLD`): connected to a company's OpenBot whose admin raised the oldest - * app it serves, or with an OpenBot on this computer that needs a newer app. + * (`client_version::APP_TOO_OLD`): connected to an OpenBot, such as OpenBot Cloud, that raised the + * oldest app it serves, or with an OpenBot on this computer that needs a newer app. */ export const APP_TOO_OLD = "app-too-old"; diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts index be55fd2eb9..d57dfc8043 100644 --- a/desktop/src/setupLayout.browser.test.ts +++ b/desktop/src/setupLayout.browser.test.ts @@ -87,12 +87,11 @@ fake.emit = emit; // the back end's, which the window runs first (a Mac at 8.2 GB). const updateShort = location.hash === "#update-short"; const backEndShort = location.hash === "#backend-short"; -// An OpenBot and this app that don't fit, as the shell says it: connected to a company's OpenBot -// that needs a newer app, or that is too old for this one; one whose sign-in ended, as it always -// was; and the OpenBot on this computer needing a newer app once Start has it running. +// This app too old for its OpenBot, as the shell says it: connected to an OpenBot (such as OpenBot +// Cloud) that needs a newer app; one whose sign-in ended, as it always was; and the OpenBot on +// this computer needing a newer app once Start has it running. const CONNECTED_PROBLEMS = { "#connect-app-too-old": { said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", kind: "app-too-old" }, - "#connect-too-old": { said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs your OpenBot to update it, or open it in your browser.", kind: "too-old" }, "#connect-session-ended": { said: "Your sign-in to openbot.example.com has ended. Sign in again to keep going.", kind: "session-ended" }, }; const connectedProblem = CONNECTED_PROBLEMS[location.hash]; @@ -2169,13 +2168,13 @@ describe.skipIf(!asked)( ); /* - * When this app and its OpenBot don't fit (`client_version.rs`), the window says the shell's - * sentence and offers its one way on, in view and uncovered, without outgrowing the window: Update - * and restart when this app is too old, Open in browser when that OpenBot is. Beside them a problem - * the screen always had, a sign-in that ended, for comparison. With `OPENBOT_SHOTS_DIR` set, each is + * When this app is too old for its OpenBot (`client_version.rs`), the window says the shell's + * sentence and offers its one way on, Update and restart, in view and uncovered, without outgrowing + * the window. Beside them problems the screen always had, a sign-in that ended and a found-running + * OpenBot that fails to show, for comparison. With `OPENBOT_SHOTS_DIR` set, each is * saved there in light and dark, at the window's default size. */ -describe.skipIf(!asked)("an OpenBot and this app that don't fit", () => { +describe.skipIf(!asked)("an OpenBot this app is too old for", () => { const shots = process.env.OPENBOT_SHOTS_DIR; const states: { name: string; @@ -2195,12 +2194,6 @@ describe.skipIf(!asked)("an OpenBot and this app that don't fit", () => { said: "needs a newer version of this app. Update OpenBot, then connect again.", way: { role: "button", name: "Update and restart" }, }, - { - name: "connected-server-too-old", - at: "#connect-too-old", - said: "Ask whoever runs your OpenBot to update it, or open it in your browser.", - way: { role: "link", name: "Open in browser" }, - }, { name: "local-app-too-old", at: "#local-app-too-old", diff --git a/mobile/src/api/generated/model/minimumClients.ts b/mobile/src/api/generated/model/minimumClients.ts index 26e1e29164..bedba5d4b8 100644 --- a/mobile/src/api/generated/model/minimumClients.ts +++ b/mobile/src/api/generated/model/minimumClients.ts @@ -4,7 +4,7 @@ import type { ClientRelease } from "./clientRelease"; /** - * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. Absent from a release before it was published. + * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published. */ export interface MinimumClients { web?: ClientRelease; diff --git a/mobile/src/client-version.ts b/mobile/src/client-version.ts index 976bb024fb..d5f29bc03d 100644 --- a/mobile/src/client-version.ts +++ b/mobile/src/client-version.ts @@ -18,9 +18,6 @@ export const API_VERSIONS: readonly string[] = ["v2"]; /** What a person reads when the app is older than the OpenBot it talks to serves. */ export const APP_UPDATE_SENTENCE = "Update OpenBot"; -/** What a person reads when the OpenBot is older than the app can use. */ -export const SERVER_UPDATE_SENTENCE = - "Ask whoever runs your OpenBot to update it"; /** The apps that name themselves, as the server's minimums list them. */ type ClientKind = "web" | "desktop" | "mobile" | "recorder"; @@ -81,7 +78,8 @@ function major(version: string): number | undefined { /** * - `ok`: they can. Features the server lacks are hidden by the fields that offer them, never by a version. * - `app`: the app is too old. "Update OpenBot". - * - `server`: the server is too old. "Ask whoever runs your OpenBot to update it". + * - `server`: the server serves only API versions older than any the app speaks. The phone app adds nothing for it: + * whoever runs that OpenBot keeps it and their apps matched, and the screens say what failed, as they always have. */ export type Compatibility = | { fit: "ok" } @@ -90,14 +88,12 @@ export type Compatibility = /** * Whether an app and the OpenBot it talks to can work together, from that OpenBot's `deployment`. A `deployment` that - * publishes no `api` is from a release before this check, and every such release serves v2. `"before-v2"` is an - * OpenBot that answers no `deployment` but still answers as an OpenBot: a release from before the v2 API. + * publishes no `api` is from a release before this check, and every such release serves v2. */ export function compatibility( - deployment: { api?: unknown; minimumClients?: unknown } | "before-v2", + deployment: { api?: unknown; minimumClients?: unknown }, client: { kind: ClientKind; version: string; speaks?: readonly string[] }, ): Compatibility { - if (deployment === "before-v2") return { fit: "server" }; const speaks = client.speaks ?? API_VERSIONS; const served = Array.isArray(deployment.api) ? deployment.api.filter( @@ -125,19 +121,6 @@ export function compatibility( return { fit: "ok" }; } -/** - * Whether an answer at `/api/capabilities` is an OpenBot's: every OpenBot release answers there with its edition and - * what it offers, and one from before the v2 API answers nowhere else. - */ -export function isOpenBotCapabilities(body: unknown): boolean { - if (!body || typeof body !== "object") return false; - const answer = body as Record; - return ( - typeof answer.edition === "string" && - typeof answer.generativeUi === "boolean" - ); -} - /** * What the update screen says under "Update OpenBot": OpenBot's own sentence for refusing this app (as * shared/client-version.ts `clientUpdateDetail` words it for the phone app), with the release it needs when known. @@ -148,11 +131,8 @@ export function phoneUpdateDetail(minimum?: string): string { : "This OpenBot needs a newer OpenBot phone app. Update OpenBot, then try again."; } -/** What the root layout shows: the app, or one of the two sentences. */ -export type VersionVerdict = - | { kind: "ok" } - | { kind: "app"; detail: string } - | { kind: "server" }; +/** What the root layout shows: the app, or "Update OpenBot". */ +export type VersionVerdict = { kind: "ok" } | { kind: "app"; detail: string }; /** * Anything that learns OpenBot refused this app as too old (a request's CLIENT_UPDATE_REQUIRED) says so here, and the diff --git a/mobile/src/version-check.ts b/mobile/src/version-check.ts index 1ff0cf49c5..cf8baf289a 100644 --- a/mobile/src/version-check.ts +++ b/mobile/src/version-check.ts @@ -1,36 +1,20 @@ /** - * Whether this phone app can work with the OpenBot it was built for, asked before anybody signs in. + * Whether this phone app is new enough for the OpenBot it was built for, asked before anybody signs in. * * The app reads the OpenBot's `deployment` (which answers before sign-in) and decides by the rule in ./client-version. - * An OpenBot that answers no `deployment` but answers `/api/capabilities` as an OpenBot is from before the v2 API, and - * too old. Anything else that fails here decides nothing: the screens say what failed, as they always have. + * Only an app too old for its OpenBot is stopped, with "Update OpenBot". Anything else decides nothing: the screens say + * what failed, as they always have. */ -import { - ApiError, - DEPLOYMENT_ORGANIZATION_ID, - apiRequest, -} from "./api/request"; +import { ApiError, DEPLOYMENT_ORGANIZATION_ID } from "./api/request"; import { getDeployment } from "./api/generated/organization-settings/organization-settings"; import { CLIENT_UPDATE_REQUIRED, compatibility, - isOpenBotCapabilities, phoneUpdateDetail, type VersionVerdict, } from "./client-version"; import { RELEASE } from "./release"; -/** Whether the server answers `/api/capabilities` as an OpenBot does. */ -async function answersAsOpenBot(): Promise { - try { - return isOpenBotCapabilities( - await apiRequest("/api/capabilities"), - ); - } catch { - return false; - } -} - export async function checkVersion(): Promise { let deployment: Awaited>; try { @@ -38,12 +22,6 @@ export async function checkVersion(): Promise { } catch (error) { if (error instanceof ApiError && error.code === CLIENT_UPDATE_REQUIRED) return { kind: "app", detail: error.message }; - if ( - error instanceof ApiError && - error.status === 404 && - (await answersAsOpenBot()) - ) - return { kind: "server" }; return { kind: "ok" }; } // A build that names no release can still tell an API it doesn't speak; it is never refused for a version. @@ -53,6 +31,5 @@ export async function checkVersion(): Promise { }); if (fit.fit === "app") return { kind: "app", detail: phoneUpdateDetail(fit.minimum) }; - if (fit.fit === "server") return { kind: "server" }; return { kind: "ok" }; } diff --git a/mobile/src/version-gate.tsx b/mobile/src/version-gate.tsx index 777584bd31..483c66c6f2 100644 --- a/mobile/src/version-gate.tsx +++ b/mobile/src/version-gate.tsx @@ -1,7 +1,6 @@ /** - * The screen the root layout shows in place of the app when it and its OpenBot can't work together: the app is too old - * ("Update OpenBot") or the OpenBot is ("Ask whoever runs your OpenBot to update it"). It covers everything, headers - * included, so nothing behind it is shown failing. + * The screen the root layout shows in place of the app when the app is too old for its OpenBot ("Update OpenBot"). It + * covers everything, headers included, so nothing behind it is shown failing. */ import { useCallback, useEffect, useState } from "react"; import { @@ -16,7 +15,6 @@ import { serverUrl } from "./auth"; import { APP_UPDATE_SENTENCE, onUpdateRequired, - SERVER_UPDATE_SENTENCE, type VersionVerdict, } from "./client-version"; import { heading, muted } from "./ui"; @@ -70,15 +68,9 @@ export function VersionGate({ ) : ( - {verdict.kind === "app" - ? APP_UPDATE_SENTENCE - : SERVER_UPDATE_SENTENCE} - - - {verdict.kind === "app" - ? verdict.detail - : `The OpenBot at ${new URL(serverUrl).host} is on a release this app can't connect to yet.`} + {APP_UPDATE_SENTENCE} + {verdict.detail} {serverUrl}
@@ -131,12 +142,21 @@ function loadAgain() { window.location.reload(); } -/** This page is older than the OpenBot serves: the OpenBot serves the new one on the next load. */ -function PageUpdate() { +/** + * This page is older than the OpenBot serves: the OpenBot serves the new one on the next load. For a + * security problem the heading says so and already says what to do, so no line repeats it. + */ +function PageUpdate({ security }: { security: boolean }) { return ( <> - {APP_UPDATE_SENTENCE} - This page is from an older version of OpenBot. + {security ? ( + {SECURITY_UPDATE_SENTENCE} + ) : ( + <> + {APP_UPDATE_SENTENCE} + This page is from an older version of OpenBot. + + )} @@ -167,7 +187,13 @@ function ServerUpdate() { * offers it, with how far the download has got; or, on a build that never updates itself, what to * do instead. */ -function DesktopUpdate({ minimum }: { minimum?: string }) { +function DesktopUpdate({ + minimum, + security, +}: { + minimum?: string; + security: boolean; +}) { const offer = useQuery(desktopAppUpdateQueryOptions()); const install = useMutation(installAppUpdateMutationOptions(queryClient)); const updatesItself = offer.data?.updatesItself !== false; @@ -175,7 +201,9 @@ function DesktopUpdate({ minimum }: { minimum?: string }) { const busy = install.isPending || progress !== null; return ( <> - {APP_UPDATE_SENTENCE} + + {security ? SECURITY_UPDATE_SENTENCE : APP_UPDATE_SENTENCE} + {minimum ? `This OpenBot needs OpenBot Desktop ${minimum} or later.` diff --git a/app/src/lib/api/generated/model/deployment.ts b/app/src/lib/api/generated/model/deployment.ts index 30cb696d50..b113d710fb 100644 --- a/app/src/lib/api/generated/model/deployment.ts +++ b/app/src/lib/api/generated/model/deployment.ts @@ -44,6 +44,8 @@ export interface Deployment { */ api?: string[]; minimumClients?: MinimumClients; + /** The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is. */ + securityMinimumClients?: MinimumClients; /** * The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. * @minimum 1 diff --git a/app/src/lib/api/generated/model/problem.ts b/app/src/lib/api/generated/model/problem.ts index 6ed25de3a0..c92b9572e8 100644 --- a/app/src/lib/api/generated/model/problem.ts +++ b/app/src/lib/api/generated/model/problem.ts @@ -36,4 +36,6 @@ export interface Problem { client?: ProblemClient; /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ minimumVersion?: string; + /** On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. */ + security?: boolean; } diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts index 0ee9a86730..92b1353bf7 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts @@ -33,6 +33,15 @@ export const getDeploymentResponseMinimumClientsMobileRegExp = new RegExp( export const getDeploymentResponseMinimumClientsRecorderRegExp = new RegExp( "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", ); +export const getDeploymentResponseSecurityMinimumClientsWebRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseSecurityMinimumClientsDesktopRegExp = + new RegExp("^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$"); +export const getDeploymentResponseSecurityMinimumClientsMobileRegExp = + new RegExp("^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$"); +export const getDeploymentResponseSecurityMinimumClientsRecorderRegExp = + new RegExp("^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$"); export const GetDeploymentResponse = zod .object({ @@ -134,6 +143,33 @@ export const GetDeploymentResponse = zod .describe( "The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published.", ), + securityMinimumClients: zod + .object({ + web: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsWebRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + desktop: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsDesktopRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + mobile: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsMobileRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + recorder: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsRecorderRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + }) + .optional() + .describe( + "The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is.", + ), launcherApi: zod .int() .min(1) diff --git a/app/src/lib/client-version/refusal.ts b/app/src/lib/client-version/refusal.ts index 1d756ee764..59ef6a1b92 100644 --- a/app/src/lib/client-version/refusal.ts +++ b/app/src/lib/client-version/refusal.ts @@ -4,7 +4,8 @@ * Every request names this app in the `OpenBot-Client` header (`lib/client.ts`). An OpenBot whose * oldest served release of that app is newer than it refuses every request except its `deployment` * with a 400 problem whose code is CLIENT_UPDATE_REQUIRED, naming the app (`client`) and the oldest - * release it serves (`minimumVersion`). Inside OpenBot Desktop's window the desktop app adds its own + * release it serves (`minimumVersion`), and `security: true` when that minimum was raised because of a + * security problem in older releases. Inside OpenBot Desktop's window the desktop app adds its own * name to the page's header, so there the app named can be OpenBot Desktop rather than this page. * * `lib/client.ts` hands every 400 here before the caller sees it. The first refusal is kept until the @@ -20,8 +21,15 @@ import { isVersion, } from "@openbot/shared/client-version"; -/** The app the OpenBot refused, and the oldest release of it that OpenBot serves. */ -export type ClientRefusal = { client: ClientKind; minimumVersion?: string }; +/** + * The app the OpenBot refused, the oldest release of it that OpenBot serves, and `security` when that + * minimum is there for a security problem. + */ +export type ClientRefusal = { + client: ClientKind; + minimumVersion?: string; + security?: true; +}; let refused: ClientRefusal | null = null; const listeners = new Set<() => void>(); @@ -33,15 +41,20 @@ export function clientRefusalOf(body: unknown): ClientRefusal | null { code?: unknown; client?: unknown; minimumVersion?: unknown; + security?: unknown; }; if (problem.code !== CLIENT_UPDATE_REQUIRED) return null; // A refusal that names no app we know is still this page's to act on: it is the page that asked. const client = (CLIENT_KINDS as readonly unknown[]).includes(problem.client) ? (problem.client as ClientKind) : "web"; - return isVersion(problem.minimumVersion) - ? { client, minimumVersion: problem.minimumVersion } - : { client }; + return { + client, + ...(isVersion(problem.minimumVersion) + ? { minimumVersion: problem.minimumVersion } + : {}), + ...(problem.security === true ? { security: true as const } : {}), + }; } /** diff --git a/app/tests/client-version-gate.test.tsx b/app/tests/client-version-gate.test.tsx index e0392a1e24..fd7be15e9f 100644 --- a/app/tests/client-version-gate.test.tsx +++ b/app/tests/client-version-gate.test.tsx @@ -30,6 +30,7 @@ import { compatibility, parseClientHeader, RELEASE, + SECURITY_UPDATE_SENTENCE, SERVER_UPDATE_SENTENCE, } from "@openbot/shared/client-version"; import { DOESNT_UPDATE_ITSELF } from "@openbot/shared/desktop-updates"; @@ -68,19 +69,29 @@ const SPEC_REFUSAL = { title: "This app is too old for this OpenBot.", status: 400, detail: - "This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again.", + "This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again.", code: "CLIENT_UPDATE_REQUIRED", category: "validation", retryable: false, requestId: "req_example", traceId: "trace_example", client: "desktop", - minimumVersion: "1.0.2", + minimumVersion: "1.2.0", +}; + +/** The spec's example of a refusal for a security problem (`clientUpdateRequiredSecurity`), as is. */ +const SPEC_SECURITY_REFUSAL = { + ...SPEC_REFUSAL, + detail: + "This version of OpenBot has a security problem. Update to keep using it.", + security: true, }; /** What the OpenBot answers: its `deployment`, and whether it refuses every other v2 operation. */ let deployment: DeploymentName; let refuseEverything: boolean; +/** What it refuses every other v2 operation with, when it does. */ +let refusalBody: Record; const NativeResponse = globalThis.Response; let openbot: ReturnType; @@ -96,7 +107,7 @@ function answer(request: Request): Response { const published = cases.deployments[deployment]; if (/^\/api\/v2\/organizations\/[^/]+\/deployment$/.test(path)) return NativeResponse.json(published); - if (refuseEverything) return problem(400, SPEC_REFUSAL); + if (refuseEverything) return problem(400, refusalBody); // A later OpenBot that serves only v3 no longer answers at v2. One that names no API serves v2. if ("api" in published && !published.api.includes("v2")) return problem(404, { code: "NOT_FOUND" }); @@ -130,6 +141,7 @@ beforeAll(() => { beforeEach(() => { deployment = "current"; refuseEverything = false; + refusalBody = SPEC_REFUSAL; queryClient.clear(); // The page is at the server. globalThis.fetch = pageFetch(); @@ -303,9 +315,59 @@ test("any request refused with CLIENT_UPDATE_REQUIRED brings up Update OpenBot, ).toBeTruthy(); expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); expect(view.queryByText(SPEC_REFUSAL.detail)).toBeNull(); + // A plain raise is not a security problem. + expect(view.queryByText(SECURITY_UPDATE_SENTENCE)).toBeNull(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("a refusal for a security problem says so in place of Update OpenBot, with the same Update", async () => { + refuseEverything = true; + refusalBody = SPEC_SECURITY_REFUSAL; + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: SECURITY_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.queryByText(APP_UPDATE_SENTENCE)).toBeNull(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); }, 15_000); +test("an OpenBot whose deployment raised an app's minimum for a security problem: that app reads the security sentence", async () => { + deployment = "security"; + const app = { kind: "recorder" as const, version: "1.1.0" }; + expect(compatibility(cases.deployments.security, app)).toEqual({ + fit: "app", + minimum: "1.2.0", + security: true, + }); + const view = openApp(app); + expect( + await view.findByRole( + "heading", + { name: SECURITY_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + cleanup(); + // The same OpenBot's plain raise, for an app it raised for no security problem, reads as before. + deployment = "raised"; + queryClient.clear(); + const plain = openApp(app); + expect( + await plain.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(plain.queryByText(SECURITY_UPDATE_SENTENCE)).toBeNull(); +}, 15_000); + /** OpenBot Desktop's window around the page, answering its plugin's update commands. */ function insideDesktop(updatesItself: boolean, installed: string[]) { (window as unknown as Record).__TAURI_INTERNALS__ = { @@ -343,7 +405,7 @@ test("inside OpenBot Desktop, a refusal naming OpenBot Desktop offers its own Up ), ).toBeTruthy(); expect( - view.getByText("This OpenBot needs OpenBot Desktop 1.0.2 or later."), + view.getByText("This OpenBot needs OpenBot Desktop 1.2.0 or later."), ).toBeTruthy(); const update = await view.findByRole( "button", @@ -357,6 +419,30 @@ test("inside OpenBot Desktop, a refusal naming OpenBot Desktop offers its own Up ).toBe("Couldn't install the update: No update is available right now."); }, 15_000); +test("inside OpenBot Desktop, a refusal of it for a security problem says so, with its own Update and restart", async () => { + refuseEverything = true; + refusalBody = SPEC_SECURITY_REFUSAL; + insideDesktop(true, []); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: SECURITY_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This OpenBot needs OpenBot Desktop 1.2.0 or later."), + ).toBeTruthy(); + expect( + await view.findByRole( + "button", + { name: "Update and restart" }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); +}, 15_000); + test("inside an OpenBot Desktop that never updates itself, it says what to do instead", async () => { refuseEverything = true; insideDesktop(false, []); diff --git a/desktop/src-tauri/src/client_version.rs b/desktop/src-tauri/src/client_version.rs index dc8bc1d479..b77ab64e5a 100644 --- a/desktop/src-tauri/src/client_version.rs +++ b/desktop/src-tauri/src/client_version.rs @@ -29,6 +29,15 @@ pub const API_VERSIONS: &[&str] = &["v2"]; /// offers this app's own update for it, wherever it shows. pub const APP_TOO_OLD: &str = "app-too-old"; +/// The `kind` for the same when the minimum this app is below was raised because of a security +/// problem in older releases. The window offers the same update and says [`SECURITY_UPDATE`]. +pub const APP_TOO_OLD_SECURITY: &str = "app-too-old-security"; + +/// What the person reads in place of "Update OpenBot" when the minimum was raised for a security +/// problem (`shared/client-version.ts` `SECURITY_UPDATE_SENTENCE`). +pub const SECURITY_UPDATE: &str = + "This version of OpenBot has a security problem. Update to keep using it."; + static VERSION: OnceLock = OnceLock::new(); /** @@ -99,8 +108,13 @@ pub enum Fit { /// They can. Features that OpenBot lacks are hidden by the fields that offer them. Ok, /// The app is too old: that OpenBot serves only newer API versions, or names a minimum for - /// this app above its version (`minimum`). "Update OpenBot". - App { minimum: Option }, + /// this app above its version (`minimum`). "Update OpenBot". `security` when it also names this + /// app in `securityMinimumClients` above its version: the minimum is there for a security + /// problem, and the person reads [`SECURITY_UPDATE`] instead. + App { + minimum: Option, + security: bool, + }, /// That OpenBot is too old: it serves only API versions older than any the app speaks. Server, } @@ -209,25 +223,30 @@ pub fn compatibility(deployment: &Deployment, kind: &str, version: &str, speaks: let newest_spoken = speaks.iter().filter_map(|v| major(v)).max(); // Only newer versions than any the app speaks: the app is behind. Otherwise the server is. return if newest_served > newest_spoken { - Fit::App { minimum: None } + Fit::App { + minimum: None, + security: false, + } } else { Fit::Server }; } - let minimum = deployment - .get("minimumClients") - .and_then(serde_json::Value::as_object) - .and_then(|minimums| minimums.get(kind)) - .and_then(serde_json::Value::as_str) - .filter(|minimum| is_version(minimum)); - if let Some(minimum) = minimum { - if compare_versions(version, minimum) == Some(std::cmp::Ordering::Less) { - return Fit::App { - minimum: Some(minimum.to_owned()), - }; - } + let below = |field: &str| { + deployment + .get(field) + .and_then(serde_json::Value::as_object) + .and_then(|minimums| minimums.get(kind)) + .and_then(serde_json::Value::as_str) + .filter(|minimum| is_version(minimum)) + .filter(|minimum| compare_versions(version, minimum) == Some(std::cmp::Ordering::Less)) + }; + match below("minimumClients") { + Some(minimum) => Fit::App { + minimum: Some(minimum.to_owned()), + security: below("securityMinimumClients").is_some(), + }, + None => Fit::Ok, } - Fit::Ok } /// [`compatibility`] for this app. @@ -248,6 +267,14 @@ pub fn why(deployment: &Deployment, fit: &Fit) -> String { match fit { Fit::App { minimum: Some(minimum), + security: true, + } => format!( + "the deployment's minimumClients.{KIND} is {minimum}, raised for a security problem \ + (securityMinimumClients); {this}" + ), + Fit::App { + minimum: Some(minimum), + .. } => format!("the deployment's minimumClients.{KIND} is {minimum}; {this}"), _ => format!("the deployment says {served}; {this}"), } @@ -289,11 +316,16 @@ pub fn local_problem(base: &str, install_token: Option<&str>) -> Option return None; }; let decided = fit(&deployment); - let Fit::App { .. } = decided else { + let Fit::App { security, .. } = decided else { return None; }; - let mut problem = Problem::with(LOCAL_APP_TOO_OLD, why(&deployment, &decided)); - problem.kind = Some(APP_TOO_OLD); + let (said, kind) = if security { + (SECURITY_UPDATE, APP_TOO_OLD_SECURITY) + } else { + (LOCAL_APP_TOO_OLD, APP_TOO_OLD) + }; + let mut problem = Problem::with(said, why(&deployment, &decided)); + problem.kind = Some(kind); Some(problem) } @@ -339,7 +371,7 @@ mod tests { fn every_case_in_the_shared_fixture_is_decided_as_the_contract_says() { let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); let list = cases["cases"].as_array().unwrap(); - assert!(list.len() >= 15, "the fixture lost its cases"); + assert!(list.len() >= 19, "the fixture lost its cases"); for case in list { let name = case["deployment"].as_str().unwrap(); let client = &case["client"]; @@ -359,6 +391,7 @@ mod tests { "server" => Fit::Server, "app" => Fit::App { minimum: case["minimum"].as_str().map(str::to_owned), + security: case["security"].as_bool().unwrap_or(false), }, other => panic!("an unknown fit {other}"), }; @@ -407,22 +440,30 @@ mod tests { fn the_openbot_on_this_computer_says_update_openbot_only_when_it_needs_a_newer_app() { use crate::connected::fake_openbot::{FakeOpenBot, Shape}; let _version = as_version("1.1.0"); - for (shape, too_old) in [ - (Shape::Answers("raised"), true), - (Shape::Answers("v3-only"), true), - (Shape::Answers("current"), false), - (Shape::Answers("v1.1.0"), false), + let plain = Some(( + APP_TOO_OLD, + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + )); + let security = Some(( + APP_TOO_OLD_SECURITY, + "This version of OpenBot has a security problem. Update to keep using it.", + )); + for (shape, said) in [ + (Shape::Answers("raised"), plain), + (Shape::Answers("v3-only"), plain), + (Shape::Answers("security"), security), + (Shape::Answers("current"), None), + (Shape::Answers("v1.1.0"), None), ] { let server = FakeOpenBot::start(shape.clone()); let problem = local_problem(&server.address(), Some("install-token-abc")); - assert_eq!(problem.is_some(), too_old, "{shape:?}: {problem:?}"); - if let Some(problem) = problem { - assert_eq!(problem.kind, Some(APP_TOO_OLD)); - assert_eq!( - problem.said, - "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going." - ); - } + assert_eq!( + problem + .as_ref() + .map(|problem| (problem.kind.unwrap(), problem.said.as_str())), + said, + "{shape:?}: {problem:?}" + ); let asked = server.seen_at(crate::connected::address::DEPLOYMENT); assert_eq!(asked.len(), 1, "{shape:?}"); assert_eq!(asked[0].header("openbot-client"), Some("desktop/1.1.0")); diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs index 96a6daee4e..0c6bbb4a6d 100644 --- a/desktop/src-tauri/src/connected/address.rs +++ b/desktop/src-tauri/src/connected/address.rs @@ -114,8 +114,13 @@ pub fn probe(address: &str) -> Result { // only an older API is told as an OpenBot this app can't connect to always was. match client_version::fit(deployment) { client_version::Fit::Ok => {} - fit @ client_version::Fit::App { .. } => { - return Err(Kind::AppTooOld.problem(&host, client_version::why(deployment, &fit))); + fit @ client_version::Fit::App { security, .. } => { + let kind = if security { + Kind::AppTooOldSecurity + } else { + Kind::AppTooOld + }; + return Err(kind.problem(&host, client_version::why(deployment, &fit))); } fit @ client_version::Fit::Server => { return Err(Kind::TooOld.problem(&host, client_version::why(deployment, &fit))); @@ -365,6 +370,20 @@ mod tests { ); assert!(server.seen_at(METADATA).is_empty(), "{name}"); } + // One that raised this app's minimum for a security problem says so instead, and offers the + // same update. + let security = FakeOpenBot::start(Shape::Answers("security")); + let problem = check(&security.address()).expect_err("security"); + assert_eq!(kind_of(&problem), Some(Kind::AppTooOldSecurity)); + assert_eq!( + problem.said, + "This version of OpenBot has a security problem. Update to keep using it." + ); + assert_eq!( + problem.detail.as_deref(), + Some("the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2") + ); + assert!(security.seen_at(METADATA).is_empty()); // What the log says beside the sentence: what that OpenBot asked for, against this app. let raised = FakeOpenBot::start(Shape::Answers("raised")); let problem = check(&raised.address()).expect_err("raised"); @@ -380,10 +399,14 @@ mod tests { #[test] fn the_launch_check_catches_an_openbot_that_moved_since_the_app_connected() { let _version = crate::client_version::as_version("1.1.0"); - for name in ["raised", "v3-only"] { + for (name, kind) in [ + ("raised", Kind::AppTooOld), + ("v3-only", Kind::AppTooOld), + ("security", Kind::AppTooOldSecurity), + ] { let server = FakeOpenBot::start(Shape::Answers(name)); let problem = probe(&server.address()).expect_err(name); - assert_eq!(kind_of(&problem), Some(Kind::AppTooOld), "{name}"); + assert_eq!(kind_of(&problem), Some(kind), "{name}"); } } diff --git a/desktop/src-tauri/src/connected/fake_openbot_tests.rs b/desktop/src-tauri/src/connected/fake_openbot_tests.rs index 5a1dcfa4fb..a0be752470 100644 --- a/desktop/src-tauri/src/connected/fake_openbot_tests.rs +++ b/desktop/src-tauri/src/connected/fake_openbot_tests.rs @@ -63,8 +63,8 @@ pub enum Shape { /// Its revocation endpoint fails with a 500 whatever it is sent. RevokeBroken, /// Signs in as `Current` does, and answers `deployment` with one of the real answers in - /// `shared/fixtures/client-version/cases.json`, by name: `current`, `v1.1.0`, `raised` or - /// `v3-only`. + /// `shared/fixtures/client-version/cases.json`, by name: `current`, `v1.1.0`, `raised`, + /// `security` or `v3-only`. Answers(&'static str), } diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs index db90ce0a31..44ff280019 100644 --- a/desktop/src-tauri/src/connected/mod.rs +++ b/desktop/src-tauri/src/connected/mod.rs @@ -43,6 +43,8 @@ pub enum Kind { TooOld, /// This app is older than that OpenBot serves: the window offers this app's own update. AppTooOld, + /// The same, for a minimum that OpenBot raised because of a security problem. + AppTooOldSecurity, SignInCancelled, SignInFailed, /// Signed in, and then the OpenBot refused the new sign-in on the app's screens (401 or 403). @@ -60,6 +62,7 @@ impl Kind { Kind::SinglePerson => "single-person", Kind::TooOld => "too-old", Kind::AppTooOld => crate::client_version::APP_TOO_OLD, + Kind::AppTooOldSecurity => crate::client_version::APP_TOO_OLD_SECURITY, Kind::SignInCancelled => "sign-in-cancelled", Kind::SignInFailed => "sign-in-failed", Kind::AccessRefused => "access-refused", @@ -92,6 +95,7 @@ impl Kind { "The OpenBot at {host} needs a newer version of this app. Update OpenBot, then \ connect again." ), + Kind::AppTooOldSecurity => crate::client_version::SECURITY_UPDATE.into(), Kind::SignInCancelled => "Sign-in didn't finish. Try again when you're ready.".into(), Kind::SignInFailed => format!( "OpenBot couldn't sign you in at {host}. Try again, or ask whoever runs your OpenBot." @@ -132,6 +136,7 @@ pub fn kind_of(problem: &Problem) -> Option { Kind::SinglePerson, Kind::TooOld, Kind::AppTooOld, + Kind::AppTooOldSecurity, Kind::SignInCancelled, Kind::SignInFailed, Kind::AccessRefused, @@ -227,6 +232,16 @@ mod tests { Kind::AppTooOld.said("openbot.example.com"), "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again." ); + assert_eq!( + Kind::AppTooOldSecurity.said("openbot.example.com"), + "This version of OpenBot has a security problem. Update to keep using it." + ); + let insecure = Kind::AppTooOldSecurity.problem("openbot.example.com", "security"); + assert_eq!(kind_of(&insecure), Some(Kind::AppTooOldSecurity)); + assert_eq!( + serde_json::to_value(&insecure).unwrap()["kind"], + "app-too-old-security" + ); let too_old = Kind::AppTooOld.problem("openbot.example.com", "minimum 1.2.0"); assert_eq!(kind_of(&too_old), Some(Kind::AppTooOld)); assert_eq!( diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 34533e5ad4..9a4cd11855 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -24289,7 +24289,8 @@ fn main() { /// The OpenBot on this computer is read as every app reads it before the window opens it /// (API versioning design, 7.1). One whose admin raised the oldest app it serves above this - /// one, or one that serves only a newer API, is not shown: the window says "Update OpenBot" + /// one, or one that serves only a newer API, is not shown: the window says "Update OpenBot", or + /// that this version has a security problem when the minimum was raised for one, /// and offers this app's update, and Show Window keeps it on setup. One left at 1.1.0, which /// publishes no version fields, opens exactly as before. Every request names this app. #[test] @@ -24320,17 +24321,32 @@ fn main() { let mut raised = answer("raised"); let major: u64 = version.split('.').next().unwrap().parse().unwrap(); raised["minimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); - - for too_new in [raised, answer("v3-only")] { + // The fixture's `security`, the same minimum raised for a security problem. + let mut security = answer("security"); + security["minimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); + security["securityMinimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); + let plain = ( + "app-too-old", + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + ); + + for (too_new, (kind, said)) in [ + (raised, plain), + (answer("v3-only"), plain), + ( + security, + ( + "app-too-old-security", + "This version of OpenBot has a security problem. Update to keep using it.", + ), + ), + ] { std::fs::write(f.owned.join("deployment.json"), too_new.to_string()).unwrap(); let app = f.app(&f.owned, "tauri://localhost/"); assert!(already_running_now(app.handle(), &root)); let problem = show_openbot_on(app.handle().clone(), &f.ports).unwrap_err(); - assert_eq!(problem.kind, Some("app-too-old"), "{too_new}"); - assert_eq!( - problem.said, - "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going." - ); + assert_eq!(problem.kind, Some(kind), "{too_new}"); + assert_eq!(problem.said, said); assert_eq!(window_url(&app), "http://127.0.0.1:9/stale-page"); restore_window_on(app.handle(), &f.ports); assert_eq!(window_url(&app), "tauri://localhost/"); diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 96d1f586bf..258e48cfaa 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -929,6 +929,12 @@ const CONNECT_PROBLEMS: Array<{ offer: "Update and restart", said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", }, + { + kind: "app-too-old-security", + at: "check", + offer: "Update and restart", + said: "This version of OpenBot has a security problem. Update to keep using it.", + }, { kind: "sign-in-cancelled", at: "connect", @@ -3975,6 +3981,43 @@ test("an OpenBot on this computer that needs a newer app says Update OpenBot, no expect(view.getByRole("button", { name: "Stop OpenBot" })).toBeTruthy(); }); +// The same, for a minimum raised because of a security problem: the security sentence is the heading, +// in place of Update OpenBot, and the card under it offers the update without saying it again. +test("an OpenBot on this computer that raised this app's minimum for a security problem says so as the heading", async () => { + setupConnectedLocalStack( + "/tmp/local-eval-app-too-old-security", + localStatus("ready", "valid"), + ); + const said = + "This version of OpenBot has a security problem. Update to keep using it."; + const previous = invokeHandler; + invokeHandler = async (command, args) => { + if (command === "show_openbot") + throw { + said, + detail: + "the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old-security", + }; + if (command === "app_update_offer") + return { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }; + return previous(command, args); + }; + const view = await renderApp(); + await waitFor(() => expect(localSequence()).toContain("start_stack")); + await view.findByRole("heading", { level: 1, name: said }); + expect(view.queryByRole("heading", { name: "Update OpenBot" })).toBeNull(); + expect(view.queryByRole("heading", { name: "OpenBot stopped" })).toBeNull(); + expect(view.getAllByText(said)).toHaveLength(1); + expect(view.getByRole("button", { name: "Update and restart" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Stop OpenBot" })).toBeTruthy(); +}); + test("relaunch says when Docker Desktop did not start, and Retry opens it again", async () => { setupConnectedLocalStack( "/tmp/local-eval-docker-never", diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index 32894d4743..3fc07fd7db 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -63,7 +63,7 @@ import { type SetupStep, } from "./telemetry"; import { choseThisComputer, rememberThisComputer } from "./thisComputer"; -import { AppTooOld, appTooOld } from "./UpdateOpenBot"; +import { AppTooOld, appTooOld, forSecurity } from "./UpdateOpenBot"; import { UsageDataChoice } from "./UsageDataChoice"; import { type Hosting, Welcome } from "./Welcome"; import { @@ -1753,11 +1753,13 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { {/* Running, and needing a newer version of this app: nothing stopped, so the heading says what to do and the card under it offers the update. */}

- {appTooOld(displayedFailure) - ? "Update OpenBot" - : displayedFailure - ? "OpenBot stopped" - : "OpenBot is running"} + {forSecurity(displayedFailure) && displayedFailure + ? displayedFailure.said + : appTooOld(displayedFailure) + ? "Update OpenBot" + : displayedFailure + ? "OpenBot stopped" + : "OpenBot is running"}

{/* The back end runs the release it had: information, said where the lede goes. Nothing failed, so it is not drawn as a failure and offers no help. */} diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index 2645b7375f..32dcda49ff 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -3,7 +3,11 @@ import { useEffect, useId, useRef, useState } from "react"; import { ExternalLink } from "./ExternalLink"; import { asProblem, type Problem } from "./Problem"; import { StatusLine } from "./SetupProgress"; -import { APP_TOO_OLD, UpdateOpenBot } from "./UpdateOpenBot"; +import { + APP_TOO_OLD, + APP_TOO_OLD_SECURITY, + UpdateOpenBot, +} from "./UpdateOpenBot"; /** * What the screen offers after something went wrong, chosen by the problem's `kind`. The sentence @@ -26,6 +30,7 @@ function offerFor(kind: string | null | undefined): Offer { case "too-old": return "browser"; case APP_TOO_OLD: + case APP_TOO_OLD_SECURITY: return "update"; case "sign-in-cancelled": case "sign-in-failed": diff --git a/desktop/src/Problem.test.tsx b/desktop/src/Problem.test.tsx index 49638524fb..c818c64c3a 100644 --- a/desktop/src/Problem.test.tsx +++ b/desktop/src/Problem.test.tsx @@ -88,6 +88,36 @@ test("an OpenBot that needs a newer app says Update OpenBot and Update and resta await waitFor(() => expect(update.textContent).toBe("Downloading…")); }); +/** The same, for a minimum the OpenBot on this computer raised because of a security problem. */ +const LOCAL_APP_TOO_OLD_SECURITY = { + said: "This version of OpenBot has a security problem. Update to keep using it.", + detail: + "the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old-security", +}; + +// For a security problem, the security sentence is the heading, in place of Update OpenBot, with the +// same update and nothing repeating it below. +test("an OpenBot that raised this app's minimum for a security problem says so in place of Update OpenBot, with the same update", async () => { + answers = { + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }, + }; + const view = render(); + expect( + view.getByRole("heading", { name: LOCAL_APP_TOO_OLD_SECURITY.said }), + ).toBeTruthy(); + expect(view.queryByRole("heading", { name: "Update OpenBot" })).toBeNull(); + expect(view.getAllByText(LOCAL_APP_TOO_OLD_SECURITY.said)).toHaveLength(1); + expect(view.queryByText("That didn’t finish")).toBeNull(); + const update = view.getByRole("button", { name: "Update and restart" }); + await waitFor(() => expect(update).toHaveProperty("disabled", false)); +}); + // A build that never updates itself has nothing to press: it says how to get one that does. test("an OpenBot that needs a newer app, on a build that doesn't update itself, says how to get one", async () => { answers = { diff --git a/desktop/src/UpdateOpenBot.tsx b/desktop/src/UpdateOpenBot.tsx index 2acf1fe4f1..12485ba743 100644 --- a/desktop/src/UpdateOpenBot.tsx +++ b/desktop/src/UpdateOpenBot.tsx @@ -12,9 +12,21 @@ import { type AppUpdate, describe } from "./UpdateOffer"; */ export const APP_TOO_OLD = "app-too-old"; -/** Whether a problem is this app being too old for its OpenBot. */ +/** + * The same, when the minimum this app is below was raised because of a security problem in older + * releases (`client_version::APP_TOO_OLD_SECURITY`). The shell's sentence says so, and the window + * puts it where "Update OpenBot" would be. + */ +export const APP_TOO_OLD_SECURITY = "app-too-old-security"; + +/** Whether a problem is this app being too old for its OpenBot, for a security problem or not. */ export function appTooOld(problem: Problem | null | undefined): boolean { - return problem?.kind === APP_TOO_OLD; + return problem?.kind === APP_TOO_OLD || forSecurity(problem); +} + +/** Whether this app is too old for its OpenBot because of a security problem. */ +export function forSecurity(problem: Problem | null | undefined): boolean { + return problem?.kind === APP_TOO_OLD_SECURITY; } /** How often to ask the shell how an install is going, as Check for updates does. */ @@ -170,22 +182,24 @@ export function UpdateOpenBot() { /** * An OpenBot that needs a newer version of this app, wherever setup shows a problem: the shell's * sentence, which says "Update OpenBot", and Update and restart. Nothing failed, so it is not drawn as - * a failure: no "That didn't finish", no technical details, no troubleshooting logs. + * a failure: no "That didn't finish", no technical details, no troubleshooting logs. For a security + * problem the shell's sentence is the heading, in place of "Update OpenBot", and is not said twice. */ export function AppTooOld({ problem, headed = true, }: { problem: Problem; - /** False where the screen's own heading already says "Update OpenBot". */ + /** False where the screen's own heading already says it. */ headed?: boolean; }) { + const security = forSecurity(problem); return ( // The calm notice the connect screen uses for a connection that didn't work, not the failure // card: nothing failed.
- {headed &&

Update OpenBot

} -

{problem.said}

+ {headed &&

{security ? problem.said : "Update OpenBot"}

} + {!security &&

{problem.said}

}
); diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts index d57dfc8043..1f73019a57 100644 --- a/desktop/src/setupLayout.browser.test.ts +++ b/desktop/src/setupLayout.browser.test.ts @@ -92,10 +92,13 @@ const backEndShort = location.hash === "#backend-short"; // this computer needing a newer app once Start has it running. const CONNECTED_PROBLEMS = { "#connect-app-too-old": { said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", kind: "app-too-old" }, + "#connect-app-too-old-security": { said: "This version of OpenBot has a security problem. Update to keep using it.", kind: "app-too-old-security" }, "#connect-session-ended": { said: "Your sign-in to openbot.example.com has ended. Sign in again to keep going.", kind: "session-ended" }, }; const connectedProblem = CONNECTED_PROBLEMS[location.hash]; -const localTooOld = location.hash === "#local-app-too-old"; +// The same, for a minimum raised because of a security problem. +const localSecurity = location.hash === "#local-app-too-old-security"; +const localTooOld = location.hash === "#local-app-too-old" || localSecurity; // A launch that finds this computer's OpenBot already running, and that it needs a newer app. const runningTooOld = location.hash === "#local-app-too-old-running"; // The same launch, where showing it fails as it could before: the slot the card above lands in. @@ -144,6 +147,12 @@ export async function invoke(command, args) { if ((runningTooOld || runningFails) && command === "already_running") return true; if (runningFails && command === "show_openbot") throw { said: "Part of OpenBot needs recovery. Try starting OpenBot once more." }; + if (localSecurity && command === "show_openbot") + throw { + said: "This version of OpenBot has a security problem. Update to keep using it.", + detail: "the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old-security", + }; if ((localTooOld || runningTooOld) && command === "show_openbot") throw { said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", @@ -2194,6 +2203,18 @@ describe.skipIf(!asked)("an OpenBot this app is too old for", () => { said: "needs a newer version of this app. Update OpenBot, then connect again.", way: { role: "button", name: "Update and restart" }, }, + { + name: "connected-app-too-old-security", + at: "#connect-app-too-old-security", + said: "This version of OpenBot has a security problem. Update to keep using it.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "local-app-too-old-security", + at: "#local-app-too-old-security", + said: "This version of OpenBot has a security problem. Update to keep using it.", + way: { role: "button", name: "Update and restart" }, + }, { name: "local-app-too-old", at: "#local-app-too-old", diff --git a/desktop/src/styles.css b/desktop/src/styles.css index 78c50d4409..02c09bb3a2 100644 --- a/desktop/src/styles.css +++ b/desktop/src/styles.css @@ -492,6 +492,11 @@ button.text-link:hover:not(:disabled) { margin-top: 12px; } +/* A card with nothing said above its button (the heading over it already says why): no gap above. */ +.local-alert.app-too-old > .row:first-child { + margin-top: 0; +} + /* Under its button, a line keeps the row's gap rather than touching the button. */ .local-alert .row + .footnote { margin-top: 12px; diff --git a/extension/src/background/connection.ts b/extension/src/background/connection.ts index 4cccbbec9e..52344d8502 100644 --- a/extension/src/background/connection.ts +++ b/extension/src/background/connection.ts @@ -900,7 +900,9 @@ async function desktopConnect( return refused( error instanceof OpenBotError ? error.updateRequired - ? "client-update-required" + ? error.securityUpdateRequired + ? "client-security-update-required" + : "client-update-required" : "exchange-refused" : "openbot-unreachable", ); diff --git a/extension/src/pages/popup/desktop-sentence.ts b/extension/src/pages/popup/desktop-sentence.ts index fef200bdcb..f69398946f 100644 --- a/extension/src/pages/popup/desktop-sentence.ts +++ b/extension/src/pages/popup/desktop-sentence.ts @@ -1,6 +1,6 @@ /** Why Connect with OpenBot Desktop did not connect this browser, one plain sentence per code: OpenBot Desktop's own * error codes, and the Recorder's (no answer, the policy, an address it cannot use, OpenBot not taking Desktop's code, - * OpenBot serving only newer Recorders). */ + * OpenBot serving only newer Recorders, for a security problem or not). */ const SENTENCES: Record = { "origin-not-allowed": "OpenBot Desktop does not recognise this copy of the Recorder. Connect from OpenBot in your browser instead.", @@ -30,6 +30,8 @@ const SENTENCES: Record = { "OpenBot did not accept the code OpenBot Desktop gave the Recorder. Try again.", "client-update-required": "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", + "client-security-update-required": + "This version of OpenBot has a security problem. Update to keep using it.", "openbot-unreachable": "OpenBot did not answer. Make sure OpenBot is running in OpenBot Desktop, then try again.", }; diff --git a/extension/src/shared/generated/recorder.ts b/extension/src/shared/generated/recorder.ts index 125ed97816..1d894bc47c 100644 --- a/extension/src/shared/generated/recorder.ts +++ b/extension/src/shared/generated/recorder.ts @@ -305,6 +305,8 @@ export interface Problem { client?: ProblemClient; /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ minimumVersion?: string; + /** On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. */ + security?: boolean; } /** diff --git a/extension/src/shared/openbot-client.ts b/extension/src/shared/openbot-client.ts index 9c1cd2f54c..a9566cfd4e 100644 --- a/extension/src/shared/openbot-client.ts +++ b/extension/src/shared/openbot-client.ts @@ -6,6 +6,7 @@ import { clientToken, clientUpdateDetail, isVersion, + SECURITY_UPDATE_SENTENCE, } from "@openbot/shared/client-version"; import { RECORDER_SIGNED_OUT, @@ -31,6 +32,14 @@ export class OpenBotError extends Error { get updateRequired(): boolean { return this.body?.code === CLIENT_UPDATE_REQUIRED; } + + /** True when that refusal's minimum was raised because of a security problem in older releases. */ + get securityUpdateRequired(): boolean { + return ( + this.updateRequired && + (this.body as Record | null)?.security === true + ); + } } /** What the person reads when OpenBot serves only newer Recorders and its answer names no release we can use. */ @@ -40,11 +49,13 @@ export const RECORDER_UPDATE_REQUIRED = /** * The sentence for OpenBot refusing this Recorder as too old, or null for any other failure. It is the Recorder's own * sentence, the same one OpenBot words its refusal with (`clientUpdateDetail`), built from the app and release the - * answer names. The text of the answer itself is never shown: any site can answer as OpenBot, and only a known app and a - * release number pass through. + * answer names, or the security sentence when the minimum was raised for a security problem. The text of the answer + * itself is never shown: any site can answer as OpenBot, and only a known app, a release number and the security flag + * pass through. */ export function updateRequiredSentence(error: unknown): string | null { if (!(error instanceof OpenBotError) || !error.updateRequired) return null; + if (error.securityUpdateRequired) return SECURITY_UPDATE_SENTENCE; const body = error.body as Record | null; const named = body?.client; const kind: ClientKind = (CLIENT_KINDS as readonly unknown[]).includes(named) diff --git a/extension/tests/connection.test.ts b/extension/tests/connection.test.ts index 064f27b438..8de027289a 100644 --- a/extension/tests/connection.test.ts +++ b/extension/tests/connection.test.ts @@ -53,6 +53,14 @@ const TOO_OLD = { minimumVersion: "1.2.0", }; +/** The same refusal for a minimum raised because of a security problem (the spec's clientUpdateRequiredSecurity). */ +const INSECURE = { + ...TOO_OLD, + detail: + "This version of OpenBot has a security problem. Update to keep using it.", + security: true, +}; + let server: ReturnType; /** * The web OpenBot most tests connect: an https site, as a hosted OpenBot is. The Recorder takes a connect from OpenBot @@ -113,6 +121,11 @@ async function openbot(request: Request): Promise { await holdIfAsked(url.pathname); if (body.code === "obc_expired") return Response.json({ error: HOSTILE }, { status: 400 }); + if (body.code === "obc_insecure") + return Response.json(INSECURE, { + status: 400, + headers: { "content-type": "application/problem+json" }, + }); if (body.code === "obc_too_old") return Response.json(TOO_OLD, { status: 400, @@ -397,6 +410,23 @@ test("an OpenBot that serves only newer Recorders says so on the Connect page, U expect(await readLocal("connection")).toBeUndefined(); }); +test("an OpenBot that raised the Recorder's minimum for a security problem says so on the Connect page, and stores nothing", async () => { + await connect("obc_insecure"); + expect( + await handleConnectionMessage({ + type: "page.connect.decide", + approve: true, + label: "x", + origin, + }), + ).toEqual({ + ok: false, + error: + "This version of OpenBot has a security problem. Update to keep using it.", + }); + expect(await readLocal("connection")).toBeUndefined(); +}); + test("an approve that cannot reach OpenBot shows a plain sentence, not the browser's error, and stores nothing", async () => { await connect("obc_abc"); const unreachable = spyOn(globalThis, "fetch").mockImplementation( @@ -942,6 +972,18 @@ test("an OpenBot that serves only newer Recorders refuses Desktop's code with it "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", ); expect(await currentConnection()).toBeNull(); + // One raised for a security problem has its own reason, which the popup says as that. + expect( + await connectThroughDesktop({ + askDesktop: async () => ({ openbotUrl: loopback, code: "obc_insecure" }), + openTab, + readPolicy: async () => policy, + }), + ).toEqual({ connected: false, reason: "client-security-update-required" }); + expect(desktopSentence("client-security-update-required")).toBe( + "This version of OpenBot has a security problem. Update to keep using it.", + ); + expect(await currentConnection()).toBeNull(); }); test("a pin elsewhere that lands while Desktop's code is exchanged keeps the connection out and revokes its new token", async () => { diff --git a/extension/tests/recording.test.ts b/extension/tests/recording.test.ts index 54246c9a68..dfe739c25a 100644 --- a/extension/tests/recording.test.ts +++ b/extension/tests/recording.test.ts @@ -3953,14 +3953,14 @@ const CLIENT_UPDATE_REQUIRED_EXAMPLE = { title: "This app is too old for this OpenBot.", status: 400, detail: - "This OpenBot needs OpenBot Desktop 1.0.2 or later. Update OpenBot, then try again.", + "This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again.", code: "CLIENT_UPDATE_REQUIRED", category: "validation", retryable: false, requestId: "req_example", traceId: "trace_example", client: "desktop", - minimumVersion: "1.0.2", + minimumVersion: "1.2.0", }; test("an OpenBot that serves only newer Recorders reaches the popup as its sentence: Update OpenBot, never a plain failure and never text the server made up", async () => { @@ -3986,6 +3986,18 @@ test("an OpenBot that serves only newer Recorders reaches the popup as its sente }, "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", ], + // A minimum raised for a security problem (the spec's clientUpdateRequiredSecurity), said in the Recorder's own + // words for it, whatever detail came with it. + [ + { + ...CLIENT_UPDATE_REQUIRED_EXAMPLE, + detail: "Install the fix from https://evil.example.test.", + client: "recorder", + minimumVersion: "1.2.0", + security: true, + }, + "This version of OpenBot has a security problem. Update to keep using it.", + ], ] as const) { openbot.learningRefusal = { status: 400, body }; const answer = await page({ type: "page.learning" }); diff --git a/mobile/src/api/generated/model/deployment.ts b/mobile/src/api/generated/model/deployment.ts index 30cb696d50..b113d710fb 100644 --- a/mobile/src/api/generated/model/deployment.ts +++ b/mobile/src/api/generated/model/deployment.ts @@ -44,6 +44,8 @@ export interface Deployment { */ api?: string[]; minimumClients?: MinimumClients; + /** The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is. */ + securityMinimumClients?: MinimumClients; /** * The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. * @minimum 1 diff --git a/mobile/src/api/generated/model/problem.ts b/mobile/src/api/generated/model/problem.ts index 6ed25de3a0..c92b9572e8 100644 --- a/mobile/src/api/generated/model/problem.ts +++ b/mobile/src/api/generated/model/problem.ts @@ -36,4 +36,6 @@ export interface Problem { client?: ProblemClient; /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ minimumVersion?: string; + /** On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. */ + security?: boolean; } diff --git a/mobile/src/api/request.ts b/mobile/src/api/request.ts index b769e12820..f8c37d4a1d 100644 --- a/mobile/src/api/request.ts +++ b/mobile/src/api/request.ts @@ -22,12 +22,16 @@ import { import { clientHeaders } from "../release"; import { listOrganizations } from "./generated/organizations/organizations"; -/** A refusal from the server, with its status and the API's problem code when it gave one. */ +/** + * A refusal from the server, with its status and the API's problem code when it gave one, and whether a refusal of + * this app as too old was for a security problem. + */ export class ApiError extends Error { constructor( message: string, readonly status: number, readonly code?: string, + readonly security = false, ) { super(message); this.name = "ApiError"; @@ -104,6 +108,7 @@ function refusal(body: unknown): { said?: string; code?: string; minimumVersion?: string; + security?: boolean; } { if (!body || typeof body !== "object") return {}; const field = (name: string) => { @@ -114,6 +119,7 @@ function refusal(body: unknown): { said: field("detail") ?? field("error"), code: field("code"), minimumVersion: field("minimumVersion"), + security: (body as Record).security === true, }; } @@ -143,11 +149,14 @@ export async function apiRequest( if (response.status === 204) return undefined as T; const body: unknown = await response.json().catch(() => null); if (!response.ok) { - const { said, code, minimumVersion } = refusal(body); + const { said, code, minimumVersion, security } = refusal(body); if (code === CLIENT_UPDATE_REQUIRED) { - const detail = said ?? phoneUpdateDetail(minimumVersion); - reportUpdateRequired(detail); - throw new ApiError(detail, response.status, code); + // A minimum raised for a security problem is always said in the app's own words for it. + const detail = security + ? phoneUpdateDetail(minimumVersion, true) + : (said ?? phoneUpdateDetail(minimumVersion)); + reportUpdateRequired(detail, security); + throw new ApiError(detail, response.status, code, security); } throw new ApiError( said ?? `Request failed (${response.status}).`, diff --git a/mobile/src/client-version.ts b/mobile/src/client-version.ts index d5f29bc03d..f286dcb2e7 100644 --- a/mobile/src/client-version.ts +++ b/mobile/src/client-version.ts @@ -18,6 +18,9 @@ export const API_VERSIONS: readonly string[] = ["v2"]; /** What a person reads when the app is older than the OpenBot it talks to serves. */ export const APP_UPDATE_SENTENCE = "Update OpenBot"; +/** What a person reads in its place when the minimum the app is below was raised for a security problem. */ +export const SECURITY_UPDATE_SENTENCE = + "This version of OpenBot has a security problem. Update to keep using it."; /** The apps that name themselves, as the server's minimums list them. */ type ClientKind = "web" | "desktop" | "mobile" | "recorder"; @@ -77,13 +80,14 @@ function major(version: string): number | undefined { /** * - `ok`: they can. Features the server lacks are hidden by the fields that offer them, never by a version. - * - `app`: the app is too old. "Update OpenBot". + * - `app`: the app is too old. "Update OpenBot". `security` when the minimum it is below was raised for a security + * problem in older releases (the server names the app in `securityMinimumClients` above its version too). * - `server`: the server serves only API versions older than any the app speaks. The phone app adds nothing for it: * whoever runs that OpenBot keeps it and their apps matched, and the screens say what failed, as they always have. */ export type Compatibility = | { fit: "ok" } - | { fit: "app"; minimum?: string } + | { fit: "app"; minimum?: string; security?: true } | { fit: "server" }; /** @@ -91,7 +95,11 @@ export type Compatibility = * publishes no `api` is from a release before this check, and every such release serves v2. */ export function compatibility( - deployment: { api?: unknown; minimumClients?: unknown }, + deployment: { + api?: unknown; + minimumClients?: unknown; + securityMinimumClients?: unknown; + }, client: { kind: ClientKind; version: string; speaks?: readonly string[] }, ): Compatibility { const speaks = client.speaks ?? API_VERSIONS; @@ -109,42 +117,59 @@ export function compatibility( ); return newestServed > newestSpoken ? { fit: "app" } : { fit: "server" }; } - const minimums = - deployment.minimumClients && typeof deployment.minimumClients === "object" - ? (deployment.minimumClients as Record) - : {}; - const minimum = minimums[client.kind]; - if (isVersion(minimum)) { - const order = compareVersions(client.version, minimum); - if (order !== undefined && order < 0) return { fit: "app", minimum }; + const minimum = minimumFor(deployment.minimumClients, client.kind); + if (minimum && below(client.version, minimum)) { + const floor = minimumFor(deployment.securityMinimumClients, client.kind); + return floor && below(client.version, floor) + ? { fit: "app", minimum, security: true } + : { fit: "app", minimum }; } return { fit: "ok" }; } +/** The release `minimums` names for `kind`, when it names one. */ +function minimumFor(minimums: unknown, kind: ClientKind): string | undefined { + if (!minimums || typeof minimums !== "object") return undefined; + const minimum = (minimums as Record)[kind]; + return isVersion(minimum) ? minimum : undefined; +} + +/** Whether `version` is a release before `minimum`. */ +function below(version: string, minimum: string): boolean { + const order = compareVersions(version, minimum); + return order !== undefined && order < 0; +} + /** * What the update screen says under "Update OpenBot": OpenBot's own sentence for refusing this app (as - * shared/client-version.ts `clientUpdateDetail` words it for the phone app), with the release it needs when known. + * shared/client-version.ts `clientUpdateDetail` words it for the phone app), with the release it needs when known, or + * the security sentence when the minimum was raised for a security problem. */ -export function phoneUpdateDetail(minimum?: string): string { +export function phoneUpdateDetail( + minimum?: string, + security?: boolean, +): string { + if (security) return SECURITY_UPDATE_SENTENCE; return isVersion(minimum) ? `This OpenBot needs the OpenBot phone app ${minimum.replace(/^v/, "")} or later. Update OpenBot, then try again.` : "This OpenBot needs a newer OpenBot phone app. Update OpenBot, then try again."; } -/** What the root layout shows: the app, or "Update OpenBot". */ -export type VersionVerdict = { kind: "ok" } | { kind: "app"; detail: string }; +/** What the root layout shows: the app, or "Update OpenBot" (`security` when it is for a security problem). */ +export type VersionVerdict = + | { kind: "ok" } + | { kind: "app"; detail: string; security?: true }; /** * Anything that learns OpenBot refused this app as too old (a request's CLIENT_UPDATE_REQUIRED) says so here, and the * root layout, which listens, shows the update screen in place of whatever was open. */ -const listeners = new Set<(detail: string) => void>(); -export function reportUpdateRequired(detail: string): void { - for (const listener of listeners) listener(detail); +type UpdateRequired = (detail: string, security: boolean) => void; +const listeners = new Set(); +export function reportUpdateRequired(detail: string, security = false): void { + for (const listener of listeners) listener(detail, security); } -export function onUpdateRequired( - listener: (detail: string) => void, -): () => void { +export function onUpdateRequired(listener: UpdateRequired): () => void { listeners.add(listener); return () => { listeners.delete(listener); diff --git a/mobile/src/version-check.ts b/mobile/src/version-check.ts index cf8baf289a..06a273f20b 100644 --- a/mobile/src/version-check.ts +++ b/mobile/src/version-check.ts @@ -21,7 +21,9 @@ export async function checkVersion(): Promise { deployment = await getDeployment(DEPLOYMENT_ORGANIZATION_ID); } catch (error) { if (error instanceof ApiError && error.code === CLIENT_UPDATE_REQUIRED) - return { kind: "app", detail: error.message }; + return error.security + ? { kind: "app", detail: error.message, security: true } + : { kind: "app", detail: error.message }; return { kind: "ok" }; } // A build that names no release can still tell an API it doesn't speak; it is never refused for a version. @@ -30,6 +32,12 @@ export async function checkVersion(): Promise { version: RELEASE ?? "0.0.0", }); if (fit.fit === "app") - return { kind: "app", detail: phoneUpdateDetail(fit.minimum) }; + return fit.security + ? { + kind: "app", + detail: phoneUpdateDetail(fit.minimum, true), + security: true, + } + : { kind: "app", detail: phoneUpdateDetail(fit.minimum) }; return { kind: "ok" }; } diff --git a/mobile/src/version-gate.tsx b/mobile/src/version-gate.tsx index 483c66c6f2..7c10181676 100644 --- a/mobile/src/version-gate.tsx +++ b/mobile/src/version-gate.tsx @@ -1,6 +1,7 @@ /** - * The screen the root layout shows in place of the app when the app is too old for its OpenBot ("Update OpenBot"). It - * covers everything, headers included, so nothing behind it is shown failing. + * The screen the root layout shows in place of the app when the app is too old for its OpenBot ("Update OpenBot", or + * the security sentence when the minimum was raised for a security problem). It covers everything, headers included, + * so nothing behind it is shown failing. */ import { useCallback, useEffect, useState } from "react"; import { @@ -15,6 +16,7 @@ import { serverUrl } from "./auth"; import { APP_UPDATE_SENTENCE, onUpdateRequired, + SECURITY_UPDATE_SENTENCE, type VersionVerdict, } from "./client-version"; import { heading, muted } from "./ui"; @@ -42,8 +44,12 @@ export function useVersionVerdict() { const subscription = AppState.addEventListener("change", (state) => { if (state === "active") void check(); }); - const stop = onUpdateRequired((detail) => - setVerdict({ kind: "app", detail }), + const stop = onUpdateRequired((detail, security) => + setVerdict( + security + ? { kind: "app", detail, security: true } + : { kind: "app", detail }, + ), ); return () => { subscription.remove(); @@ -67,10 +73,19 @@ export function VersionGate({ ) : ( - - {APP_UPDATE_SENTENCE} - - {verdict.detail} + {verdict.security ? ( + // The security sentence is the heading, and says what to do: nothing repeats it below. + + {SECURITY_UPDATE_SENTENCE} + + ) : ( + <> + + {APP_UPDATE_SENTENCE} + + {verdict.detail} + + )} {serverUrl}
)} - {freshInstall || ( + {freshInstall || appBehind || ( } {pauseCard} {updatingLine} - {displayedFailure && !roomShort && ( - - )} + {displayedFailure && + !roomShort && + (appBehind ? ( + + ) : ( + + ))} {updatingSelf && } {/* While a local step runs, its Cancel is the only control. */} {!localStarting && !installingAfresh && ( @@ -1634,8 +1650,9 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { > Change AI connection - {/* Room is what is short: a repair installs again, and needs room too. */} - {displayedFailure && !roomShort && ( + {/* Room is what is short: a repair installs again, and needs room too. And a + release that needs a newer app is not broken: a repair lays the same one out. */} + {displayedFailure && !roomShort && !appBehind && (