diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json
index aeeba8785e..57515ac4a6 100644
--- a/.github/ci-budgets.json
+++ b/.github/ci-budgets.json
@@ -7,6 +7,7 @@
"API spec": 3,
"native types": 3,
"app (real browser)": 8,
+ "app (real browser, Chromium) (shard N of N)": 15,
"app (real browser, WebKit) (shard N of N)": 15,
"app (real browser, desktop setup window)": 12,
"tests (shard N of N)": 7,
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index be4195a368..ff60a19f54 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,6 +2,8 @@ name: CI
on:
pull_request:
+ # Adding full-ci must start the full replacement run on the same commit.
+ types: [opened, synchronize, reopened, labeled]
push:
branches: [main]
# The merge queue: main's merge queue builds each pull request on top of main and the pull
@@ -18,7 +20,7 @@ on:
permissions:
contents: read
-# The newest push on a pull request wins. Every commit on main keeps its own run, for the badge and
+# The newest run on a pull request wins. Every commit on main keeps its own run, for the badge and
# for the release: publishing a release relies on main's CI having passed on a commit whose tree
# differs from the release's only in what it runs again (scripts/release-ci-gate.ts). In one group,
# a push landing while another commit's run was in progress replaced the pending run of the commit
@@ -34,12 +36,15 @@ permissions:
# GitHub drops from the group's one pending slot is re-run later by Contributor CI
# (scripts/contributor-ci.ts), which also pauses fork runs while CopilotKit's are waiting.
#
-# Only a pull request's own push cancels. The release's call of these checks runs with the release
-# push's context, a push to main or to a release branch, and is never cancelled by the next one
-# (scripts/workflow-concurrency.test.ts).
+# A pull request's newer push, or the `full-ci` label, starts a replacement run. Any other label waits
+# for the run in progress instead of cancelling it: once that run is done, the waiting run finds every
+# check it passed on the same commit, skips them, and takes a minute. A label run cannot simply skip
+# everything up front: a skipped `verify` counts as passing, and could turn a failing pull request
+# green. The release's call runs with the release push's context, a push to main or to a release
+# branch, and is never cancelled by the next one (scripts/workflow-concurrency.test.ts).
concurrency:
group: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && format('ci-{0}-forks', github.workflow) || format('ci-{0}-{1}', github.workflow, github.ref == 'refs/heads/main' && github.sha || github.ref) }}
- cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') }}
# Runners. The checks run on the 16-core larger runners (org runner group openbot-larger, billed per
# minute) for main, releases and pull requests from this repository: the standard runners are shared
@@ -51,11 +56,13 @@ concurrency:
jobs:
# What this push has to run (scripts/ci-changes.ts). On a pull request, a job whose inputs are
# unchanged since a commit where it passed is skipped, and `verify` reads the skip as a pass: test
- # files alone run just those tests, docs alone run only the tests that name them, and a release PR
+ # files alone run just those tests (removing one reruns the suite's count floor), docs alone run
+ # only the tests that name them, and a release PR
# of only the release files runs the checks publishing re-runs on it. main's run of a commit the
# merge queue merged skips the checks the queue's run already passed on that same commit, and runs
- # only `component dockerfile` and any job whose cache key the push changed, which write the caches
- # pull requests read. A merge group is decided like a pull request, from main's history and the
+ # only `component dockerfile`, any job whose cache key the push changed, and startup when the queue
+ # ran Windows but omitted macOS. The first two write caches pull requests read. A merge group is
+ # decided like a pull request, from main's history and the
# queued pull request's: a job runs unless nothing it reads changed since it passed on one of them.
# A push to main the queue did not pass, the release's own call of these checks and a pull request
# labelled `full-ci` (in its own runs and in the queue) run everything. CHANGELOG.md is never a
@@ -100,6 +107,19 @@ jobs:
# Strings, since 0 is falsy and `&& 0 || 1` would always give 1.
fetch-depth: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '0' || '1' }}
filter: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && 'blob:none' || '' }}
+ # The run API names the PR head, while these jobs test its merge with main. Keep the actual
+ # checkout commit so a later merge group compares against the tree the jobs really tested.
+ - name: Record the tested checkout
+ if: github.event_name == 'pull_request'
+ run: git rev-parse HEAD > "$RUNNER_TEMP/ci-tested-tree.txt"
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: github.event_name == 'pull_request'
+ with:
+ # Re-running only a failed check retains changes' original proof artifact.
+ name: ci-tested-tree-${{ github.run_id }}
+ path: ${{ runner.temp }}/ci-tested-tree.txt
+ retention-days: 14
+ overwrite: true
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.4.3
@@ -141,6 +161,11 @@ jobs:
- run: bun run format:check
- run: bun run lint
- run: bun run typecheck
+ # Desktop is not a root workspace; its test files still belong to its TypeScript project.
+ - run: bun install --frozen-lockfile
+ working-directory: desktop
+ - run: bun run typecheck
+ working-directory: desktop
- name: Desktop version tracks the release version
run: bun desktop/scripts/desktop-version.ts check
# What each recorded OpenBot Desktop launch hands Compose, read with this tree's
@@ -635,8 +660,12 @@ jobs:
# than the error screen, the diagram drawn in its default colours. In the image, as above:
# WebKit's system packages are about 94 MB, which took nine minutes from the mirror on a slow day.
#
+ # Each shard runs twice, once per engine: OPENBOT_APP_ENGINES names one, and every file opens only
+ # the engines it names (app/tests/browser-engines.ts). A file that only ever runs in Chromium skips
+ # itself in the WebKit leg, so no file runs the same browser twice (scripts/ci-changes.test.ts).
+ #
# The files run side by side, like the Chromium list's, but eight at a time rather than a worker
- # per core: each file opens Chromium and WebKit, and sixteen workers' 32 browsers on 16 cores
+ # per core: each file used to open Chromium and WebKit, and sixteen workers' 32 browsers on 16 cores
# starved the tests that wait on a clock (a hold's Retry-After, a menu's load). This job began
# with one file and ran its list one file after another; by 24 November it held 30 files in two
# engines each, took 35 minutes and was the whole length of a run. Add a new file to this one
@@ -653,15 +682,21 @@ jobs:
#
# In shards, one runner each, as the suite is: one job took 16 to 17 minutes before the browser tests
# no job had ever named were added, and every file is still named here once. `bun test --shard`
- # deals the sorted list out in turn. A run is as long as its slowest shard, and a shard as long as
- # its slowest file: artifacts-screens, about 11 minutes.
+ # cuts the list by each file's recorded duration in that engine (scripts/browser-timings/), so the
+ # shards take about as long as each other, and each worker starts its slowest file first. Each
+ # shard writes what its files took over the record, kept as an artifact for refreshing it
+ # (scripts/browser-timings.ts). A shard is still as long as its slowest file, so no file should
+ # take more than a few minutes in one engine: artifacts-screens took 11 and set every run's length
+ # until its layout cases were dealt over four files of their own.
app-browser-webkit:
- name: app (real browser, WebKit) (shard ${{ matrix.shard }} of ${{ strategy.job-total }})
+ name: app (real browser, ${{ matrix.engine }}) (shard ${{ matrix.shard }} of 3)
needs: changes
strategy:
- # Every shard runs to the end, so one red run names every failing test, as the suite's do.
+ # Each engine and shard has its own runner and result, so a failed leg can be re-run on its
+ # own. A failure still stops the whole run at once (.github/actions/stop-on-failure).
fail-fast: false
matrix:
+ engine: [Chromium, WebKit]
shard: [1, 2, 3]
# On a pull request, only when the app, what it imports or its tests change (scripts/ci-changes.ts,
# app_browser_webkit). A merge group and main run it every time.
@@ -677,7 +712,9 @@ jobs:
PLAYWRIGHT_IMAGE: mcr.microsoft.com/playwright:v1.62.1-noble@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e
TEST_WORKERS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '2' || '8' }}
TEST_TIMEOUT_MS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '15000' || '5000' }}
- TEST_SHARD: ${{ matrix.shard }}/${{ strategy.job-total }}
+ # Three shards per engine; strategy.job-total counts all six engine/shard jobs.
+ TEST_SHARD: ${{ matrix.shard }}/3
+ BROWSER_ENGINE: ${{ matrix.engine == 'WebKit' && 'webkit' || 'chromium' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -714,6 +751,10 @@ jobs:
app/tests/artifact-sign-in-refusal-browser.test.tsx
app/tests/artifact-tool-cards-browser.test.tsx
app/tests/artifacts-kit.test.ts
+ app/tests/artifacts-screens-layout-1.test.tsx
+ app/tests/artifacts-screens-layout-2.test.tsx
+ app/tests/artifacts-screens-layout-3.test.tsx
+ app/tests/artifacts-screens-layout-4.test.tsx
app/tests/artifacts-screens.test.tsx
app/tests/board-row-layout.test.tsx
app/tests/boot-screen.test.ts
@@ -832,12 +873,21 @@ jobs:
docker run --rm --ipc=host \
--volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \
--volume "$(command -v bun):/usr/local/bin/bun:ro" \
- --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \
+ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES="$BROWSER_ENGINE" \
"$PLAYWRIGHT_IMAGE" \
- bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" --shard="$TEST_SHARD" "${files[@]}"
+ bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" --shard="$TEST_SHARD" --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings "${files[@]}"
+ # This shard's own durations, which the run wrote over the engine's record: download every
+ # shard's and merge them to refresh it (scripts/browser-timings.ts).
+ - if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: browser-timings-${{ env.BROWSER_ENGINE }}-${{ matrix.shard }}
+ path: scripts/browser-timings/${{ env.BROWSER_ENGINE }}.json
+ retention-days: 14
+ if-no-files-found: ignore
# Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard.
# Only that test: the rest of the file runs in Chromium in the job above. Once, on the first shard.
- - if: matrix.shard == 1
+ - if: matrix.engine == 'WebKit' && matrix.shard == 1
run: |
docker run --rm --ipc=host \
--volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \
@@ -851,8 +901,9 @@ jobs:
# The desktop setup window's, for the same reason as the list above: the AI step's form holding
# still while the install behind it comes and goes. It bundles the window from the desktop's own
- # dependencies. One file, so it is its own job rather than one of the list's workers. In the
- # image, as above.
+ # dependencies, so it is its own job rather than one of the list's workers. In the image, as
+ # above. Its describes were one file of ten minutes, the longest job of a run; they are three
+ # files now (setupLayout.browser.harness.ts holds what they share), run side by side.
app-browser-desktop:
name: app (real browser, desktop setup window)
needs: changes
@@ -875,13 +926,20 @@ jobs:
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: desktop
+ # A list, as in the jobs above, so scripts/ci-changes.ts can tell this job covers the file and a
+ # change to it does not run it a second time in `tests (changed files)`. Paths from desktop/.
- run: |
+ files=(
+ src/setupLayout.approved.browser.test.ts
+ src/setupLayout.browser.test.ts
+ src/setupLayout.moveToCloud.browser.test.ts
+ )
docker run --rm --ipc=host \
--volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE/desktop" \
--volume "$(command -v bun):/usr/local/bin/bun:ro" \
--env OPENBOT_APP_BROWSER=1 \
"$PLAYWRIGHT_IMAGE" \
- bun test src/setupLayout.browser.test.ts
+ bun test --parallel "${files[@]}"
# Connect your AI's key field and tab row, in WebKit, the engine the Mac window draws with.
# Only those tests: the rest of the file runs in Chromium in the step above.
- run: |
@@ -1034,8 +1092,12 @@ jobs:
if: needs.changes.outputs.browser_tests != '[]' || needs.changes.outputs.desktop_browser_tests != '[]'
run: bunx playwright-core install --with-deps --no-shell chromium
- name: Install WebKit
- if: needs.changes.outputs.webkit_tests != '[]'
+ if: needs.changes.outputs.webkit_tests != '[]' || contains(fromJSON(needs.changes.outputs.desktop_browser_tests), 'desktop/src/setupLayout.browser.test.ts')
run: bunx playwright-core install --with-deps webkit
+ # The print-page test serves the shipped HTML, styles and assets from app/dist.
+ - name: Build the print page and app assets
+ if: contains(fromJSON(needs.changes.outputs.browser_tests), 'app/tests/artifact-print-browser.test.ts')
+ run: bun run --cwd app build
- name: Run the changed tests
env:
TESTS: ${{ needs.changes.outputs.tests }}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f24ee67563..1c6f5335c5 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -47,8 +47,9 @@ request merges, by editing its description before the release is prepared.
- **A new push starts a new run.** If you push again while a run is waiting, the newer commit is
the one that gets checked.
- **It merges through a merge queue.** Once it is approved and CI passes, a maintainer adds it to
- `main`'s merge queue, which runs CI once more on top of `main` and the pull requests queued ahead
- of it, and merges it when that passes. You never need to update your branch from `main` for it
+ `main`'s merge queue, which checks it once more on top of `main` and the pull requests queued
+ ahead of it, and merges it when that passes. A check that already passed on the tree it would
+ test is not run again; the rest run on only what changed since. You never need to update your branch from `main` for it
to merge.
Locally, `bun install` and then `bun test` runs the suite, `bun run lint` and `bun run format:check`
diff --git a/app/tests/artifact-bridge-browser.test.ts b/app/tests/artifact-bridge-browser.test.ts
index 38a00b90ee..40dd88aedb 100644
--- a/app/tests/artifact-bridge-browser.test.ts
+++ b/app/tests/artifact-bridge-browser.test.ts
@@ -2,6 +2,7 @@ import { afterAll, describe, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import type { Browser, Frame, Page } from "playwright-core";
+import { ownBrowsersAsked } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -20,7 +21,8 @@ import { test } from "./renderer-crash";
* Why it is worth a browser: an opaque origin, the sandbox, CSP and MessageChannel transfer are the
* browser's, and a test without them proves nothing about them.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/artifact-collab-browser.test.tsx b/app/tests/artifact-collab-browser.test.tsx
index 93d3926e03..2e1f65f4be 100644
--- a/app/tests/artifact-collab-browser.test.tsx
+++ b/app/tests/artifact-collab-browser.test.tsx
@@ -13,6 +13,7 @@ import {
fakeArtifactServer,
type Person,
} from "./artifact-pages-api";
+import { ownBrowsersAsked } from "./browser-engines";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -31,7 +32,8 @@ import { test } from "./renderer-crash";
*
* With OPENBOT_APP_SHOTS=
each screen is saved in light and dark, at 400 and 1280 wide.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/artifact-error-notice-layout.test.tsx b/app/tests/artifact-error-notice-layout.test.tsx
index b943619362..63049fe1d4 100644
--- a/app/tests/artifact-error-notice-layout.test.tsx
+++ b/app/tests/artifact-error-notice-layout.test.tsx
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { ownBrowsersAsked } from "./browser-engines";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -18,7 +19,8 @@ import { test } from "./renderer-crash";
*
* With OPENBOT_APP_SHOTS= it saves each as artifact-error-notice--.png.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/artifact-events-socket.test.ts b/app/tests/artifact-events-socket.test.ts
index 84e9493454..c063a15ccd 100644
--- a/app/tests/artifact-events-socket.test.ts
+++ b/app/tests/artifact-events-socket.test.ts
@@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect } from "bun:test";
import { join } from "node:path";
import type { Server, ServerWebSocket } from "bun";
import type { Browser } from "playwright-core";
+import { ownBrowsersAsked } from "./browser-engines";
import { marksPlugin } from "./marks-plugin";
import { test } from "./renderer-crash";
@@ -19,7 +20,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 bun test app/tests/artifact-events-socket.test.ts
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const EVENTS = /\/api\/v2\/organizations\/[^/]+\/artifacts\/[^/]+\/events$/;
type Behaviour = "not-here" | "drops";
diff --git a/app/tests/artifact-kinds-browser.test.tsx b/app/tests/artifact-kinds-browser.test.tsx
index b409294b66..e09153a2de 100644
--- a/app/tests/artifact-kinds-browser.test.tsx
+++ b/app/tests/artifact-kinds-browser.test.tsx
@@ -9,6 +9,7 @@ import {
import { basename, dirname, join } from "node:path";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { ownBrowsersAsked } from "./browser-engines";
import { marksPlugin } from "./marks-plugin";
import { test } from "./renderer-crash";
@@ -21,7 +22,8 @@ import { test } from "./renderer-crash";
* With OPENBOT_APP_SHOTS= every page is saved as kinds---.png, beside the
* app's own gallery cards (kinds-reference-…), to look at side by side.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/artifacts-kit.test.ts b/app/tests/artifacts-kit.test.ts
index 19b6b19322..dbe9754bd9 100644
--- a/app/tests/artifacts-kit.test.ts
+++ b/app/tests/artifacts-kit.test.ts
@@ -15,6 +15,7 @@ import { build } from "esbuild";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { scheme, TOKENS } from "../../tokens/src/scheme";
+import { ownBrowsersAsked } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -35,7 +36,8 @@ const APP = join(import.meta.dir, "..");
const ROOT = join(APP, "..");
const SCRIPT = join(APP, "scripts", "build-artifacts-kit.ts");
const RUNTIME_SOURCE = join(APP, "src/lib/artifacts/bridge/page-runtime.ts");
-const browserAsked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens Chromium itself, so it runs where Chromium is selected (browser-engines.ts).
+const browserAsked = ownBrowsersAsked();
const shots = process.env.OPENBOT_SHOTS;
let scratch: string;
diff --git a/app/tests/artifacts-screens-layout-1.test.tsx b/app/tests/artifacts-screens-layout-1.test.tsx
new file mode 100644
index 0000000000..7d969614fa
--- /dev/null
+++ b/app/tests/artifacts-screens-layout-1.test.tsx
@@ -0,0 +1,25 @@
+import { describe } from "bun:test";
+import {
+ holdsItsLayout,
+ layoutPart,
+ withArtifactsBrowser,
+} from "./artifacts-screens.harness";
+import { ownBrowsersAsked } from "./browser-engines";
+import { test } from "./renderer-crash";
+
+/**
+ * The artifact screens hold their layout, part 1 of the files the cases are dealt over
+ * (artifacts-screens.harness.ts): each screen in light and dark, wide, narrow and on a phone, with
+ * nothing scrolling sideways, no control cut off, a dialog on the screen and nothing the server
+ * refused. The flows of the same screens are in artifacts-screens.test.tsx.
+ *
+ * OPENBOT_APP_BROWSER=1 bun test app/tests/artifacts-screens-layout-1.test.tsx
+ */
+// Opens its own browser, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
+withArtifactsBrowser(asked);
+
+describe.skipIf(!asked)("the artifact screens hold their layout", () => {
+ for (const layout of layoutPart(1))
+ test(layout.name, () => holdsItsLayout(layout), 60_000);
+});
diff --git a/app/tests/artifacts-screens-layout-2.test.tsx b/app/tests/artifacts-screens-layout-2.test.tsx
new file mode 100644
index 0000000000..54a3ce5bcb
--- /dev/null
+++ b/app/tests/artifacts-screens-layout-2.test.tsx
@@ -0,0 +1,25 @@
+import { describe } from "bun:test";
+import {
+ holdsItsLayout,
+ layoutPart,
+ withArtifactsBrowser,
+} from "./artifacts-screens.harness";
+import { ownBrowsersAsked } from "./browser-engines";
+import { test } from "./renderer-crash";
+
+/**
+ * The artifact screens hold their layout, part 2 of the files the cases are dealt over
+ * (artifacts-screens.harness.ts): each screen in light and dark, wide, narrow and on a phone, with
+ * nothing scrolling sideways, no control cut off, a dialog on the screen and nothing the server
+ * refused. The flows of the same screens are in artifacts-screens.test.tsx.
+ *
+ * OPENBOT_APP_BROWSER=1 bun test app/tests/artifacts-screens-layout-2.test.tsx
+ */
+// Opens its own browser, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
+withArtifactsBrowser(asked);
+
+describe.skipIf(!asked)("the artifact screens hold their layout", () => {
+ for (const layout of layoutPart(2))
+ test(layout.name, () => holdsItsLayout(layout), 60_000);
+});
diff --git a/app/tests/artifacts-screens-layout-3.test.tsx b/app/tests/artifacts-screens-layout-3.test.tsx
new file mode 100644
index 0000000000..c682448e12
--- /dev/null
+++ b/app/tests/artifacts-screens-layout-3.test.tsx
@@ -0,0 +1,25 @@
+import { describe } from "bun:test";
+import {
+ holdsItsLayout,
+ layoutPart,
+ withArtifactsBrowser,
+} from "./artifacts-screens.harness";
+import { ownBrowsersAsked } from "./browser-engines";
+import { test } from "./renderer-crash";
+
+/**
+ * The artifact screens hold their layout, part 3 of the files the cases are dealt over
+ * (artifacts-screens.harness.ts): each screen in light and dark, wide, narrow and on a phone, with
+ * nothing scrolling sideways, no control cut off, a dialog on the screen and nothing the server
+ * refused. The flows of the same screens are in artifacts-screens.test.tsx.
+ *
+ * OPENBOT_APP_BROWSER=1 bun test app/tests/artifacts-screens-layout-3.test.tsx
+ */
+// Opens its own browser, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
+withArtifactsBrowser(asked);
+
+describe.skipIf(!asked)("the artifact screens hold their layout", () => {
+ for (const layout of layoutPart(3))
+ test(layout.name, () => holdsItsLayout(layout), 60_000);
+});
diff --git a/app/tests/artifacts-screens-layout-4.test.tsx b/app/tests/artifacts-screens-layout-4.test.tsx
new file mode 100644
index 0000000000..7fcb5483dc
--- /dev/null
+++ b/app/tests/artifacts-screens-layout-4.test.tsx
@@ -0,0 +1,25 @@
+import { describe } from "bun:test";
+import {
+ holdsItsLayout,
+ layoutPart,
+ withArtifactsBrowser,
+} from "./artifacts-screens.harness";
+import { ownBrowsersAsked } from "./browser-engines";
+import { test } from "./renderer-crash";
+
+/**
+ * The artifact screens hold their layout, part 4 of the files the cases are dealt over
+ * (artifacts-screens.harness.ts): each screen in light and dark, wide, narrow and on a phone, with
+ * nothing scrolling sideways, no control cut off, a dialog on the screen and nothing the server
+ * refused. The flows of the same screens are in artifacts-screens.test.tsx.
+ *
+ * OPENBOT_APP_BROWSER=1 bun test app/tests/artifacts-screens-layout-4.test.tsx
+ */
+// Opens its own browser, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
+withArtifactsBrowser(asked);
+
+describe.skipIf(!asked)("the artifact screens hold their layout", () => {
+ for (const layout of layoutPart(4))
+ test(layout.name, () => holdsItsLayout(layout), 60_000);
+});
diff --git a/app/tests/artifacts-screens.harness.ts b/app/tests/artifacts-screens.harness.ts
new file mode 100644
index 0000000000..6938205df2
--- /dev/null
+++ b/app/tests/artifacts-screens.harness.ts
@@ -0,0 +1,768 @@
+import { afterAll, beforeAll, expect } from "bun:test";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import type {
+ Browser,
+ BrowserType,
+ Page,
+ WebSocketRoute,
+} from "playwright-core";
+import { compile } from "tailwindcss";
+import {
+ ARTIFACTS_HOST,
+ DASHBOARD_ID,
+ PAGE_ID,
+ PLAN_ID,
+ SHARED_ID,
+ THUMBNAIL_DARK_SHA,
+ THUMBNAIL_LIGHT_SHA,
+} from "./artifacts-api";
+import { marksPlugin } from "./marks-plugin";
+import { still } from "./page-still";
+
+/**
+ * What the artifact screens' browser test files share (artifacts-screens.test.tsx, and the layout
+ * cases in artifacts-screens-layout-1.test.tsx and the files numbered after it): the browser and the server's files, a page of the
+ * app opened and styled, what a person would see wrong, and the screens whose layout is held.
+ *
+ * The layout cases are dealt out over several files so the browser jobs run them side by side: in
+ * one file they took about nine of its twelve minutes, and the file set the length of a shard.
+ * Each file calls `withArtifactsBrowser` for its own browser.
+ */
+export const shots = process.env.OPENBOT_APP_SHOTS;
+
+export const APP = join(import.meta.dir, "..");
+export const ORIGIN = "http://openbot.test";
+
+export const WIDE = { width: 1440, height: 900 };
+export const NARROW = { width: 700, height: 900 };
+export const PHONE = { width: 390, height: 844 };
+export const THEMES = ["light", "dark"] as const;
+export type Theme = (typeof THEMES)[number];
+export type Window = { width: number; height: number };
+
+export async function bundle(entry: string): Promise {
+ const built = await Bun.build({
+ entrypoints: [join(import.meta.dir, entry)],
+ target: "browser",
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
+ // An optional map renderer a library loads only when asked to draw a map; not installed.
+ external: ["maplibre-gl"],
+ plugins: [marksPlugin],
+ });
+ if (!built.success) throw new AggregateError(built.logs, "bundle failed");
+ const script = built.outputs.find((output) => output.kind === "entry-point");
+ if (!script) throw new Error("bundle has no entry point");
+ return script.text();
+}
+
+/** The directory of an installed package, from the app or the repository root. */
+export function packageDir(name: string): string {
+ const dir = [
+ join(APP, "node_modules", name),
+ join(APP, "..", "node_modules", name),
+ ].find(existsSync);
+ if (!dir) throw new Error(`no package ${name}`);
+ return dir;
+}
+
+/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */
+export function packageStylesheet(id: string): string {
+ const parts = id.split("/");
+ const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
+ const dir = packageDir(name as string);
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
+ const subpath = `.${id.slice((name as string).length)}`;
+ const entry = pkg.exports?.[subpath];
+ const file =
+ typeof entry === "string"
+ ? entry
+ : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css");
+ return join(dir, file);
+}
+
+/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */
+export async function stylesheet(classes: string[]): Promise {
+ const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP));
+ const entry = join(APP, "src", "styles.css");
+ const compiler = await compile(readFileSync(entry, "utf8"), {
+ base: dirname(entry),
+ loadStylesheet: async (id, base) => {
+ const path =
+ id === "tailwindcss"
+ ? join(tailwind, "index.css")
+ : id.startsWith(".")
+ ? join(base, id)
+ : packageStylesheet(id);
+ return { path, base: dirname(path), content: readFileSync(path, "utf8") };
+ },
+ });
+ return compiler.build(classes);
+}
+
+export let browser: Browser;
+export const scripts: Record = {};
+/** A page version's still pictures, by SHA-256, as the server draws them: real JPEGs of the page. */
+export const pictures = new Map();
+
+/** An exported file's bytes, as the server streams them. */
+export const EXPORTED_PDF = "%PDF-1.7 Q3 launch plan";
+
+/**
+ * The server's file downloads, on a real socket. A download leaves the page's own network: the
+ * browser fetches it itself, past `page.route`, so a file fulfilled there never arrived (Chromium
+ * called the download cancelled, WebKit never started it) while the test still read the name off
+ * the link. The browser reaches the app's address through this, as a proxy, and it answers an
+ * export's file as `downloadArtifactExport` does.
+ */
+export let files: ReturnType | undefined;
+
+export function withArtifactsBrowser(asked: boolean) {
+ beforeAll(async () => {
+ if (!asked) return;
+ scripts.app = await bundle("artifacts-app.fixture.tsx");
+ scripts.conversation = await bundle("artifacts-conversation.fixture.tsx");
+ files = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch: (request) =>
+ /\/exports\/[^/]+\/file$/.test(new URL(request.url).pathname)
+ ? new Response(EXPORTED_PDF, {
+ headers: {
+ "content-type": "application/pdf",
+ "content-disposition":
+ 'attachment; filename="Q3 launch plan.pdf"',
+ "cache-control": "private, no-store",
+ "x-content-type-options": "nosniff",
+ },
+ })
+ : new Response("", { status: 404 }),
+ });
+ const proxy = { server: `http://127.0.0.1:${files.port}` };
+ const playwright = await import("playwright-core");
+ const chromium: BrowserType = playwright.chromium;
+ // OPENBOT_APP_ENGINE=webkit: Safari's engine. The CI job installs full Chromium without the
+ // headless shell.
+ browser =
+ process.env.OPENBOT_APP_ENGINE === "webkit"
+ ? await playwright.webkit.launch({ proxy })
+ : await chromium.launch({ channel: "chromium", proxy });
+ // The page in light and dark, drawn at 1280 by 720 as the server's renderer draws it.
+ for (const [sha, html] of [
+ [THUMBNAIL_LIGHT_SHA, PAGE_CONTENT],
+ [THUMBNAIL_DARK_SHA, PAGE_CONTENT_DARK],
+ ] as const) {
+ const drawing = await browser.newPage({
+ viewport: { width: 1280, height: 720 },
+ });
+ await drawing.setContent(html);
+ pictures.set(
+ sha,
+ await drawing.screenshot({ type: "jpeg", quality: 80 }),
+ );
+ await drawing.close();
+ }
+ }, 180_000);
+
+ afterAll(async () => {
+ await browser?.close();
+ files?.stop(true);
+ });
+}
+
+/** What a sandboxed page artifact's content looks like when the artifacts host serves it. */
+export const PAGE_CONTENT = `
Pricing
Seats × price, as a page a Bot built.
`;
+/** The same page as the bridge draws it when the app is dark: the server's dark picture of it. */
+export const PAGE_CONTENT_DARK = PAGE_CONTENT.replace(
+ "background:#fff;color:#111",
+ "background:#0e131b;color:#f2f4f7",
+);
+
+export type Opened = {
+ page: Page;
+ /** The artifact sockets the page opened, by artifact id. */
+ sockets: Map;
+};
+
+/**
+ * One page of the app: the conversation stand-in or the real app (`entry`), at `path` on the app's
+ * address or on the artifacts host (`host`), in a theme and a window, with the server's setup in
+ * `query`.
+ */
+export async function open(options: {
+ entry: "app" | "conversation";
+ path: string;
+ theme: Theme;
+ window: Window;
+ host?: boolean;
+ /**
+ * The artifacts host's mark without the organization, as the server serves it to somebody who
+ * may not see the artifact yet.
+ */
+ unnamed?: boolean;
+ /** Inside the OpenBot Desktop window (`installDesktopWindow`). */
+ desktop?: boolean;
+ ready: (page: Page) => Promise;
+}): Promise {
+ const page = await browser.newPage({
+ viewport: options.window,
+ colorScheme: options.theme,
+ reducedMotion: "reduce",
+ acceptDownloads: true,
+ });
+ page.on("pageerror", (error) => console.error(error));
+ if (options.desktop) await page.addInitScript(installDesktopWindow);
+ const inter = join(packageDir("@fontsource-variable/figtree"), "files");
+ const script = scripts[options.entry] as string;
+ const html = (meta: string) =>
+ `${meta}`;
+ const serve =
+ (meta: string) => async (route: import("playwright-core").Route) => {
+ const url = new URL(route.request().url());
+ const path = url.pathname;
+ if (path === "/screens.js")
+ return route.fulfill({ contentType: "text/javascript", body: script });
+ // OpenBot's mark, which the bundle names by a file of its own.
+ if (/openbot-logo.*\.png$/.test(path))
+ return route.fulfill({
+ path: join(APP, "src", "assets", "openbot-logo.png"),
+ });
+ const font = join(inter, path.split("/").pop() ?? "");
+ if (path.startsWith("/files/") && existsSync(font))
+ return route.fulfill({ path: font });
+ // A file the Download menu hands the browser to save: the export's own address, which
+ // the browser fetches itself, from the real server (`files`).
+ if (/\/exports\/[^/]+\/file$/.test(path)) return route.continue();
+ // A page version's still picture, through the artifact's asset route.
+ const asset = /\/artifacts\/[^/]+\/assets\/([0-9a-f]{64})$/.exec(path);
+ if (asset) {
+ const picture = pictures.get(asset[1] as string);
+ return picture
+ ? route.fulfill({
+ status: 200,
+ body: picture,
+ headers: { "content-type": "image/jpeg" },
+ })
+ : route.fulfill({ status: 404, body: "" });
+ }
+ // A page artifact's content, as the artifacts host serves it: sandboxed, whatever frames it.
+ if (/\/content$/.test(path))
+ return route.fulfill({
+ status: 200,
+ body: PAGE_CONTENT,
+ headers: {
+ "content-type": "text/html",
+ "content-security-policy":
+ "sandbox allow-scripts; default-src 'none'; style-src 'unsafe-inline'",
+ },
+ });
+ return route.fulfill({ contentType: "text/html", body: html(meta) });
+ };
+ await page.route(`${ORIGIN}/**`, serve(""));
+ await page.route(
+ `${ARTIFACTS_HOST}/**`,
+ serve(
+ options.unnamed
+ ? ''
+ : '',
+ ),
+ );
+ const sockets = new Map();
+ await page.routeWebSocket(/.*/, (socket) => {
+ const found = /\/artifacts\/([^/]+)\/events/.exec(socket.url());
+ if (found) sockets.set(decodeURIComponent(found[1] as string), socket);
+ });
+ await page.goto(`${options.host ? ARTIFACTS_HOST : ORIGIN}${options.path}`);
+ await options.ready(page);
+ await restyle(page);
+ return { page, sockets };
+}
+
+/**
+ * THE OPENBOT DESKTOP WINDOW, AS THE PAGE SEES IT, for the page's downloads: Tauri's
+ * `__TAURI_INTERNALS__`, answering `show_download` as the desktop does once it has shown the file,
+ * and refusing every other command as a desktop app without it does (tauri/src/ipc/authority.rs),
+ * which every caller in the app already copes with. Every call is kept in `window.desktopCalls`.
+ * Run in the page before it loads, so it is serialised whole.
+ */
+export function installDesktopWindow() {
+ const calls: { command: string; args?: unknown }[] = [];
+ (window as unknown as { desktopCalls: typeof calls }).desktopCalls = calls;
+ let callbacks = 0;
+ (window as unknown as { __TAURI_INTERNALS__: unknown }).__TAURI_INTERNALS__ =
+ {
+ transformCallback: () => {
+ callbacks += 1;
+ return callbacks;
+ },
+ unregisterCallback: () => {},
+ invoke: async (command: string, args?: unknown) => {
+ calls.push({ command, args });
+ if (command === "plugin:openbot-desktop|show_download") return null;
+ const name = command.split("|").pop();
+ throw `openbot-desktop.${name} not allowed. Command not found`;
+ },
+ };
+}
+
+/** What OpenBot Desktop dispatches once a download ends (`downloads::tell_script`). */
+export function desktopSaid(
+ page: Page,
+ detail: {
+ id: number;
+ fileName: string;
+ folder: string;
+ saved: boolean;
+ system: string;
+ },
+) {
+ return page.evaluate(
+ (told) =>
+ window.dispatchEvent(
+ new CustomEvent("openbot:download", { detail: told, cancelable: true }),
+ ),
+ detail,
+ );
+}
+
+/** The arguments of each call the page made to one of the desktop's commands. */
+export function desktopCalls(page: Page, command: string) {
+ return page.evaluate(
+ (name) =>
+ (
+ window as unknown as {
+ desktopCalls: { command: string; args?: unknown }[];
+ }
+ ).desktopCalls
+ .filter((call) => call.command === `plugin:openbot-desktop|${name}`)
+ .map((call) => call.args),
+ command,
+ );
+}
+
+/** Styles what the page draws now: a press drew things the last stylesheet was not built for. */
+export async function restyle(page: Page) {
+ const classes = await page.evaluate(() =>
+ [...document.querySelectorAll("[class]")].flatMap((element) => [
+ ...element.classList,
+ ]),
+ );
+ await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) });
+ await page.evaluate(() => document.fonts.ready);
+ await still(page);
+}
+
+export async function shoot(page: Page, name: string) {
+ if (!shots) return;
+ mkdirSync(shots, { recursive: true });
+ await page.screenshot({ path: join(shots, `${name}.png`) });
+}
+
+/** What a person would see wrong: sideways scroll, a control cut off, a dialog off the screen. */
+export async function measured(page: Page) {
+ return page.evaluate(() => {
+ const inside = (rect: DOMRect) =>
+ rect.left >= -0.5 && rect.right <= innerWidth + 0.5;
+ const shown = (element: Element) => {
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return (
+ rect.width > 0 &&
+ rect.height > 0 &&
+ style.visibility !== "hidden" &&
+ rect.bottom > 0 &&
+ rect.top < innerHeight
+ );
+ };
+ const dialog = document.querySelector("[data-slot=dialog-content]");
+ const scope: Element = dialog ?? document.body;
+ const cut = [
+ ...scope.querySelectorAll(
+ "button, a, input, [role=combobox], [role=switch], [role=tab]",
+ ),
+ ]
+ .filter(shown)
+ .filter((control) => !control.matches("[data-sidebar=rail]"))
+ // Inside a scroller that scrolls sideways on purpose (a table, the code), a control past the
+ // edge is reached by scrolling it.
+ .filter((control) => !control.closest(".overflow-x-auto"))
+ // The detail panel, closed: folded to no width and clipped, so nothing in it is on screen.
+ .filter(
+ (control) =>
+ (control
+ .closest("[data-slot=detail-pane]")
+ ?.parentElement?.getBoundingClientRect().width ?? 1) > 0,
+ )
+ .filter((control) => !inside(control.getBoundingClientRect()))
+ .map(
+ (control) =>
+ control.textContent?.trim() ||
+ control.getAttribute("aria-label") ||
+ control.tagName,
+ );
+ const box = dialog?.getBoundingClientRect();
+ return {
+ sideways:
+ document.documentElement.scrollWidth > innerWidth ||
+ document.body.scrollWidth > innerWidth,
+ cut,
+ dialogInside: box
+ ? inside(box) && box.top >= 0 && box.bottom <= innerHeight + 0.5
+ : true,
+ };
+ });
+}
+
+export const HOLDS = { sideways: false, cut: [], dialogInside: true };
+
+export async function unanswered(page: Page): Promise {
+ return page.evaluate(() =>
+ window.unanswered.filter(
+ (line) => line.startsWith("SPEC") || line.startsWith("REFUSED"),
+ ),
+ );
+}
+
+export async function asks(page: Page) {
+ return page.evaluate(() =>
+ window.artifactsServer.asked.map((one) => ({
+ method: one.method,
+ path: one.path,
+ ifMatch: one.headers["if-match"],
+ key: one.headers["idempotency-key"],
+ body: one.body,
+ })),
+ );
+}
+
+export const conversation = (query = "") => `/channel/launch${query}`;
+/** Inside the open viewer, not a glimpse of the same artifact in a card or a tile. */
+export const inViewer = (page: Page) =>
+ page.locator("[data-slot=artifact-viewer]");
+export const cardsReady = (page: Page) =>
+ page.getByRole("button", { name: "Open Pricing calculator" }).waitFor();
+
+/** The card a tool's answer drew for the artifact called `title`. */
+export const cardOf = (page: Page, title: string) =>
+ page.locator("[data-slot=artifact-card]", {
+ has: page.getByRole("button", { name: `Open ${title}`, exact: true }),
+ });
+/** What a glimpse shows once it has read its artifact: a page's picture or frame, a kind's own. */
+export const DRAWN =
+ ":is([data-slot=artifact-page-thumbnail],[data-slot=artifact-page-live],[data-mode=thumbnail])";
+
+/** Whether every one of `inner`'s boxes lies inside `outer`'s. */
+export async function inside(
+ outer: import("playwright-core").Locator,
+ inner: import("playwright-core").Locator[],
+) {
+ const box = await outer.boundingBox();
+ if (!box) return false;
+ for (const one of inner) {
+ const rect = await one.boundingBox();
+ if (!rect) return false;
+ if (
+ rect.x < box.x - 0.5 ||
+ rect.y < box.y - 0.5 ||
+ rect.x + rect.width > box.x + box.width + 0.5 ||
+ rect.y + rect.height > box.y + box.height + 0.5
+ )
+ return false;
+ }
+ return true;
+}
+
+export type Screen = {
+ name: string;
+ entry: "app" | "conversation";
+ path: string;
+ host?: boolean;
+ ready: (page: Page) => Promise;
+ /** What the person does next, once the screen is styled. */
+ press?: (page: Page) => Promise;
+ /** Drawn only to be looked at beside the artifact screens, when screenshots are asked for. */
+ lookOnly?: boolean;
+};
+
+/** The viewer, with the version's content drawn in it (styled after that, not before). */
+export const panelReady = (page: Page) =>
+ inViewer(page)
+ .locator(
+ ":is([data-slot=artifact-document],[data-slot=artifact-slides],[data-slot=artifact-dashboard],[data-slot=artifact-sheet],[data-slot=artifact-diagram],[data-slot=artifact-page-frame])",
+ )
+ .first()
+ .waitFor();
+
+export const SCREENS: Screen[] = [
+ {
+ name: "conversation-cards",
+ entry: "conversation",
+ path: conversation(),
+ ready: cardsReady,
+ },
+ {
+ name: "panel-older-version",
+ entry: "conversation",
+ path: conversation(`?artifact=${PLAN_ID}&artifactVersion=2`),
+ ready: (page) => page.getByText("You're looking at v2.").waitFor(),
+ },
+ {
+ name: "panel-source",
+ entry: "conversation",
+ path: conversation(`?artifact=${PLAN_ID}`),
+ ready: panelReady,
+ press: (page) => page.getByRole("tab", { name: "Source" }).click(),
+ },
+ {
+ name: "panel-versions-menu",
+ entry: "conversation",
+ path: conversation(`?artifact=${PLAN_ID}`),
+ ready: panelReady,
+ press: async (page) => {
+ await page.getByRole("button", { name: /Choose a version/ }).click();
+ await page.getByRole("menuitemradio").first().waitFor();
+ },
+ },
+ {
+ name: "panel-dashboard",
+ entry: "conversation",
+ path: conversation(`?artifact=${DASHBOARD_ID}`),
+ ready: (page) =>
+ inViewer(page).getByText("Deals by stage").first().waitFor(),
+ },
+ {
+ name: "panel-page",
+ entry: "conversation",
+ path: conversation(`?artifact=${PAGE_ID}`),
+ ready: (page) => page.locator("[data-slot=artifact-page-frame]").waitFor(),
+ },
+ {
+ name: "share-dialog",
+ entry: "conversation",
+ path: conversation(`?artifact=${PLAN_ID}`),
+ ready: panelReady,
+ press: async (page) => {
+ await page.getByRole("button", { name: "Share" }).click();
+ await page.getByRole("dialog").getByText("Asking for access").waitFor();
+ },
+ },
+ {
+ name: "share-dialog-link-to-pass-on",
+ entry: "conversation",
+ path: conversation(`?mail=off&artifact=${PLAN_ID}`),
+ ready: panelReady,
+ press: async (page) => {
+ await page.getByRole("button", { name: "Share" }).click();
+ const dialog = page.getByRole("dialog");
+ await dialog.getByText("Asking for access").waitFor();
+ // The dialog is drawn with classes of its own, styled before anything in it is pressed.
+ await restyle(page);
+ await dialog
+ .getByRole("textbox", { name: "Email address to invite" })
+ .fill("jo@partner.example");
+ await dialog.getByRole("button", { name: "Invite", exact: true }).click();
+ await dialog.getByText(/Send them this link yourself/).waitFor();
+ await dialog
+ .getByText(/Send them this link yourself/)
+ .scrollIntoViewIfNeeded();
+ },
+ },
+ // Each card's glimpse, on screen: every kind drawn as itself, a page as its picture or itself.
+ ...(
+ [
+ ["card-slides", "Board update, November"],
+ ["card-sheet", "Hiring tracker"],
+ ["card-diagram", "Signup flow"],
+ ["card-page", "Pricing calculator"],
+ ["card-page-making", "Mortgage calculator"],
+ ] as const
+ ).map(
+ ([name, title]): Screen => ({
+ name,
+ entry: "conversation",
+ path: conversation(),
+ ready: cardsReady,
+ press: async (page) => {
+ const card = cardOf(page, title);
+ await card.scrollIntoViewIfNeeded();
+ await card.locator(DRAWN).first().waitFor({ state: "attached" });
+ await card.evaluate((element) =>
+ element.scrollIntoView({ block: "center" }),
+ );
+ },
+ }),
+ ),
+ {
+ name: "artifacts-grid",
+ entry: "app",
+ path: "/artifacts",
+ ready: (page) =>
+ page.getByRole("button", { name: "Pricing calculator" }).waitFor(),
+ },
+ {
+ name: "artifacts-grid-end",
+ entry: "app",
+ path: "/artifacts",
+ ready: (page) =>
+ page.getByRole("button", { name: "Pricing calculator" }).waitFor(),
+ press: async (page) => {
+ const last = page.locator("[data-slot=artifact-tile]").last();
+ await last.scrollIntoViewIfNeeded();
+ await last.locator(DRAWN).first().waitFor({ state: "attached" });
+ },
+ },
+ {
+ name: "artifacts-list",
+ entry: "app",
+ path: "/artifacts?layout=list",
+ ready: (page) =>
+ page.getByRole("button", { name: /Pricing calculator/ }).waitFor(),
+ },
+ {
+ name: "artifacts-empty",
+ entry: "app",
+ path: "/artifacts?empty=1",
+ ready: (page) => page.getByText("No artifacts yet").waitFor(),
+ },
+ {
+ name: "artifacts-open",
+ entry: "app",
+ path: `/artifacts?artifact=${DASHBOARD_ID}`,
+ ready: (page) =>
+ inViewer(page).getByText("Deals by stage").first().waitFor(),
+ },
+ {
+ name: "full-screen-dashboard",
+ entry: "app",
+ path: `/artifacts/${DASHBOARD_ID}`,
+ ready: (page) =>
+ inViewer(page).getByText("Deals by stage").first().waitFor(),
+ },
+ {
+ name: "full-screen-slides",
+ entry: "app",
+ path: `/artifacts/Zx3Ty8Wq1Pk6Lm2Nb7Vc4D`,
+ ready: (page) => inViewer(page).getByText("Highlights").first().waitFor(),
+ },
+ // A person's cream theme on the deck and the dashboard: the content takes it, the viewer doesn't.
+ {
+ name: "open-themed-slides",
+ entry: "app",
+ path: `/artifacts?themed=1&artifact=Zx3Ty8Wq1Pk6Lm2Nb7Vc4D`,
+ ready: (page) => inViewer(page).getByText("Board update").first().waitFor(),
+ },
+ {
+ name: "full-screen-themed-slides",
+ entry: "app",
+ path: `/artifacts/Zx3Ty8Wq1Pk6Lm2Nb7Vc4D?themed=1`,
+ ready: (page) => inViewer(page).getByText("Board update").first().waitFor(),
+ },
+ {
+ name: "open-themed-dashboard",
+ entry: "app",
+ path: `/artifacts?themed=1&artifact=${DASHBOARD_ID}`,
+ ready: (page) =>
+ inViewer(page).getByText("Deals by stage").first().waitFor(),
+ },
+ {
+ name: "full-screen-themed-dashboard",
+ entry: "app",
+ path: `/artifacts/${DASHBOARD_ID}?themed=1`,
+ ready: (page) =>
+ inViewer(page).getByText("Deals by stage").first().waitFor(),
+ },
+ {
+ name: "host-outside-public",
+ entry: "app",
+ path: `/${SHARED_ID}?outside=1`,
+ host: true,
+ ready: (page) =>
+ page.getByText("Nine renewals are due this quarter.").waitFor(),
+ },
+ {
+ name: "host-outside-code",
+ entry: "app",
+ path: `/${PLAN_ID}?outside=1`,
+ host: true,
+ ready: (page) => page.getByLabel("Were you sent a code?").waitFor(),
+ },
+ {
+ name: "host-member",
+ entry: "app",
+ path: `/${PLAN_ID}`,
+ host: true,
+ ready: panelReady,
+ },
+ // One of the app's own pages, to look at beside the new ones.
+ {
+ name: "teams-page",
+ entry: "app",
+ path: "/teams",
+ lookOnly: true,
+ ready: (page) => page.getByText("Finance").first().waitFor(),
+ },
+];
+
+/** One screen's layout case: in a theme, at a width. */
+export type LayoutCase = {
+ name: string;
+ screen: Screen;
+ theme: Theme;
+ window: Window;
+};
+
+/**
+ * How many files the layout cases are dealt over: artifacts-screens-layout-1.test.tsx to -4. Each
+ * is about two minutes in CI, beside the other files of its shard.
+ */
+export const LAYOUT_PARTS = 4;
+
+/** Every layout case, in order: each screen in light and dark, wide, narrow and on a phone. */
+export function layoutCases(): LayoutCase[] {
+ return SCREENS.filter((screen) => !screen.lookOnly || shots).flatMap(
+ (screen) =>
+ THEMES.flatMap((theme) =>
+ [WIDE, NARROW, PHONE].map((window) => ({
+ name: `${screen.name} in ${theme}, ${window.width}px`,
+ screen,
+ theme,
+ window,
+ })),
+ ),
+ );
+}
+
+/**
+ * The cases one file runs: every `LAYOUT_PARTS`th, from its own place on, so each file gets about
+ * as many, of every kind of screen, and a screen added to `SCREENS` lands in one of them by itself.
+ */
+export function layoutPart(part: number): LayoutCase[] {
+ return layoutCases().filter((_, index) => index % LAYOUT_PARTS === part - 1);
+}
+
+/**
+ * A screen holds its layout: nothing scrolls sideways, no control is cut off, a dialog stays on the
+ * screen, and the page asked the server nothing it refused.
+ */
+export async function holdsItsLayout({ screen, theme, window }: LayoutCase) {
+ const { page } = await open({
+ entry: screen.entry,
+ path: screen.path,
+ host: screen.host,
+ theme,
+ window,
+ ready: screen.ready,
+ });
+ try {
+ if (screen.press) {
+ await screen.press(page);
+ await restyle(page);
+ }
+ await shoot(page, `${screen.name}-${theme}-${window.width}`);
+ if (screen.lookOnly) return;
+ expect(await measured(page)).toEqual(HOLDS);
+ expect(await unanswered(page)).toEqual([]);
+ } finally {
+ await page.close();
+ }
+}
diff --git a/app/tests/artifacts-screens.test.tsx b/app/tests/artifacts-screens.test.tsx
index e2e182ef9e..7b2253112d 100644
--- a/app/tests/artifacts-screens.test.tsx
+++ b/app/tests/artifacts-screens.test.tsx
@@ -1,13 +1,6 @@
-import { afterAll, beforeAll, describe, expect } from "bun:test";
-import { existsSync, mkdirSync, readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import type {
- Browser,
- BrowserType,
- Page,
- WebSocketRoute,
-} from "playwright-core";
-import { compile } from "tailwindcss";
+import { describe, expect } from "bun:test";
+import { mkdirSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
import {
ARTIFACTS_HOST,
DASHBOARD_ID,
@@ -20,7 +13,33 @@ import {
THUMBNAIL_DARK_SHA,
THUMBNAIL_LIGHT_SHA,
} from "./artifacts-api";
-import { marksPlugin } from "./marks-plugin";
+import {
+ asks,
+ cardOf,
+ cardsReady,
+ conversation,
+ DRAWN,
+ desktopCalls,
+ desktopSaid,
+ EXPORTED_PDF,
+ HOLDS,
+ inside,
+ inViewer,
+ LAYOUT_PARTS,
+ measured,
+ NARROW,
+ ORIGIN,
+ open,
+ PHONE,
+ restyle,
+ shoot,
+ shots,
+ THEMES,
+ unanswered,
+ WIDE,
+ withArtifactsBrowser,
+} from "./artifacts-screens.harness";
+import { ownBrowsersAsked } from "./browser-engines";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -44,415 +63,37 @@ import { test } from "./renderer-crash";
* OPENBOT_APP_SHOTS= every screen is saved as
* --.png, in light and dark, wide (1440), narrow (700, the panel a sheet) and
* at a phone's width (390), beside one of the app's own pages (Teams) to compare them with.
+ *
+ * Each screen's layout, in each theme and width, is held in artifacts-screens-layout-1.test.tsx and
+ * the files numbered after it, dealt over several files so the browser jobs run them side by side
+ * (artifacts-screens.harness.ts).
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
-const shots = process.env.OPENBOT_APP_SHOTS;
-
-const APP = join(import.meta.dir, "..");
-const ORIGIN = "http://openbot.test";
-
-const WIDE = { width: 1440, height: 900 };
-const NARROW = { width: 700, height: 900 };
-const PHONE = { width: 390, height: 844 };
-const THEMES = ["light", "dark"] as const;
-type Theme = (typeof THEMES)[number];
-type Window = { width: number; height: number };
-
-async function bundle(entry: string): Promise {
- const built = await Bun.build({
- entrypoints: [join(import.meta.dir, entry)],
- target: "browser",
- define: { "process.env.NODE_ENV": JSON.stringify("production") },
- // An optional map renderer a library loads only when asked to draw a map; not installed.
- external: ["maplibre-gl"],
- plugins: [marksPlugin],
- });
- if (!built.success) throw new AggregateError(built.logs, "bundle failed");
- const script = built.outputs.find((output) => output.kind === "entry-point");
- if (!script) throw new Error("bundle has no entry point");
- return script.text();
-}
-
-/** The directory of an installed package, from the app or the repository root. */
-function packageDir(name: string): string {
- const dir = [
- join(APP, "node_modules", name),
- join(APP, "..", "node_modules", name),
- ].find(existsSync);
- if (!dir) throw new Error(`no package ${name}`);
- return dir;
-}
-
-/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */
-function packageStylesheet(id: string): string {
- const parts = id.split("/");
- const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
- const dir = packageDir(name as string);
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
- const subpath = `.${id.slice((name as string).length)}`;
- const entry = pkg.exports?.[subpath];
- const file =
- typeof entry === "string"
- ? entry
- : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css");
- return join(dir, file);
-}
-
-/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */
-async function stylesheet(classes: string[]): Promise {
- const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP));
- const entry = join(APP, "src", "styles.css");
- const compiler = await compile(readFileSync(entry, "utf8"), {
- base: dirname(entry),
- loadStylesheet: async (id, base) => {
- const path =
- id === "tailwindcss"
- ? join(tailwind, "index.css")
- : id.startsWith(".")
- ? join(base, id)
- : packageStylesheet(id);
- return { path, base: dirname(path), content: readFileSync(path, "utf8") };
- },
- });
- return compiler.build(classes);
-}
-
-let browser: Browser;
-const scripts: Record = {};
-/** A page version's still pictures, by SHA-256, as the server draws them: real JPEGs of the page. */
-const pictures = new Map();
-
-/** An exported file's bytes, as the server streams them. */
-const EXPORTED_PDF = "%PDF-1.7 Q3 launch plan";
-
-/**
- * The server's file downloads, on a real socket. A download leaves the page's own network: the
- * browser fetches it itself, past `page.route`, so a file fulfilled there never arrived (Chromium
- * called the download cancelled, WebKit never started it) while the test still read the name off
- * the link. The browser reaches the app's address through this, as a proxy, and it answers an
- * export's file as `downloadArtifactExport` does.
- */
-let files: ReturnType | undefined;
-
-beforeAll(async () => {
- if (!asked) return;
- scripts.app = await bundle("artifacts-app.fixture.tsx");
- scripts.conversation = await bundle("artifacts-conversation.fixture.tsx");
- files = Bun.serve({
- hostname: "127.0.0.1",
- port: 0,
- fetch: (request) =>
- /\/exports\/[^/]+\/file$/.test(new URL(request.url).pathname)
- ? new Response(EXPORTED_PDF, {
- headers: {
- "content-type": "application/pdf",
- "content-disposition":
- 'attachment; filename="Q3 launch plan.pdf"',
- "cache-control": "private, no-store",
- "x-content-type-options": "nosniff",
- },
- })
- : new Response("", { status: 404 }),
- });
- const proxy = { server: `http://127.0.0.1:${files.port}` };
- const playwright = await import("playwright-core");
- const chromium: BrowserType = playwright.chromium;
- // OPENBOT_APP_ENGINE=webkit: Safari's engine. The CI job installs full Chromium without the
- // headless shell.
- browser =
- process.env.OPENBOT_APP_ENGINE === "webkit"
- ? await playwright.webkit.launch({ proxy })
- : await chromium.launch({ channel: "chromium", proxy });
- // The page in light and dark, drawn at 1280 by 720 as the server's renderer draws it.
- for (const [sha, html] of [
- [THUMBNAIL_LIGHT_SHA, PAGE_CONTENT],
- [THUMBNAIL_DARK_SHA, PAGE_CONTENT_DARK],
- ] as const) {
- const drawing = await browser.newPage({
- viewport: { width: 1280, height: 720 },
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
+withArtifactsBrowser(asked);
+
+// In the suite as well as the browser jobs: a layout file missing, or one dealing out the wrong
+// part, would leave a share of the screens unheld with nothing going red.
+test("every layout case is in one of the layout files, once", () => {
+ const files = readdirSync(import.meta.dir)
+ .filter((file) => /^artifacts-screens-layout-\d+\.test\.tsx$/.test(file))
+ .sort();
+ const parts = Array.from({ length: LAYOUT_PARTS }, (_, index) => index + 1);
+ expect(files).toEqual(
+ parts.map((part) => `artifacts-screens-layout-${part}.test.tsx`).sort(),
+ );
+ for (const part of parts) {
+ const source = readFileSync(
+ join(import.meta.dir, `artifacts-screens-layout-${part}.test.tsx`),
+ "utf8",
+ );
+ expect({ part, deals: source.match(/layoutPart\((\d+)\)/g) }).toEqual({
+ part,
+ deals: [`layoutPart(${part})`],
});
- await drawing.setContent(html);
- pictures.set(sha, await drawing.screenshot({ type: "jpeg", quality: 80 }));
- await drawing.close();
}
-}, 180_000);
-
-afterAll(async () => {
- await browser?.close();
- files?.stop(true);
});
-/** What a sandboxed page artifact's content looks like when the artifacts host serves it. */
-const PAGE_CONTENT = `
Pricing
Seats × price, as a page a Bot built.
`;
-/** The same page as the bridge draws it when the app is dark: the server's dark picture of it. */
-const PAGE_CONTENT_DARK = PAGE_CONTENT.replace(
- "background:#fff;color:#111",
- "background:#0e131b;color:#f2f4f7",
-);
-
-type Opened = {
- page: Page;
- /** The artifact sockets the page opened, by artifact id. */
- sockets: Map;
-};
-
-/**
- * One page of the app: the conversation stand-in or the real app (`entry`), at `path` on the app's
- * address or on the artifacts host (`host`), in a theme and a window, with the server's setup in
- * `query`.
- */
-async function open(options: {
- entry: "app" | "conversation";
- path: string;
- theme: Theme;
- window: Window;
- host?: boolean;
- /**
- * The artifacts host's mark without the organization, as the server serves it to somebody who
- * may not see the artifact yet.
- */
- unnamed?: boolean;
- /** Inside the OpenBot Desktop window (`installDesktopWindow`). */
- desktop?: boolean;
- ready: (page: Page) => Promise;
-}): Promise {
- const page = await browser.newPage({
- viewport: options.window,
- colorScheme: options.theme,
- reducedMotion: "reduce",
- acceptDownloads: true,
- });
- page.on("pageerror", (error) => console.error(error));
- if (options.desktop) await page.addInitScript(installDesktopWindow);
- const inter = join(packageDir("@fontsource-variable/figtree"), "files");
- const script = scripts[options.entry] as string;
- const html = (meta: string) =>
- `${meta}`;
- const serve =
- (meta: string) => async (route: import("playwright-core").Route) => {
- const url = new URL(route.request().url());
- const path = url.pathname;
- if (path === "/screens.js")
- return route.fulfill({ contentType: "text/javascript", body: script });
- // OpenBot's mark, which the bundle names by a file of its own.
- if (/openbot-logo.*\.png$/.test(path))
- return route.fulfill({
- path: join(APP, "src", "assets", "openbot-logo.png"),
- });
- const font = join(inter, path.split("/").pop() ?? "");
- if (path.startsWith("/files/") && existsSync(font))
- return route.fulfill({ path: font });
- // A file the Download menu hands the browser to save: the export's own address, which
- // the browser fetches itself, from the real server (`files`).
- if (/\/exports\/[^/]+\/file$/.test(path)) return route.continue();
- // A page version's still picture, through the artifact's asset route.
- const asset = /\/artifacts\/[^/]+\/assets\/([0-9a-f]{64})$/.exec(path);
- if (asset) {
- const picture = pictures.get(asset[1] as string);
- return picture
- ? route.fulfill({
- status: 200,
- body: picture,
- headers: { "content-type": "image/jpeg" },
- })
- : route.fulfill({ status: 404, body: "" });
- }
- // A page artifact's content, as the artifacts host serves it: sandboxed, whatever frames it.
- if (/\/content$/.test(path))
- return route.fulfill({
- status: 200,
- body: PAGE_CONTENT,
- headers: {
- "content-type": "text/html",
- "content-security-policy":
- "sandbox allow-scripts; default-src 'none'; style-src 'unsafe-inline'",
- },
- });
- return route.fulfill({ contentType: "text/html", body: html(meta) });
- };
- await page.route(`${ORIGIN}/**`, serve(""));
- await page.route(
- `${ARTIFACTS_HOST}/**`,
- serve(
- options.unnamed
- ? ''
- : '',
- ),
- );
- const sockets = new Map();
- await page.routeWebSocket(/.*/, (socket) => {
- const found = /\/artifacts\/([^/]+)\/events/.exec(socket.url());
- if (found) sockets.set(decodeURIComponent(found[1] as string), socket);
- });
- await page.goto(`${options.host ? ARTIFACTS_HOST : ORIGIN}${options.path}`);
- await options.ready(page);
- await restyle(page);
- return { page, sockets };
-}
-
-/**
- * THE OPENBOT DESKTOP WINDOW, AS THE PAGE SEES IT, for the page's downloads: Tauri's
- * `__TAURI_INTERNALS__`, answering `show_download` as the desktop does once it has shown the file,
- * and refusing every other command as a desktop app without it does (tauri/src/ipc/authority.rs),
- * which every caller in the app already copes with. Every call is kept in `window.desktopCalls`.
- * Run in the page before it loads, so it is serialised whole.
- */
-function installDesktopWindow() {
- const calls: { command: string; args?: unknown }[] = [];
- (window as unknown as { desktopCalls: typeof calls }).desktopCalls = calls;
- let callbacks = 0;
- (window as unknown as { __TAURI_INTERNALS__: unknown }).__TAURI_INTERNALS__ =
- {
- transformCallback: () => {
- callbacks += 1;
- return callbacks;
- },
- unregisterCallback: () => {},
- invoke: async (command: string, args?: unknown) => {
- calls.push({ command, args });
- if (command === "plugin:openbot-desktop|show_download") return null;
- const name = command.split("|").pop();
- throw `openbot-desktop.${name} not allowed. Command not found`;
- },
- };
-}
-
-/** What OpenBot Desktop dispatches once a download ends (`downloads::tell_script`). */
-function desktopSaid(
- page: Page,
- detail: {
- id: number;
- fileName: string;
- folder: string;
- saved: boolean;
- system: string;
- },
-) {
- return page.evaluate(
- (told) =>
- window.dispatchEvent(
- new CustomEvent("openbot:download", { detail: told, cancelable: true }),
- ),
- detail,
- );
-}
-
-/** The arguments of each call the page made to one of the desktop's commands. */
-function desktopCalls(page: Page, command: string) {
- return page.evaluate(
- (name) =>
- (
- window as unknown as {
- desktopCalls: { command: string; args?: unknown }[];
- }
- ).desktopCalls
- .filter((call) => call.command === `plugin:openbot-desktop|${name}`)
- .map((call) => call.args),
- command,
- );
-}
-
-/** Styles what the page draws now: a press drew things the last stylesheet was not built for. */
-async function restyle(page: Page) {
- const classes = await page.evaluate(() =>
- [...document.querySelectorAll("[class]")].flatMap((element) => [
- ...element.classList,
- ]),
- );
- await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) });
- await page.evaluate(() => document.fonts.ready);
- await still(page);
-}
-
-async function shoot(page: Page, name: string) {
- if (!shots) return;
- mkdirSync(shots, { recursive: true });
- await page.screenshot({ path: join(shots, `${name}.png`) });
-}
-
-/** What a person would see wrong: sideways scroll, a control cut off, a dialog off the screen. */
-async function measured(page: Page) {
- return page.evaluate(() => {
- const inside = (rect: DOMRect) =>
- rect.left >= -0.5 && rect.right <= innerWidth + 0.5;
- const shown = (element: Element) => {
- const rect = element.getBoundingClientRect();
- const style = getComputedStyle(element);
- return (
- rect.width > 0 &&
- rect.height > 0 &&
- style.visibility !== "hidden" &&
- rect.bottom > 0 &&
- rect.top < innerHeight
- );
- };
- const dialog = document.querySelector("[data-slot=dialog-content]");
- const scope: Element = dialog ?? document.body;
- const cut = [
- ...scope.querySelectorAll(
- "button, a, input, [role=combobox], [role=switch], [role=tab]",
- ),
- ]
- .filter(shown)
- .filter((control) => !control.matches("[data-sidebar=rail]"))
- // Inside a scroller that scrolls sideways on purpose (a table, the code), a control past the
- // edge is reached by scrolling it.
- .filter((control) => !control.closest(".overflow-x-auto"))
- // The detail panel, closed: folded to no width and clipped, so nothing in it is on screen.
- .filter(
- (control) =>
- (control
- .closest("[data-slot=detail-pane]")
- ?.parentElement?.getBoundingClientRect().width ?? 1) > 0,
- )
- .filter((control) => !inside(control.getBoundingClientRect()))
- .map(
- (control) =>
- control.textContent?.trim() ||
- control.getAttribute("aria-label") ||
- control.tagName,
- );
- const box = dialog?.getBoundingClientRect();
- return {
- sideways:
- document.documentElement.scrollWidth > innerWidth ||
- document.body.scrollWidth > innerWidth,
- cut,
- dialogInside: box
- ? inside(box) && box.top >= 0 && box.bottom <= innerHeight + 0.5
- : true,
- };
- });
-}
-
-const HOLDS = { sideways: false, cut: [], dialogInside: true };
-
-async function unanswered(page: Page): Promise {
- return page.evaluate(() =>
- window.unanswered.filter(
- (line) => line.startsWith("SPEC") || line.startsWith("REFUSED"),
- ),
- );
-}
-
-async function asks(page: Page) {
- return page.evaluate(() =>
- window.artifactsServer.asked.map((one) => ({
- method: one.method,
- path: one.path,
- ifMatch: one.headers["if-match"],
- key: one.headers["idempotency-key"],
- body: one.body,
- })),
- );
-}
-
-const conversation = (query = "") => `/channel/launch${query}`;
-/** Inside the open viewer, not a glimpse of the same artifact in a card or a tile. */
-const inViewer = (page: Page) => page.locator("[data-slot=artifact-viewer]");
-const cardsReady = (page: Page) =>
- page.getByRole("button", { name: "Open Pricing calculator" }).waitFor();
-
/* ------------------------------------------------------------------------------------- The flows */
describe.skipIf(!asked)("artifacts in a conversation", () => {
@@ -1466,38 +1107,6 @@ describe.skipIf(!asked)("the artifacts host", () => {
}, 60_000);
});
-/* ----------------------------------------------------------------- Glimpses: every kind, pictured */
-
-/** The card a tool's answer drew for the artifact called `title`. */
-const cardOf = (page: Page, title: string) =>
- page.locator("[data-slot=artifact-card]", {
- has: page.getByRole("button", { name: `Open ${title}`, exact: true }),
- });
-/** What a glimpse shows once it has read its artifact: a page's picture or frame, a kind's own. */
-const DRAWN =
- ":is([data-slot=artifact-page-thumbnail],[data-slot=artifact-page-live],[data-mode=thumbnail])";
-
-/** Whether every one of `inner`'s boxes lies inside `outer`'s. */
-async function inside(
- outer: import("playwright-core").Locator,
- inner: import("playwright-core").Locator[],
-) {
- const box = await outer.boundingBox();
- if (!box) return false;
- for (const one of inner) {
- const rect = await one.boundingBox();
- if (!rect) return false;
- if (
- rect.x < box.x - 0.5 ||
- rect.y < box.y - 0.5 ||
- rect.x + rect.width > box.x + box.width + 0.5 ||
- rect.y + rect.height > box.y + box.height + 0.5
- )
- return false;
- }
- return true;
-}
-
describe.skipIf(!asked)("glimpses show every kind as itself", () => {
test("a page's card shows its picture; one still being made runs the page in its sandbox until the picture comes; no card is a placeholder", async () => {
const { page } = await open({
@@ -1755,265 +1364,3 @@ describe.skipIf(!asked)("glimpses show every kind as itself", () => {
});
/* ----------------------------------------------------------------------- Every screen, looked at */
-
-type Screen = {
- name: string;
- entry: "app" | "conversation";
- path: string;
- host?: boolean;
- ready: (page: Page) => Promise;
- /** What the person does next, once the screen is styled. */
- press?: (page: Page) => Promise;
- /** Drawn only to be looked at beside the artifact screens, when screenshots are asked for. */
- lookOnly?: boolean;
-};
-
-/** The viewer, with the version's content drawn in it (styled after that, not before). */
-const panelReady = (page: Page) =>
- inViewer(page)
- .locator(
- ":is([data-slot=artifact-document],[data-slot=artifact-slides],[data-slot=artifact-dashboard],[data-slot=artifact-sheet],[data-slot=artifact-diagram],[data-slot=artifact-page-frame])",
- )
- .first()
- .waitFor();
-
-const SCREENS: Screen[] = [
- {
- name: "conversation-cards",
- entry: "conversation",
- path: conversation(),
- ready: cardsReady,
- },
- {
- name: "panel-older-version",
- entry: "conversation",
- path: conversation(`?artifact=${PLAN_ID}&artifactVersion=2`),
- ready: (page) => page.getByText("You're looking at v2.").waitFor(),
- },
- {
- name: "panel-source",
- entry: "conversation",
- path: conversation(`?artifact=${PLAN_ID}`),
- ready: panelReady,
- press: (page) => page.getByRole("tab", { name: "Source" }).click(),
- },
- {
- name: "panel-versions-menu",
- entry: "conversation",
- path: conversation(`?artifact=${PLAN_ID}`),
- ready: panelReady,
- press: async (page) => {
- await page.getByRole("button", { name: /Choose a version/ }).click();
- await page.getByRole("menuitemradio").first().waitFor();
- },
- },
- {
- name: "panel-dashboard",
- entry: "conversation",
- path: conversation(`?artifact=${DASHBOARD_ID}`),
- ready: (page) =>
- inViewer(page).getByText("Deals by stage").first().waitFor(),
- },
- {
- name: "panel-page",
- entry: "conversation",
- path: conversation(`?artifact=${PAGE_ID}`),
- ready: (page) => page.locator("[data-slot=artifact-page-frame]").waitFor(),
- },
- {
- name: "share-dialog",
- entry: "conversation",
- path: conversation(`?artifact=${PLAN_ID}`),
- ready: panelReady,
- press: async (page) => {
- await page.getByRole("button", { name: "Share" }).click();
- await page.getByRole("dialog").getByText("Asking for access").waitFor();
- },
- },
- {
- name: "share-dialog-link-to-pass-on",
- entry: "conversation",
- path: conversation(`?mail=off&artifact=${PLAN_ID}`),
- ready: panelReady,
- press: async (page) => {
- await page.getByRole("button", { name: "Share" }).click();
- const dialog = page.getByRole("dialog");
- await dialog.getByText("Asking for access").waitFor();
- // The dialog is drawn with classes of its own, styled before anything in it is pressed.
- await restyle(page);
- await dialog
- .getByRole("textbox", { name: "Email address to invite" })
- .fill("jo@partner.example");
- await dialog.getByRole("button", { name: "Invite", exact: true }).click();
- await dialog.getByText(/Send them this link yourself/).waitFor();
- await dialog
- .getByText(/Send them this link yourself/)
- .scrollIntoViewIfNeeded();
- },
- },
- // Each card's glimpse, on screen: every kind drawn as itself, a page as its picture or itself.
- ...(
- [
- ["card-slides", "Board update, November"],
- ["card-sheet", "Hiring tracker"],
- ["card-diagram", "Signup flow"],
- ["card-page", "Pricing calculator"],
- ["card-page-making", "Mortgage calculator"],
- ] as const
- ).map(
- ([name, title]): Screen => ({
- name,
- entry: "conversation",
- path: conversation(),
- ready: cardsReady,
- press: async (page) => {
- const card = cardOf(page, title);
- await card.scrollIntoViewIfNeeded();
- await card.locator(DRAWN).first().waitFor({ state: "attached" });
- await card.evaluate((element) =>
- element.scrollIntoView({ block: "center" }),
- );
- },
- }),
- ),
- {
- name: "artifacts-grid",
- entry: "app",
- path: "/artifacts",
- ready: (page) =>
- page.getByRole("button", { name: "Pricing calculator" }).waitFor(),
- },
- {
- name: "artifacts-grid-end",
- entry: "app",
- path: "/artifacts",
- ready: (page) =>
- page.getByRole("button", { name: "Pricing calculator" }).waitFor(),
- press: async (page) => {
- const last = page.locator("[data-slot=artifact-tile]").last();
- await last.scrollIntoViewIfNeeded();
- await last.locator(DRAWN).first().waitFor({ state: "attached" });
- },
- },
- {
- name: "artifacts-list",
- entry: "app",
- path: "/artifacts?layout=list",
- ready: (page) =>
- page.getByRole("button", { name: /Pricing calculator/ }).waitFor(),
- },
- {
- name: "artifacts-empty",
- entry: "app",
- path: "/artifacts?empty=1",
- ready: (page) => page.getByText("No artifacts yet").waitFor(),
- },
- {
- name: "artifacts-open",
- entry: "app",
- path: `/artifacts?artifact=${DASHBOARD_ID}`,
- ready: (page) =>
- inViewer(page).getByText("Deals by stage").first().waitFor(),
- },
- {
- name: "full-screen-dashboard",
- entry: "app",
- path: `/artifacts/${DASHBOARD_ID}`,
- ready: (page) =>
- inViewer(page).getByText("Deals by stage").first().waitFor(),
- },
- {
- name: "full-screen-slides",
- entry: "app",
- path: `/artifacts/Zx3Ty8Wq1Pk6Lm2Nb7Vc4D`,
- ready: (page) => inViewer(page).getByText("Highlights").first().waitFor(),
- },
- // A person's cream theme on the deck and the dashboard: the content takes it, the viewer doesn't.
- {
- name: "open-themed-slides",
- entry: "app",
- path: `/artifacts?themed=1&artifact=Zx3Ty8Wq1Pk6Lm2Nb7Vc4D`,
- ready: (page) => inViewer(page).getByText("Board update").first().waitFor(),
- },
- {
- name: "full-screen-themed-slides",
- entry: "app",
- path: `/artifacts/Zx3Ty8Wq1Pk6Lm2Nb7Vc4D?themed=1`,
- ready: (page) => inViewer(page).getByText("Board update").first().waitFor(),
- },
- {
- name: "open-themed-dashboard",
- entry: "app",
- path: `/artifacts?themed=1&artifact=${DASHBOARD_ID}`,
- ready: (page) =>
- inViewer(page).getByText("Deals by stage").first().waitFor(),
- },
- {
- name: "full-screen-themed-dashboard",
- entry: "app",
- path: `/artifacts/${DASHBOARD_ID}?themed=1`,
- ready: (page) =>
- inViewer(page).getByText("Deals by stage").first().waitFor(),
- },
- {
- name: "host-outside-public",
- entry: "app",
- path: `/${SHARED_ID}?outside=1`,
- host: true,
- ready: (page) =>
- page.getByText("Nine renewals are due this quarter.").waitFor(),
- },
- {
- name: "host-outside-code",
- entry: "app",
- path: `/${PLAN_ID}?outside=1`,
- host: true,
- ready: (page) => page.getByLabel("Were you sent a code?").waitFor(),
- },
- {
- name: "host-member",
- entry: "app",
- path: `/${PLAN_ID}`,
- host: true,
- ready: panelReady,
- },
- // One of the app's own pages, to look at beside the new ones.
- {
- name: "teams-page",
- entry: "app",
- path: "/teams",
- lookOnly: true,
- ready: (page) => page.getByText("Finance").first().waitFor(),
- },
-];
-
-describe.skipIf(!asked)("the artifact screens hold their layout", () => {
- for (const screen of SCREENS) {
- if (screen.lookOnly && !shots) continue;
- for (const theme of THEMES)
- for (const window of [WIDE, NARROW, PHONE]) {
- test(`${screen.name} in ${theme}, ${window.width}px`, async () => {
- const { page } = await open({
- entry: screen.entry,
- path: screen.path,
- host: screen.host,
- theme,
- window,
- ready: screen.ready,
- });
- try {
- if (screen.press) {
- await screen.press(page);
- await restyle(page);
- }
- await shoot(page, `${screen.name}-${theme}-${window.width}`);
- if (screen.lookOnly) return;
- expect(await measured(page)).toEqual(HOLDS);
- expect(await unanswered(page)).toEqual([]);
- } finally {
- await page.close();
- }
- }, 60_000);
- }
- }
-});
diff --git a/app/tests/board-row-layout.test.tsx b/app/tests/board-row-layout.test.tsx
index 3e21ec5bdf..2093be6cf9 100644
--- a/app/tests/board-row-layout.test.tsx
+++ b/app/tests/board-row-layout.test.tsx
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Browser, BrowserType, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { ownBrowsersAsked } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -21,7 +22,8 @@ import { test } from "./renderer-crash";
* With OPENBOT_APP_SHOTS= it also saves the rows at each width, light and dark, in each
* browser, as board-row---.png.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/bots-panel-start-conversation.test.tsx b/app/tests/bots-panel-start-conversation.test.tsx
index 4954776337..85b30644a1 100644
--- a/app/tests/bots-panel-start-conversation.test.tsx
+++ b/app/tests/bots-panel-start-conversation.test.tsx
@@ -1,10 +1,11 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type { Browser, BrowserType, Locator, Page } from "playwright-core";
+import type { Browser, Locator, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { EXPANDED_BOTS_STORAGE_KEY } from "@/lib/bots/panel";
import { personBody } from "./accounts-api";
+import { launchBrowserEngines } from "./browser-engines";
import { conversationPage } from "./conversations-api";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -25,8 +26,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/bots-panel-start-conversation.test.tsx
*
- * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when
- * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves the panel, light and dark,
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both.
+ * With OPENBOT_APP_SHOTS= it saves the panel, light and dark,
* in a desktop window and a narrow one, as bots-panel---.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -196,11 +197,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- // The CI job installs full Chromium without the headless shell.
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
}, 120_000);
afterAll(async () => {
diff --git a/app/tests/browser-engines.test.ts b/app/tests/browser-engines.test.ts
new file mode 100644
index 0000000000..f105354fd8
--- /dev/null
+++ b/app/tests/browser-engines.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { launchBrowserEngines, ownBrowsersAsked } from "./browser-engines";
+
+describe("browser engine selection", () => {
+ for (const [selection, expected] of [
+ [undefined, ["chromium"]],
+ ["chromium", ["chromium"]],
+ ["webkit", ["webkit"]],
+ ["chromium,webkit", ["chromium", "webkit"]],
+ [" chromium, webkit ", ["chromium", "webkit"]],
+ ] as const) {
+ test(`${selection ?? "default"} launches only its selected engines`, async () => {
+ const calls: { engine: string; options: unknown }[] = [];
+ const factory = (engine: string) => ({
+ launch: async (options?: { channel?: string }) => {
+ calls.push({ engine, options });
+ return { engine };
+ },
+ });
+ const opened: [string, { engine: string }][] = [];
+ await launchBrowserEngines(
+ { chromium: factory("chromium"), webkit: factory("webkit") },
+ selection,
+ opened,
+ );
+ expect(calls).toEqual(
+ expected.map((engine) => ({
+ engine,
+ options: engine === "chromium" ? { channel: "chromium" } : undefined,
+ })),
+ );
+ expect(opened).toEqual(expected.map((engine) => [engine, { engine }]));
+ });
+ }
+
+ test("the caller owns browsers already launched when a later engine fails", async () => {
+ const opened: [string, { close: () => void }][] = [];
+ let closed = false;
+ const chromium = {
+ close: () => {
+ closed = true;
+ },
+ };
+ await expect(
+ launchBrowserEngines(
+ {
+ chromium: { launch: async () => chromium },
+ webkit: {
+ launch: async () => {
+ throw new Error("WebKit launch failed");
+ },
+ },
+ },
+ "chromium,webkit",
+ opened,
+ ),
+ ).rejects.toThrow("WebKit launch failed");
+ expect(opened).toEqual([["chromium", chromium]]);
+ for (const [, browser] of opened) browser.close();
+ expect(closed).toBe(true);
+ });
+
+ test("an unsupported selection cannot silently run no browsers", async () => {
+ let launched = false;
+ const factory = {
+ launch: async () => {
+ launched = true;
+ return {};
+ },
+ };
+ await expect(
+ launchBrowserEngines(
+ { chromium: factory, webkit: factory },
+ "unsupported",
+ [],
+ ),
+ ).rejects.toThrow("Unsupported browser engine");
+ expect(launched).toBe(false);
+ });
+});
+
+/** Built, not written out: a file naming the variable outright is taken for a real-browser test. */
+const ASK = ["OPENBOT", "APP", "BROWSER"].join("_");
+
+describe("a file that opens its own browsers", () => {
+ test("runs where Chromium is selected, and only when real-browser tests are asked for", () => {
+ for (const [env, runs] of [
+ [{}, false],
+ [{ [ASK]: "1" }, true],
+ [{ [ASK]: "1", OPENBOT_APP_ENGINES: "chromium" }, true],
+ [{ [ASK]: "1", OPENBOT_APP_ENGINES: "chromium,webkit" }, true],
+ [{ [ASK]: "1", OPENBOT_APP_ENGINES: "webkit" }, false],
+ ] as const) {
+ expect({ env, runs: ownBrowsersAsked(env) }).toEqual({ env, runs });
+ }
+ expect(() =>
+ ownBrowsersAsked({
+ [ASK]: "1",
+ OPENBOT_APP_ENGINES: "firefox",
+ }),
+ ).toThrow("Unsupported browser engine: firefox");
+ });
+
+ test("CI's cross-browser list: every file opens only the engine its run selects, or runs once", () => {
+ // The list runs once per engine. A file that ignored the selection ran in full in both runs:
+ // artifacts-screens, the slowest file, twice. Each file must read OPENBOT_APP_ENGINES, launch
+ // through launchBrowserEngines, or gate on ownBrowsersAsked.
+ const root = join(import.meta.dir, "..", "..");
+ const ci = Bun.YAML.parse(
+ readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"),
+ ) as { jobs: Record };
+ const listed = (ci.jobs["app-browser-webkit"]?.steps ?? []).flatMap(
+ (step) =>
+ (step.run ?? "").match(/app\/tests\/[\w.-]+\.test\.tsx?/g) ?? [],
+ );
+ expect(listed.length).toBeGreaterThan(50);
+ const ignoring = [...new Set(listed)].filter(
+ (file) =>
+ !/OPENBOT_APP_ENGINES|launchBrowserEngines|ownBrowsersAsked/.test(
+ readFileSync(join(root, file), "utf8"),
+ ),
+ );
+ expect(ignoring).toEqual([]);
+ });
+});
diff --git a/app/tests/browser-engines.ts b/app/tests/browser-engines.ts
new file mode 100644
index 0000000000..d34ae22b62
--- /dev/null
+++ b/app/tests/browser-engines.ts
@@ -0,0 +1,49 @@
+type BrowserFactory = {
+ launch(options?: { channel?: string }): Promise;
+};
+
+/** The engines OPENBOT_APP_ENGINES names, Chromium when it names none. */
+export function selectedEngines(
+ selection: string | undefined,
+): Set<"chromium" | "webkit"> {
+ const selected = new Set<"chromium" | "webkit">();
+ for (const engine of (selection?.trim() || "chromium").split(",")) {
+ const name = engine.trim();
+ if (name !== "chromium" && name !== "webkit") {
+ throw new Error(`Unsupported browser engine: ${name}`);
+ }
+ selected.add(name);
+ }
+ return selected;
+}
+
+/**
+ * Whether a real-browser test file that opens its own browsers, rather than the engines
+ * OPENBOT_APP_ENGINES selects, runs: real-browser tests are asked for and Chromium is selected,
+ * as it is by default. Such a file opens Chromium alone, or both engines itself. CI's cross-browser
+ * list runs once per engine, so it runs there once, in the Chromium run, not twice.
+ */
+export function ownBrowsersAsked(
+ env: Record = process.env,
+): boolean {
+ return (
+ env.OPENBOT_APP_BROWSER === "1" &&
+ selectedEngines(env.OPENBOT_APP_ENGINES).has("chromium")
+ );
+}
+
+/** Launch only the selected engines. The caller retains cleanup ownership, including on failure. */
+export async function launchBrowserEngines(
+ factories: Record<"chromium" | "webkit", BrowserFactory>,
+ selection: string | undefined,
+ opened: [string, T][],
+): Promise {
+ for (const engine of selectedEngines(selection)) {
+ // CI installs full Chromium without the headless shell.
+ const browser =
+ engine === "chromium"
+ ? await factories.chromium.launch({ channel: "chromium" })
+ : await factories.webkit.launch();
+ opened.push([engine, browser]);
+ }
+}
diff --git a/app/tests/company-sign-in.test.tsx b/app/tests/company-sign-in.test.tsx
index e3c7f17254..e9744cd20f 100644
--- a/app/tests/company-sign-in.test.tsx
+++ b/app/tests/company-sign-in.test.tsx
@@ -426,6 +426,8 @@ test("Harbor begins to hold her out while the app is open: the first request ref
heldOut = false;
const { view } = openApp();
await view.findByText("The app");
+ // Home can draw before its socket opens: hold out an established page, not a pending handshake.
+ await waitFor(() => expect(sockets).toHaveLength(1));
heldOut = true;
// Anything the page asks next, as it would on its next read.
diff --git a/app/tests/plan-notices-layout.test.tsx b/app/tests/plan-notices-layout.test.tsx
index 8f3cdc47e4..5cc4901a8d 100644
--- a/app/tests/plan-notices-layout.test.tsx
+++ b/app/tests/plan-notices-layout.test.tsx
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { ownBrowsersAsked } from "./browser-engines";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -18,7 +19,8 @@ import { test } from "./renderer-crash";
* With OPENBOT_APP_SHOTS= it also saves each scene and state as plan--.png, and
* the trial's screens in light and dark, wide and on a phone, beside one of the app's own dialogs.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/renderer-crash.test.ts b/app/tests/renderer-crash.test.ts
index 57027e4fb6..753286718b 100644
--- a/app/tests/renderer-crash.test.ts
+++ b/app/tests/renderer-crash.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import { join } from "node:path";
+import { ownBrowsersAsked } from "./browser-engines";
/**
* A real-browser test the browser's renderer crashed in runs again, up to twice, and so does one where
@@ -14,7 +15,8 @@ import { join } from "node:path";
*
* OPENBOT_APP_BROWSER=1 bun test app/tests/renderer-crash.test.ts
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
/*
* Each of the fixture's tests gets this long, all its goes together. Three crashes and three new
diff --git a/app/tests/roster-working.test.tsx b/app/tests/roster-working.test.tsx
index fbf601d216..36bb305eef 100644
--- a/app/tests/roster-working.test.tsx
+++ b/app/tests/roster-working.test.tsx
@@ -1,13 +1,9 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type {
- Browser,
- BrowserType,
- Page,
- WebSocketRoute,
-} from "playwright-core";
+import type { Browser, Page, WebSocketRoute } from "playwright-core";
import { compile } from "tailwindcss";
+import { launchBrowserEngines } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -26,7 +22,7 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/roster-working.test.tsx
*
- * Chromium always, WebKit too when `OPENBOT_APP_ENGINES` names it; light and dark. With
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both, light and dark. With
* OPENBOT_APP_SHOTS= it saves each moment as roster-working----.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -168,10 +164,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
});
afterAll(async () => {
diff --git a/app/tests/section-strip-routines.test.tsx b/app/tests/section-strip-routines.test.tsx
index 1e421b8239..491be80edd 100644
--- a/app/tests/section-strip-routines.test.tsx
+++ b/app/tests/section-strip-routines.test.tsx
@@ -1,9 +1,10 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type { Browser, BrowserType, Page } from "playwright-core";
+import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { personBody } from "./accounts-api";
+import { launchBrowserEngines } from "./browser-engines";
import { conversationPage } from "./conversations-api";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -26,8 +27,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/section-strip-routines.test.tsx
*
- * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when
- * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves the strip and the panel on
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both.
+ * With OPENBOT_APP_SHOTS= it saves the strip and the panel on
* Routines, after Conversations, Bots and then Routines, as section-strip-routines--.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -190,11 +191,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- // The CI job installs full Chromium without the headless shell.
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
}, 120_000);
afterAll(async () => {
diff --git a/app/tests/select-scrolls-layout.test.tsx b/app/tests/select-scrolls-layout.test.tsx
index 8feb270b76..1cb4dfc997 100644
--- a/app/tests/select-scrolls-layout.test.tsx
+++ b/app/tests/select-scrolls-layout.test.tsx
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { selectedEngines } from "./browser-engines";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -34,10 +35,14 @@ import { test } from "./renderer-crash";
* With OPENBOT_APP_SHOTS= each open select is saved as select-scrolls-arrow-.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
-const webkitAsked = (process.env.OPENBOT_APP_ENGINES ?? "chromium")
- .split(",")
- .map((engine) => engine.trim())
- .includes("webkit");
+// CI's cross-browser list runs this file once per engine (browser-engines.ts): the Chromium cases
+// run where Chromium is selected, the WebKit ones where WebKit is, so none runs twice.
+const engines = asked
+ ? selectedEngines(process.env.OPENBOT_APP_ENGINES)
+ : new Set();
+const chromiumAsked = engines.has("chromium");
+const webkitAsked = engines.has("webkit");
+const inChromium = test.skipIf(!chromiumAsked);
// A browser opens a page per case, and the arrow scrolls only while it is hovered.
setDefaultTimeout(20_000);
const shots = process.env.OPENBOT_APP_SHOTS;
@@ -128,6 +133,7 @@ beforeAll(async () => {
css = await stylesheet([
...new Set(sources.flatMap((source) => source.split(/[\s"'`{}]+/))),
]);
+ if (!chromiumAsked) return;
const { chromium } = await import("playwright-core");
// The CI job installs full Chromium without the headless shell.
browser = await chromium.launch({ channel: "chromium" });
@@ -246,14 +252,17 @@ async function shoot(page: Page, name: string) {
}
describe.skipIf(!asked)("a select with less room than its options", () => {
- test("is cut off at first, so the case is the one Sam saw", async () => {
- const page = await opened();
- expect(await showing(page, "Everything")).toBe(true);
- expect(await showing(page, "Nothing")).toBe(false);
- await page.close();
- });
+ inChromium(
+ "is cut off at first, so the case is the one Sam saw",
+ async () => {
+ const page = await opened();
+ expect(await showing(page, "Everything")).toBe(true);
+ expect(await showing(page, "Nothing")).toBe(false);
+ await page.close();
+ },
+ );
- test("its scroll-down arrow reaches the last option", async () => {
+ inChromium("its scroll-down arrow reaches the last option", async () => {
const page = await opened();
const arrow = page.locator('[data-slot="select-scroll-down-button"]');
await arrow.waitFor({ state: "visible", timeout: 3_000 });
@@ -264,42 +273,51 @@ describe.skipIf(!asked)("a select with less room than its options", () => {
await page.close();
});
- test("the wheel or trackpad reaches the last option, and pressing it chooses it", async () => {
- const page = await opened();
- await page.getByRole("option", { name: "Everything" }).hover();
- await page.mouse.wheel(0, 200);
- await scrolledTo(page, "Nothing");
- expect(await showing(page, "Nothing")).toBe(true);
- await page.getByRole("option", { name: "Nothing" }).click();
- await page.waitForFunction(() => document.body.dataset.chosen);
- expect(await page.evaluate(() => document.body.dataset.chosen)).toBe(
- "nothing",
- );
- await page.close();
- });
+ inChromium(
+ "the wheel or trackpad reaches the last option, and pressing it chooses it",
+ async () => {
+ const page = await opened();
+ await page.getByRole("option", { name: "Everything" }).hover();
+ await page.mouse.wheel(0, 200);
+ await scrolledTo(page, "Nothing");
+ expect(await showing(page, "Nothing")).toBe(true);
+ await page.getByRole("option", { name: "Nothing" }).click();
+ await page.waitForFunction(() => document.body.dataset.chosen);
+ expect(await page.evaluate(() => document.body.dataset.chosen)).toBe(
+ "nothing",
+ );
+ await page.close();
+ },
+ );
- test("the keyboard reaches the last option, shows it, and chooses it", async () => {
- const page = await opened();
- await page.keyboard.press("ArrowDown");
- await page.keyboard.press("ArrowDown");
- await scrolledTo(page, "Nothing");
- expect(await showing(page, "Nothing")).toBe(true);
- await page.keyboard.press("Enter");
- await page.waitForFunction(() => document.body.dataset.chosen);
- expect(await page.evaluate(() => document.body.dataset.chosen)).toBe(
- "nothing",
- );
- await page.close();
- });
+ inChromium(
+ "the keyboard reaches the last option, shows it, and chooses it",
+ async () => {
+ const page = await opened();
+ await page.keyboard.press("ArrowDown");
+ await page.keyboard.press("ArrowDown");
+ await scrolledTo(page, "Nothing");
+ expect(await showing(page, "Nothing")).toBe(true);
+ await page.keyboard.press("Enter");
+ await page.waitForFunction(() => document.body.dataset.chosen);
+ expect(await page.evaluate(() => document.body.dataset.chosen)).toBe(
+ "nothing",
+ );
+ await page.close();
+ },
+ );
- test("drawn over its control, it still scrolls to the last option", async () => {
- const page = await opened({ align: "trigger" });
- await page.getByRole("option", { name: "Everything" }).hover();
- await page.mouse.wheel(0, 200);
- await scrolledTo(page, "Nothing");
- expect(await showing(page, "Nothing")).toBe(true);
- await page.close();
- });
+ inChromium(
+ "drawn over its control, it still scrolls to the last option",
+ async () => {
+ const page = await opened({ align: "trigger" });
+ await page.getByRole("option", { name: "Everything" }).hover();
+ await page.mouse.wheel(0, 200);
+ await scrolledTo(page, "Nothing");
+ expect(await showing(page, "Nothing")).toBe(true);
+ await page.close();
+ },
+ );
// The arrow and the keyboard are two tests, each with its own page: together, with WebKit's first
// launch inside the first, they ran past the per-test time on a busy runner.
@@ -343,51 +361,57 @@ describe.skipIf(!asked)("a select with less room than its options", () => {
for (const skin of SKINS)
for (const theme of ["light", "dark"] as const)
- test(`under the ${skin} skin, ${theme}, the arrow reaches the last option on the popup's own color`, async () => {
- const page = await opened({ skin, theme });
- expect(
- await page.evaluate(() => document.documentElement.dataset.skin),
- ).toBe(skin);
- const arrow = page.locator('[data-slot="select-scroll-down-button"]');
- await arrow.waitFor({ state: "visible", timeout: 3_000 });
- const colors = await page.evaluate(() => {
- const popup = document.querySelector(
- '[data-slot="select-content"]',
- ) as HTMLElement;
- const down = popup.querySelector(
- '[data-slot="select-scroll-down-button"]',
- ) as HTMLElement;
- return [
- getComputedStyle(popup).backgroundColor,
- getComputedStyle(down).backgroundColor,
- ];
- });
- expect(colors[1]).toBe(colors[0]);
- await arrow.hover();
- await scrolledTo(page, "Nothing");
- expect(await showing(page, "Nothing")).toBe(true);
- await shoot(page, `arrow-${skin}-${theme}`);
- await page.close();
- });
+ inChromium(
+ `under the ${skin} skin, ${theme}, the arrow reaches the last option on the popup's own color`,
+ async () => {
+ const page = await opened({ skin, theme });
+ expect(
+ await page.evaluate(() => document.documentElement.dataset.skin),
+ ).toBe(skin);
+ const arrow = page.locator('[data-slot="select-scroll-down-button"]');
+ await arrow.waitFor({ state: "visible", timeout: 3_000 });
+ const colors = await page.evaluate(() => {
+ const popup = document.querySelector(
+ '[data-slot="select-content"]',
+ ) as HTMLElement;
+ const down = popup.querySelector(
+ '[data-slot="select-scroll-down-button"]',
+ ) as HTMLElement;
+ return [
+ getComputedStyle(popup).backgroundColor,
+ getComputedStyle(down).backgroundColor,
+ ];
+ });
+ expect(colors[1]).toBe(colors[0]);
+ await arrow.hover();
+ await scrolledTo(page, "Nothing");
+ expect(await showing(page, "Nothing")).toBe(true);
+ await shoot(page, `arrow-${skin}-${theme}`);
+ await page.close();
+ },
+ );
- test("in dark mode it looks the same, with its arrow on the popup's own color", async () => {
- const page = await opened({ theme: "dark" });
- const arrow = page.locator('[data-slot="select-scroll-down-button"]');
- await arrow.waitFor({ state: "visible", timeout: 3_000 });
- const colors = await page.evaluate(() => {
- const popup = document.querySelector(
- '[data-slot="select-content"]',
- ) as HTMLElement;
- const arrow = popup.querySelector(
- '[data-slot="select-scroll-down-button"]',
- ) as HTMLElement;
- return [
- getComputedStyle(popup).backgroundColor,
- getComputedStyle(arrow).backgroundColor,
- ];
- });
- expect(colors[1]).toBe(colors[0]);
- await shoot(page, "arrow-dark");
- await page.close();
- });
+ inChromium(
+ "in dark mode it looks the same, with its arrow on the popup's own color",
+ async () => {
+ const page = await opened({ theme: "dark" });
+ const arrow = page.locator('[data-slot="select-scroll-down-button"]');
+ await arrow.waitFor({ state: "visible", timeout: 3_000 });
+ const colors = await page.evaluate(() => {
+ const popup = document.querySelector(
+ '[data-slot="select-content"]',
+ ) as HTMLElement;
+ const arrow = popup.querySelector(
+ '[data-slot="select-scroll-down-button"]',
+ ) as HTMLElement;
+ return [
+ getComputedStyle(popup).backgroundColor,
+ getComputedStyle(arrow).backgroundColor,
+ ];
+ });
+ expect(colors[1]).toBe(colors[0]);
+ await shoot(page, "arrow-dark");
+ await page.close();
+ },
+ );
});
diff --git a/app/tests/sidebar-current-row.test.tsx b/app/tests/sidebar-current-row.test.tsx
index a60d3836c7..af7f010dfe 100644
--- a/app/tests/sidebar-current-row.test.tsx
+++ b/app/tests/sidebar-current-row.test.tsx
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { ownBrowsersAsked } from "./browser-engines";
import { still } from "./page-still";
/*
* A WebKit renderer crash under CI's load runs the test again (renderer-crash.ts). Found in CI on
@@ -36,7 +37,8 @@ import { test } from "./renderer-crash";
*
* With OPENBOT_APP_SHOTS= it also saves the strip on /invitations in each case.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/app/tests/sidebar-window-buttons.test.tsx b/app/tests/sidebar-window-buttons.test.tsx
index f6ca1986ba..e4a3ff3c27 100644
--- a/app/tests/sidebar-window-buttons.test.tsx
+++ b/app/tests/sidebar-window-buttons.test.tsx
@@ -1,13 +1,14 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type { Browser, BrowserType, Page } from "playwright-core";
+import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { ListConnectionsResponse } from "@/lib/api/generated/connections/connections.zod";
import { ListImportsResponse } from "@/lib/api/generated/moving-to-openbot-cloud/moving-to-openbot-cloud.zod";
import { GetPreferencesResponse } from "@/lib/api/generated/people/people.zod";
import { personBody } from "./accounts-api";
import { type AppsFixture, answerAppsApi } from "./apps-api";
+import { launchBrowserEngines } from "./browser-engines";
import { conversationPage } from "./conversations-api";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -31,8 +32,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/sidebar-window-buttons.test.tsx
*
- * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when
- * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves each case's corner, with
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit (the engine OpenBot Desktop's
+ * Mac window draws with) or both. With OPENBOT_APP_SHOTS= it saves each case's corner, with
* the buttons' area outlined, as sidebar-window-buttons--.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -373,11 +374,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- // The CI job installs full Chromium without the headless shell.
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
});
afterAll(async () => {
diff --git a/app/tests/sidebar-zoom-drag.test.tsx b/app/tests/sidebar-zoom-drag.test.tsx
index 4f84b9e62c..0dc7551b7f 100644
--- a/app/tests/sidebar-zoom-drag.test.tsx
+++ b/app/tests/sidebar-zoom-drag.test.tsx
@@ -1,9 +1,10 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type { Browser, BrowserType, Page } from "playwright-core";
+import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { personBody } from "./accounts-api";
+import { launchBrowserEngines } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -31,8 +32,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/sidebar-zoom-drag.test.tsx
*
- * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when
- * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves each case as
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both.
+ * With OPENBOT_APP_SHOTS= it saves each case as
* sidebar-zoom---.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -263,11 +264,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- // The CI job installs full Chromium without the headless shell.
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
});
afterAll(async () => {
diff --git a/app/tests/trusted-types-build.test.ts b/app/tests/trusted-types-build.test.ts
index cf2bbde318..78b6217852 100644
--- a/app/tests/trusted-types-build.test.ts
+++ b/app/tests/trusted-types-build.test.ts
@@ -14,6 +14,7 @@ import {
getGetArtifactResponseMock,
getGetArtifactVersionResponseMock,
} from "@/lib/api/generated/artifacts/artifacts.msw";
+import { ownBrowsersAsked } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -38,7 +39,8 @@ import { test } from "./renderer-crash";
* It runs `vite build` first (about a minute); OPENBOT_APP_DIST= uses a build already made.
* With OPENBOT_APP_SHOTS= each diagram is saved as tt-build--.png.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
const ORGANIZATION = "/api/v2/organizations/default";
diff --git a/app/tests/workspace-snapshots-layout.test.tsx b/app/tests/workspace-snapshots-layout.test.tsx
index 8e8c5a5d8e..241f5e4b00 100644
--- a/app/tests/workspace-snapshots-layout.test.tsx
+++ b/app/tests/workspace-snapshots-layout.test.tsx
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
+import { ownBrowsersAsked } from "./browser-engines";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -17,7 +18,8 @@ import { test } from "./renderer-crash";
*
* With OPENBOT_APP_SHOTS= it also saves each as copies---.png.
*/
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
+// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts).
+const asked = ownBrowsersAsked();
const shots = process.env.OPENBOT_APP_SHOTS;
const APP = join(import.meta.dir, "..");
diff --git a/desktop/src/setupLayout.approved.browser.test.ts b/desktop/src/setupLayout.approved.browser.test.ts
new file mode 100644
index 0000000000..7f637926ea
--- /dev/null
+++ b/desktop/src/setupLayout.approved.browser.test.ts
@@ -0,0 +1,2643 @@
+import { describe, expect, test } from "bun:test";
+import {
+ asked,
+ browser,
+ cloudBuilt,
+ DOCKER_STARTING,
+ emitProgress,
+ measure,
+ open,
+ type Page,
+ routeCalendar,
+ settled,
+ toTheAiStep,
+ withSetupWindow,
+} from "./setupLayout.browser.harness";
+
+/**
+ * The setup window's approved layouts, step by step, and the screens for an OpenBot this app is too
+ * old for. Part of the setup window's browser tests (setupLayout.browser.test.ts), in a file of its
+ * own so its job runs it beside the others.
+ *
+ * OPENBOT_APP_BROWSER=1 bun test src/setupLayout.approved.browser.test.ts
+ */
+withSetupWindow();
+
+/*
+ * 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 this app is too old for", () => {
+ const shots = process.env.OPENBOT_SHOTS_DIR;
+ const states: {
+ name: string;
+ at: string;
+ said: string;
+ way: { role: "button" | "link"; name: string };
+ /** The window's heading, where the state's screen is OpenBot on this computer running. */
+ heading?: 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-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",
+ 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" },
+ heading: "Update OpenBot",
+ },
+ // Found running by a launch that did not start it: the same screen as when Start finds it.
+ {
+ // Start refused: the release on this computer needs a newer launcher contract (launcherApi).
+ name: "local-launcher-ahead",
+ at: "#local-launcher-ahead",
+ 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-launcher-ahead-with-offer",
+ at: "?offer#local-launcher-ahead",
+ 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" },
+ heading: "Update OpenBot",
+ },
+ {
+ 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: "The OpenBot at openbot.example.com ended your sign-in.",
+ way: { role: "button", name: "Sign in again" },
+ },
+ // A launch offline with a saved sign-in: still opening, saying why, and reconnecting by
+ // itself, with the way to the first screen in view.
+ {
+ name: "connected-offline-reconnecting",
+ at: "#connect-offline",
+ said: "You're offline, or openbot.example.com isn't answering.",
+ way: { role: "button", name: "Stop reconnecting" },
+ },
+ // The window signed in at OpenBot's own address, and its page couldn't trade the browser's
+ // code for its session: the connect screen says which, with the way on.
+ {
+ name: "window-sign-in-expired",
+ at: "#connect-window-expired",
+ said: "Your sign-in at openbot.example.com didn't go through.",
+ way: { role: "button", name: "Sign in again" },
+ },
+ {
+ name: "window-sign-in-refused",
+ at: "#connect-window-refused",
+ said: "OpenBot couldn't sign you in at openbot.example.com.",
+ way: { role: "button", name: "Sign in again" },
+ },
+ {
+ name: "window-sign-in-unreachable",
+ at: "#connect-window-unreachable",
+ said: "OpenBot couldn't reach openbot.example.com.",
+ way: { role: "button", name: "Try 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);
+ // Running, so never "OpenBot is stopped" with a Start: Show OpenBot and Stop OpenBot.
+ if (state.heading) {
+ const screen = await page.evaluate(() => ({
+ heading: document.querySelector("h1")?.textContent?.trim(),
+ buttons: [...document.querySelectorAll("button")].map(
+ (button) => button.textContent?.trim(),
+ ),
+ }));
+ expect(screen.heading).toBe(state.heading);
+ expect(screen.buttons).not.toContain("Start OpenBot");
+ expect(screen.buttons).toContain("Show OpenBot");
+ expect(screen.buttons).toContain("Stop OpenBot");
+ }
+ // 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);
+ }
+ }
+
+ /*
+ * On a build that never updates itself, the line that says so is part of the notice, in the
+ * notice's type, on the connect screen as on the screen for the OpenBot on this computer. Seen on
+ * a Mac: on the connect screen it sat under the notice in body type.
+ */
+ for (const state of [
+ {
+ name: "connected-app-too-old-internal",
+ at: "?internal#connect-app-too-old",
+ said: "needs a newer version of this app. Update OpenBot, then connect again.",
+ },
+ {
+ name: "local-app-too-old-internal",
+ at: "?internal#local-app-too-old",
+ said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.",
+ },
+ ]) {
+ test(`${state.name}: "doesn't update itself" is in the notice, in the notice's type`, async () => {
+ for (const colorScheme of ["light", "dark"] as const) {
+ const page = await browser.newPage({
+ viewport: { width: 1000, height: 800 },
+ colorScheme,
+ });
+ try {
+ await open(page, state.at);
+ await page.getByText(state.said, { exact: false }).waitFor();
+ // The update's own line (Updates, folded under the buttons, says it too).
+ await page
+ .locator('p[role="status"]', { hasText: "doesn't update itself" })
+ .waitFor();
+ await page.waitForTimeout(1200);
+ const placed = await page.evaluate((said) => {
+ const notice = [...document.querySelectorAll(".local-alert")].find(
+ (element) => element.textContent?.includes(said),
+ );
+ const sentence = [...(notice?.querySelectorAll("p") ?? [])].find(
+ (element) => element.textContent?.includes(said),
+ );
+ const line = [
+ ...document.querySelectorAll('p[role="status"]'),
+ ].find((element) =>
+ element.textContent?.includes("doesn't update itself"),
+ );
+ const size = (element: Element | undefined) =>
+ element ? getComputedStyle(element).fontSize : null;
+ return {
+ inside: Boolean(notice && line && notice.contains(line)),
+ line: size(line),
+ notice: size(sentence),
+ updates: [...document.querySelectorAll("button")].filter(
+ (button) => button.textContent?.trim() === "Update and restart",
+ ).length,
+ };
+ }, state.said);
+ expect(placed.notice).not.toBeNull();
+ expect(placed).toEqual({
+ inside: true,
+ line: placed.notice,
+ notice: placed.notice,
+ updates: 0,
+ });
+ if (shots)
+ await page.screenshot({
+ path: `${shots}/${state.name}-${colorScheme}.png`,
+ });
+ } finally {
+ await page.close();
+ }
+ }
+ }, 30_000);
+ }
+});
+
+/** Approved account study: fixed heading, centered interaction and a top-safe scroll body. */
+describe.skipIf(!asked)("approved layout: account", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const) {
+ for (const colorScheme of ["light", "dark"] as const) {
+ test(`${width}x${height} ${colorScheme}: checking, code, engine wait and recovery remain reachable`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ const shot = async (state: string) => {
+ await settled(page);
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/account-${state}-${width}x${height}-${colorScheme}.png`,
+ });
+ };
+ const geometry = () =>
+ page.evaluate(() => {
+ const sheet =
+ document.querySelector(".account-layout")!;
+ const header = sheet
+ .querySelector(".setup-header-block")!
+ .getBoundingClientRect();
+ const title = sheet
+ .querySelector("h1")!
+ .getBoundingClientRect();
+ const body = sheet.querySelector(".setup-body")!;
+ const content = sheet
+ .querySelector(".setup-content")!
+ .getBoundingClientRect();
+ const box = body.getBoundingClientRect();
+ const rail = document
+ .querySelector(".rail-title")!
+ .getBoundingClientRect();
+ return {
+ titleY: title.y,
+ railY: rail.y,
+ headerBottom: header.bottom,
+ bodyTop: box.top,
+ bodyBottom: box.bottom,
+ bodyHeight: box.height,
+ contentTop: content.top,
+ contentBottom: content.bottom,
+ contentHeight: content.height,
+ centerOffset:
+ (content.top + content.bottom - box.top - box.bottom) / 2,
+ contentWidth: content.width,
+ bodyScroll: body.scrollHeight,
+ bodyClient: body.clientHeight,
+ pageHeight: document.documentElement.scrollHeight,
+ pageWidth: document.documentElement.scrollWidth,
+ horizontalOverflow: [
+ ...sheet.querySelectorAll(
+ ".setup-body, .setup-content, .setup-panel, .sign-in-wait, .sign-in-code-row",
+ ),
+ ].some(
+ (element) => element.scrollWidth > element.clientWidth + 1,
+ ),
+ };
+ });
+ // Scroll through the real body and check each action's center is unobstructed and focusable.
+ const reachable = async (selector: string) => {
+ const action = await page.evaluate((selector) => {
+ const element = document.querySelector(selector)!;
+ element.scrollIntoView({ block: "nearest" });
+ element.focus();
+ const box = element.getBoundingClientRect();
+ const body = element
+ .closest(".setup-body")!
+ .getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ box.x + box.width / 2,
+ box.y + box.height / 2,
+ );
+ return {
+ focused: document.activeElement === element,
+ hit: element === hit || element.contains(hit),
+ top: box.top,
+ bottom: box.bottom,
+ left: box.left,
+ right: box.right,
+ bodyTop: body.top,
+ bodyBottom: body.bottom,
+ };
+ }, selector);
+ expect(action.focused).toBe(true);
+ expect(action.hit).toBe(true);
+ expect(action.top).toBeGreaterThanOrEqual(action.bodyTop - 1);
+ expect(action.bottom).toBeLessThanOrEqual(action.bodyBottom + 1);
+ expect(action.left).toBeGreaterThanOrEqual(0);
+ expect(action.right).toBeLessThanOrEqual(width);
+ };
+ const check = async (titleY?: number) => {
+ const now = await geometry();
+ expect(now.pageHeight).toBeLessThanOrEqual(height);
+ expect(now.pageWidth).toBeLessThanOrEqual(width);
+ expect(now.horizontalOverflow).toBe(false);
+ expect(Math.abs(now.titleY - now.railY)).toBeLessThanOrEqual(1);
+ if (titleY !== undefined) expect(now.titleY).toBe(titleY);
+ expect(now.bodyTop).toBeGreaterThanOrEqual(now.headerBottom - 1);
+ expect(now.bodyBottom).toBeLessThanOrEqual(height);
+ expect(now.contentWidth).toBeLessThanOrEqual(600);
+ if (
+ now.contentHeight + (width === 1000 ? 60 : 36) <=
+ now.bodyHeight
+ ) {
+ if (width === 720) {
+ expect(
+ Math.abs(now.contentTop - now.bodyTop - 18),
+ ).toBeLessThanOrEqual(1);
+ } else {
+ expect(Math.abs(now.centerOffset)).toBeLessThanOrEqual(1);
+ expect(now.contentTop - now.headerBottom).toBeGreaterThan(29);
+ }
+ } else {
+ expect(now.bodyScroll).toBeGreaterThan(now.bodyClient);
+ }
+ return now;
+ };
+ try {
+ await open(page, "#signin");
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .waitFor();
+ await page.evaluate(() => {
+ globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
+ mode: "never",
+ });
+ globalThis.__workbench!.setAnswer("copilotkit_sign_in_page", {
+ mode: "value",
+ value: null,
+ });
+ });
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .click();
+ await page
+ .getByText("Checking your OpenBot account…", { exact: true })
+ .waitFor();
+ await shot("checking");
+ const initial = await check();
+ expect(await page.locator(".sign-in-wait h3").count()).toBe(0);
+ expect(
+ await page.locator(".sign-in-wait .step-spinner").count(),
+ ).toBe(1);
+ await reachable(".sign-in-wait button");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("copilotkit_sign_in_page", {
+ mode: "value",
+ value: {
+ url: "https://dashboard.copilotkit.ai/cli-auth/device?user_code=WXYZ-2345",
+ userCode: "WXYZ-2345",
+ },
+ }),
+ );
+ await page.getByText("WXYZ-2345", { exact: true }).waitFor();
+ await page.evaluate(() => {
+ document.querySelector(".setup-body")!.scrollTop = 0;
+ });
+ await shot("code");
+ await check(initial.titleY);
+ const code = await page.evaluate(() => {
+ const element =
+ document.querySelector(".sign-in-code")!;
+ const box = element.getBoundingClientRect();
+ const row = element.parentElement!.getBoundingClientRect();
+ const group = element.closest(".sign-in-wait")!;
+ const instruction = group.querySelector("h3")!;
+ const status = group.querySelector(".status-line")!;
+ return {
+ instruction: instruction.textContent,
+ status: status.textContent,
+ spinners: group.querySelectorAll(".step-spinner").length,
+ instructionSize: Number.parseFloat(
+ getComputedStyle(instruction).fontSize,
+ ),
+ statusSize: Number.parseFloat(getComputedStyle(status).fontSize),
+ instructionBottom: instruction.getBoundingClientRect().bottom,
+ statusTop: status.getBoundingClientRect().top,
+ statusBottom: status.getBoundingClientRect().bottom,
+ codeTop: row.top,
+ left: box.left,
+ right: box.right,
+ rowLeft: row.left,
+ rowRight: row.right,
+ width: element.scrollWidth,
+ client: element.clientWidth,
+ help: group.textContent?.includes("open the sign-in page again"),
+ actions: [...group.querySelectorAll("button, a")].map(
+ (el) => el.textContent,
+ ),
+ };
+ });
+ expect(code.instruction).toBe(
+ "Finish signing in to OpenBot in your browser…",
+ );
+ expect(code.status).toBe("Waiting for you to finish signing in…");
+ expect(code.spinners).toBe(1);
+ expect(code.instructionSize).toBeGreaterThan(code.statusSize);
+ expect(code.instructionBottom).toBeLessThanOrEqual(code.statusTop);
+ expect(code.statusBottom).toBeLessThanOrEqual(code.codeTop);
+ expect(code.left).toBeGreaterThanOrEqual(code.rowLeft);
+ expect(code.right).toBeLessThanOrEqual(code.rowRight);
+ expect(code.width).toBeLessThanOrEqual(code.client + 1);
+ expect(code.help).toBe(true);
+ expect(code.actions).toEqual(["Open the sign-in page", "Cancel"]);
+ await reachable(".sign-in-wait a");
+ await page
+ .getByRole("link", { name: "Open the sign-in page" })
+ .click();
+ expect(await page.evaluate(() => globalThis.__fake!.opened)).toEqual([
+ "https://dashboard.copilotkit.ai/cli-auth/device?user_code=WXYZ-2345",
+ ]);
+ await page.keyboard.press("Tab");
+ expect(
+ await page.evaluate(() => document.activeElement?.textContent),
+ ).toBe("Cancel");
+ await reachable(".sign-in-wait button");
+ // A failed browser approval retains a reachable retry, then starts a fresh attempt.
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
+ mode: "fail",
+ problem: { said: "Sign-in was interrupted." },
+ }),
+ );
+ await page
+ .getByText("Sign-in didn’t finish. Try again.", { exact: true })
+ .waitFor();
+ await shot("sign-in-failure");
+ await check(initial.titleY);
+ await reachable(".setup-panel .row button");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
+ mode: "never",
+ }),
+ );
+ await page
+ .getByRole("button", { name: "Try again", exact: true })
+ .click();
+ await page.getByText("WXYZ-2345", { exact: true }).waitFor();
+ await page
+ .getByRole("button", { name: "Cancel", exact: true })
+ .click();
+ await page
+ .getByRole("button", {
+ name: "Sign in for a free local license key",
+ })
+ .waitFor();
+ expect(
+ await page.evaluate(() =>
+ globalThis.__fake!.calls?.includes("cancel_local_eval"),
+ ),
+ ).toBe(true);
+ await page
+ .getByRole("button", {
+ name: "Sign in for a free local license key",
+ })
+ .click();
+ await page.getByText("WXYZ-2345", { exact: true }).waitFor();
+ await page.evaluate(() => {
+ globalThis.__workbench!.setAnswer("local_eval_terms", {
+ mode: "value",
+ value: { status: "engine-not-ready" },
+ });
+ globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
+ mode: "value",
+ value: { signedIn: true },
+ });
+ });
+ await page
+ .getByRole("heading", { name: "Setting up this computer" })
+ .waitFor();
+ await shot("engine-wait");
+ await check(initial.titleY);
+ expect(await page.locator(".sign-in-code").count()).toBe(0);
+ await page.evaluate(() => {
+ globalThis.__workbench!.setAnswer("connect_copilotkit_apps", {
+ mode: "fail",
+ problem: {
+ said:
+ "OpenBot couldn't connect your apps. " +
+ "Check the internet connection and the organization's sign-in settings before trying again. ".repeat(
+ 12,
+ ),
+ detail: "The connection was reset while connecting apps.",
+ },
+ });
+ globalThis.__workbench!.setAnswer("local_eval_terms", {
+ mode: "value",
+ value: { status: "not-required" },
+ });
+ });
+ await page
+ .getByRole("heading", { name: "Connect your apps" })
+ .waitFor();
+ await shot("long-failure");
+ await check(initial.titleY);
+ await reachable(".setup-panel .row button");
+ await page.keyboard.press("Tab");
+ expect(
+ await page.evaluate(() => document.activeElement?.textContent),
+ ).toBe("Continue");
+ await reachable(".setup-panel .row button.quiet");
+ await shot("failure-recovery");
+ await page
+ .getByRole("button", { name: "Continue", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Connect your AI" })
+ .waitFor();
+ } finally {
+ await page.close();
+ }
+ }, 30_000);
+ }
+ }
+});
+
+/** The approved agreement keeps the document, explanation, Read and Accept in one centered group. */
+describe.skipIf(!asked)("approved layout: agreement", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const) {
+ for (const colorScheme of ["dark", "light"] as const) {
+ test(`${width}x${height} ${colorScheme}: agreement is whole and centered`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ try {
+ await open(page, "#licence-installing");
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Accept the license agreement" })
+ .waitFor();
+ await settled(page);
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/license-${width}-${colorScheme}.png`,
+ });
+ const geometry = await page.evaluate(() => {
+ const sheet =
+ document.querySelector(".account-layout")!;
+ const bodyElement =
+ sheet.querySelector(".setup-body")!;
+ const body = bodyElement.getBoundingClientRect();
+ const panel = sheet.querySelector(".agreement-panel")!;
+ const box = panel.getBoundingClientRect();
+ const heading = sheet
+ .querySelector("h1")!
+ .getBoundingClientRect();
+ const rail = document
+ .querySelector(".rail-title")!
+ .getBoundingClientRect();
+ const link = panel
+ .querySelector("a")!
+ .parentElement!.getBoundingClientRect();
+ const action = panel
+ .querySelector("button")!
+ .getBoundingClientRect();
+ const icon = panel
+ .querySelector("svg")
+ ?.getBoundingClientRect();
+ const explanation = panel
+ .querySelector("p")!
+ .getBoundingClientRect();
+ const children = [
+ ...panel.querySelectorAll("p, a, button, svg"),
+ ].map((element) => element.getBoundingClientRect());
+ return {
+ narrowTopOffset:
+ box.top -
+ body.top -
+ Number.parseFloat(getComputedStyle(bodyElement).paddingTop),
+ panelWidth: box.width,
+ horizontalCenterOffset:
+ (box.left + box.right - body.left - body.right) / 2,
+ contentWhole: children.every(
+ (child) =>
+ child.left >= box.left &&
+ child.right <= box.right &&
+ child.top >= box.top &&
+ child.bottom <= box.bottom,
+ ),
+ iconWidth: icon?.width,
+ iconHeight: icon?.height,
+ iconDecorative: panel
+ .querySelector("svg")
+ ?.getAttribute("aria-hidden"),
+ iconVisibleBeforeExplanation:
+ !!icon &&
+ icon.width > 0 &&
+ icon.height > 0 &&
+ icon.bottom <= explanation.top,
+ explanationBeforeRead: explanation.bottom <= link.top,
+ pageWidth: document.documentElement.scrollWidth,
+ pageHeight: document.documentElement.scrollHeight,
+ headingOffset: heading.y - rail.y,
+ centerOffset: (box.top + box.bottom - body.top - body.bottom) / 2,
+ gap: action.top - link.bottom,
+ whole: box.top >= body.top && box.bottom <= body.bottom,
+ overflow: panel.scrollWidth > panel.clientWidth,
+ documentIcons: panel.querySelectorAll("svg").length,
+ explanationColor: getComputedStyle(
+ panel.querySelector("p")!,
+ ).color,
+ headingColor: getComputedStyle(
+ sheet.querySelector("h1")!,
+ ).color,
+ };
+ });
+ expect(geometry.pageWidth).toBeLessThanOrEqual(width);
+ expect(geometry.pageHeight).toBeLessThanOrEqual(height);
+ expect(Math.abs(geometry.headingOffset)).toBeLessThanOrEqual(1);
+ if (width === 720)
+ expect(Math.abs(geometry.narrowTopOffset)).toBeLessThanOrEqual(1);
+ else expect(Math.abs(geometry.centerOffset)).toBeLessThanOrEqual(1);
+ expect(geometry.gap).toBeCloseTo(24, 0);
+ expect(geometry.whole).toBe(true);
+ expect(geometry.overflow).toBe(false);
+ expect(geometry.panelWidth).toBeLessThanOrEqual(600);
+ expect(Math.abs(geometry.horizontalCenterOffset)).toBeLessThanOrEqual(
+ 1,
+ );
+ expect(geometry.contentWhole).toBe(true);
+ expect(geometry.explanationBeforeRead).toBe(true);
+ const acceptY = (await page
+ .getByRole("button", { name: "Accept", exact: true })
+ .boundingBox())!.y;
+ for (const progress of [
+ {
+ step: "images",
+ ok: true,
+ running: true,
+ detail: "Downloading OpenBot.",
+ downloads: {
+ done: 1,
+ total: 5,
+ bytes: 300_000_000,
+ size: 1_100_000_000,
+ bytesPerSecond: 9_000_000,
+ },
+ },
+ {
+ step: "engine",
+ ok: true,
+ running: true,
+ elsewhere: true,
+ detail: DOCKER_STARTING,
+ },
+ ]) {
+ await emitProgress(page, progress);
+ await settled(page);
+ expect(
+ (await page
+ .getByRole("button", { name: "Accept", exact: true })
+ .boundingBox())!.y,
+ ).toBe(acceptY);
+ }
+ await page.evaluate(() =>
+ (globalThis.__fake!.finishInstall as () => void)(),
+ );
+ await page
+ .getByText(/The rest of the install starts after you accept/)
+ .waitFor();
+ await settled(page);
+ expect(
+ (await page
+ .getByRole("button", { name: "Accept", exact: true })
+ .boundingBox())!.y,
+ ).toBe(acceptY);
+ // Reading never consents: the native legal URL is opened and Accept keeps keyboard order.
+ await page.evaluate(() =>
+ document
+ .querySelector(".agreement-panel a")!
+ .focus(),
+ );
+ await page.keyboard.press("Enter");
+ expect(await page.evaluate(() => globalThis.__fake!.opened)).toEqual([
+ "https://copilotkit.ai/legal/developer-edition",
+ ]);
+ expect(
+ await page.evaluate(() =>
+ globalThis
+ .__workbench!.calls()
+ .some((call) => call.command === "connect_copilotkit_apps"),
+ ),
+ ).toBe(false);
+ await page.keyboard.press("Tab");
+ expect(
+ await page.evaluate(() => document.activeElement?.textContent),
+ ).toBe("Accept");
+ const reachable = async (selector: string) => {
+ const seen = await page.evaluate((selector) => {
+ const element = document.querySelector(selector)!;
+ element.scrollIntoView({ block: "nearest" });
+ element.focus();
+ const box = element.getBoundingClientRect();
+ const body = element
+ .closest(".setup-body")!
+ .getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ box.x + box.width / 2,
+ box.y + box.height / 2,
+ );
+ return {
+ focused: document.activeElement === element,
+ hit: hit === element || element.contains(hit),
+ whole:
+ box.top >= body.top - 1 &&
+ box.bottom <= body.bottom + 1 &&
+ box.left >= 0 &&
+ box.right <= innerWidth,
+ };
+ }, selector);
+ expect(seen).toEqual({ focused: true, hit: true, whole: true });
+ };
+ await reachable(".agreement-panel button");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("connect_copilotkit_apps", {
+ mode: "fail",
+ problem: {
+ said:
+ "Connection failed. " +
+ "Check your connection and organization settings before trying again. ".repeat(
+ 40,
+ ),
+ detail: "Connection reset.",
+ },
+ }),
+ );
+ await page.keyboard.press("Enter");
+ await page
+ .getByRole("heading", { name: "Connect your apps" })
+ .waitFor();
+ await settled(page);
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/license-error-${width}-${colorScheme}.png`,
+ });
+ const recovery = await page.evaluate(() => {
+ const body = document.querySelector(
+ ".account-layout .setup-body",
+ )!;
+ return {
+ pageHeight: document.documentElement.scrollHeight,
+ pageWidth: document.documentElement.scrollWidth,
+ scrollable: body.scrollHeight > body.clientHeight,
+ bodyOverflow: body.scrollWidth > body.clientWidth,
+ headingY: document
+ .querySelector(".account-layout h1")!
+ .getBoundingClientRect().y,
+ railY: document
+ .querySelector(".rail-title")!
+ .getBoundingClientRect().y,
+ };
+ });
+ expect(recovery.pageHeight).toBeLessThanOrEqual(height);
+ expect(recovery.pageWidth).toBeLessThanOrEqual(width);
+ expect(recovery.bodyOverflow).toBe(false);
+ expect(recovery.scrollable).toBe(true);
+ expect(recovery.headingY).toBe(recovery.railY);
+ await reachable(".setup-panel .row button");
+ await page.keyboard.press("Tab");
+ expect(
+ await page.evaluate(() => document.activeElement?.textContent),
+ ).toBe("Continue");
+ await reachable(".setup-panel .row button.quiet");
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/license-recovery-${width}-${colorScheme}.png`,
+ });
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("connect_copilotkit_apps", {
+ mode: "value",
+ value: null,
+ }),
+ );
+ await page
+ .getByRole("button", { name: "Connect apps", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Connect your AI" })
+ .waitFor();
+ expect(
+ await page.evaluate(
+ () =>
+ globalThis
+ .__workbench!.calls()
+ .filter((call) => call.command === "connect_copilotkit_apps")
+ .length,
+ ),
+ ).toBe(2);
+ // Preserve the reference's visible document hierarchy; do not relax these for missing source styling.
+ expect(geometry.documentIcons).toBe(1);
+ expect(geometry.iconVisibleBeforeExplanation).toBe(true);
+ expect(geometry.iconWidth).toBe(28);
+ expect(geometry.iconHeight).toBe(28);
+ expect(geometry.iconDecorative).toBe("true");
+ expect(geometry.explanationColor).toBe(geometry.headingColor);
+ } finally {
+ await page.close();
+ }
+ }, 30_000);
+ }
+ }
+});
+
+/** Authentication scrolls independently of the selected identity and Continue. */
+describe.skipIf(!asked)("approved layout: provider", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const) {
+ for (const colorScheme of ["dark", "light"] as const) {
+ test(`${width}x${height} ${colorScheme}: waiting, error, key, endpoint and signed frames`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ const shot = async (state: string) => {
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/provider-${width}-${colorScheme}-${state}.png`,
+ });
+ };
+ const geometry = () =>
+ page.evaluate(() => {
+ const sheet =
+ document.querySelector(".provider-layout")!;
+ const body = sheet.querySelector(".setup-body")!;
+ const panel = body.querySelector(".chosen-provider")!;
+ const identity = sheet.querySelector(
+ ":scope > .setup-provider-identity",
+ )!;
+ const footer = sheet.querySelector(".setup-footer")!;
+ const action =
+ footer.querySelector("button:last-child")!;
+ const b = body.getBoundingClientRect(),
+ p = panel.getBoundingClientRect(),
+ i = identity.getBoundingClientRect(),
+ f = footer.getBoundingClientRect(),
+ a = action.getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ a.x + a.width / 2,
+ a.y + a.height / 2,
+ );
+ return {
+ pageWidth: document.documentElement.scrollWidth,
+ pageHeight: document.documentElement.scrollHeight,
+ bodyBottom: b.bottom,
+ footerTop: f.top,
+ actionY: a.y,
+ actionWhole: a.y >= 0 && a.bottom <= innerHeight,
+ actionHit: !!hit && action.contains(hit),
+ identity: { x: i.x, y: i.y, width: i.width, height: i.height },
+ identityOutsideScroller: identity.parentElement === sheet,
+ bodyOverflow: body.scrollWidth > body.clientWidth,
+ panelWidth: p.width,
+ leftOffset: p.left - b.left,
+ topOffset:
+ p.top -
+ b.top -
+ Number.parseFloat(getComputedStyle(body).paddingTop),
+ };
+ });
+ let baseline: Awaited> | undefined;
+ const check = async () => {
+ const now = await geometry();
+ expect(now.pageWidth).toBeLessThanOrEqual(width);
+ expect(now.pageHeight).toBeLessThanOrEqual(height);
+ expect(now.bodyBottom).toBeLessThanOrEqual(now.footerTop + 1);
+ expect(now.actionWhole).toBe(true);
+ expect(now.actionHit).toBe(true);
+ expect(now.identityOutsideScroller).toBe(true);
+ expect(now.bodyOverflow).toBe(false);
+ expect(now.panelWidth).toBeLessThanOrEqual(600);
+ expect(Math.abs(now.leftOffset)).toBeLessThanOrEqual(1);
+ if (baseline) {
+ expect(
+ Math.abs(now.actionY - baseline.actionY),
+ ).toBeLessThanOrEqual(1);
+ expect(now.identity).toEqual(baseline.identity);
+ }
+ return now;
+ };
+ const reach = async (selector: string) => {
+ expect(
+ await page.evaluate((selector) => {
+ const element = document.querySelector(selector)!;
+ element.focus();
+ element.scrollIntoView({ block: "nearest" });
+ const b = element.getBoundingClientRect(),
+ body = element
+ .closest(".setup-body")!
+ .getBoundingClientRect();
+ // An inline link can wrap. Hit a real line box, rather than the empty center
+ // of its enclosing bounding rectangle between two lines.
+ const point = element.getClientRects()[0] ?? b;
+ const hit = document.elementFromPoint(
+ point.x + point.width / 2,
+ point.y + point.height / 2,
+ );
+ return {
+ focused: document.activeElement === element,
+ whole: b.top >= body.top - 1 && b.bottom <= body.bottom + 1,
+ hit: !!hit && element.contains(hit),
+ };
+ }, selector),
+ ).toEqual({ focused: true, whole: true, hit: true });
+ await check();
+ };
+ try {
+ await open(page);
+ await page.getByRole("heading", { name: "Set up OpenBot" }).waitFor();
+ await page.evaluate(async () => {
+ const catalogue = (await globalThis.__workbench!.call(
+ "providers",
+ )) as { id: string; caution: unknown }[];
+ globalThis.__workbench!.setAnswer("providers", {
+ mode: "value",
+ value: catalogue.map((row) =>
+ row.id === "anthropic"
+ ? {
+ ...row,
+ caution: {
+ says: "A Claude plan carries a separate monthly pool of Agent SDK credits. When that pool is empty, Bots stop until it renews or you add API credits.",
+ reads_more_at: "https://openbot.test/plan-credits",
+ },
+ }
+ : row,
+ ),
+ });
+ globalThis.__workbench!.setAnswer("begin_claude_sign_in", {
+ mode: "value",
+ value: "https://openbot.test/approve",
+ });
+ globalThis.__workbench!.setAnswer("finish_claude_sign_in", {
+ mode: "never",
+ });
+ });
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Connect your AI" })
+ .waitFor();
+ await page.getByText("Anthropic", { exact: true }).click();
+ await settled(page);
+ baseline = await check();
+ await shot("long-caution");
+ await page
+ .getByRole("button", {
+ name: "Sign in with Anthropic",
+ exact: true,
+ })
+ .click();
+ await page
+ .getByText("Waiting for you to approve it…", { exact: true })
+ .waitFor();
+ await settled(page);
+ await page.evaluate(() => {
+ document.querySelector(
+ ".provider-layout .setup-body",
+ )!.scrollTop = 0;
+ });
+ const waiting = await check();
+ // Read from the top at every size, so the tab row stays where it is as the panel changes.
+ expect(Math.abs(waiting.topOffset)).toBeLessThanOrEqual(1);
+ await shot("waiting");
+ // The initial narrow view must say what is happening before the fallback link.
+ const waitingStatus = await page
+ .getByText("Waiting for you to approve it…", { exact: true })
+ .boundingBox();
+ expect(waitingStatus).not.toBeNull();
+ expect(waitingStatus!.y).toBeGreaterThanOrEqual(
+ waiting.identity.y + waiting.identity.height,
+ );
+ expect(waitingStatus!.y + waitingStatus!.height).toBeLessThanOrEqual(
+ waiting.bodyBottom + 1,
+ );
+ await reach(".chosen-provider .caution a");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("finish_claude_sign_in", {
+ mode: "fail",
+ problem: {
+ said: "OpenBot could not finish signing in. Check your connection and try again.",
+ detail:
+ "The sign-in service could not be reached. Try signing in again after the connection is restored.",
+ },
+ }),
+ );
+ await page
+ .getByText(
+ "OpenBot could not finish signing in. Check your connection and try again.",
+ { exact: true },
+ )
+ .waitFor();
+ await settled(page);
+ await check();
+ await shot("error");
+ await page
+ .getByRole("tab", { name: "Use an API key", exact: true })
+ .click();
+ await page
+ .getByLabel("Anthropic API key", { exact: true })
+ .fill("test-provider-key");
+ await settled(page);
+ await reach("#key");
+ await shot("api-key");
+ let continueFocused = false;
+ for (let n = 0; n < 12 && !continueFocused; n++) {
+ await page.keyboard.press("Tab");
+ continueFocused = await page.evaluate(
+ () =>
+ document.activeElement ===
+ document.querySelector(
+ ".setup-footer button:last-child",
+ ),
+ );
+ }
+ expect(continueFocused).toBe(true);
+ await check();
+ await page
+ .getByRole("button", { name: "Choose a different provider" })
+ .click();
+ await page
+ .getByText("Any OpenAI-compatible endpoint", { exact: true })
+ .click();
+ await page
+ .getByLabel("Base URL", { exact: true })
+ .fill("https://models.example.test/v1");
+ await page
+ .getByText("Advanced compatible endpoint options", { exact: true })
+ .click();
+ await page
+ .getByLabel("Container Base URL, if different", { exact: true })
+ .fill("http://model:11434/v1");
+ await page
+ .getByLabel("Model name", { exact: true })
+ .fill("test-model");
+ await settled(page);
+ const endpoint = await geometry();
+ expect(
+ Math.abs(endpoint.actionY - baseline.actionY),
+ ).toBeLessThanOrEqual(1);
+ baseline = endpoint;
+ for (const selector of [
+ "#base",
+ "#container-base",
+ "#model",
+ "#ekey",
+ ])
+ await reach(selector);
+ await shot("endpoint");
+ const beforeDownload = await measure(page);
+ await page.evaluate(() => {
+ globalThis.__fake!.download = {
+ done: 400_000_000,
+ total: 1_600_000_000,
+ };
+ });
+ await page.getByText("400.0 MB of 1.6 GB").waitFor();
+ expect(await measure(page)).toEqual(beforeDownload);
+ await check();
+ await page.evaluate(() => {
+ globalThis.__fake!.download = null;
+ });
+ await page
+ .getByText("400.0 MB of 1.6 GB")
+ .waitFor({ state: "hidden" });
+ expect(await measure(page)).toEqual(beforeDownload);
+ await page.evaluate(() =>
+ (
+ globalThis.__fake as unknown as { finishSetUp(): void }
+ ).finishSetUp(),
+ );
+ await page
+ .getByText("OpenBot is installed", { exact: true })
+ .waitFor();
+ expect(await measure(page)).toEqual(beforeDownload);
+ await check();
+ await page
+ .getByRole("button", { name: "Choose a different provider" })
+ .click();
+ await page.getByText("Anthropic", { exact: true }).click();
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("finish_claude_sign_in", {
+ mode: "never",
+ }),
+ );
+ await page
+ .getByRole("button", {
+ name: "Sign in with Anthropic",
+ exact: true,
+ })
+ .click();
+ await page
+ .getByText("Waiting for you to approve it…", { exact: true })
+ .waitFor();
+ await settled(page);
+ baseline = await geometry();
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("finish_claude_sign_in", {
+ mode: "value",
+ value: "test-provider-token",
+ }),
+ );
+ await page
+ .getByText("Signed in to Anthropic.", { exact: false })
+ .waitFor();
+ await check();
+ await shot("signed");
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+ }
+ }
+});
+describe.skipIf(!asked)("approved layout: install", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const) {
+ for (const colorScheme of ["light", "dark"] as const) {
+ test(`${width}x${height} ${colorScheme}: download, unpack, prompt, failure and completion`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ const emit = (payload: Record) =>
+ page.evaluate(
+ (payload) =>
+ globalThis.__workbench!.emit("setup:progress", payload),
+ payload,
+ );
+ const shot = async (state: string) => {
+ await settled(page);
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/install-${width}-${colorScheme}-${state}.png`,
+ });
+ };
+ const geometry = () =>
+ page.evaluate(() => {
+ const sheet =
+ document.querySelector(".install-layout")!;
+ const body = sheet.querySelector(".setup-body")!;
+ const content = body.querySelector(".setup-content")!;
+ const footer = sheet.querySelector(".setup-footer")!;
+ const header = sheet.querySelector(
+ ".setup-header-block",
+ )!;
+ const b = body.getBoundingClientRect(),
+ c = content.getBoundingClientRect(),
+ f = footer.getBoundingClientRect(),
+ h = header.getBoundingClientRect();
+ const rows = [
+ ...sheet.querySelectorAll(
+ ".setup-progress-focus > .step",
+ ),
+ ];
+ return {
+ pageWidth: document.documentElement.scrollWidth,
+ pageHeight: document.documentElement.scrollHeight,
+ horizontalOverflow: [body, content, ...rows].some(
+ (e) => e.scrollWidth > e.clientWidth + 1,
+ ),
+ headerBottom: h.bottom,
+ bodyTop: b.top,
+ bodyBottom: b.bottom,
+ bodyHeight: b.height,
+ footerTop: f.top,
+ footerBottom: f.bottom,
+ contentWidth: c.width,
+ contentHeight: c.height,
+ centerX: (c.left + c.right - b.left - b.right) / 2,
+ centerY: (c.top + c.bottom - b.top - b.bottom) / 2,
+ topOffset:
+ c.top +
+ body.scrollTop -
+ b.top -
+ Number.parseFloat(getComputedStyle(body).paddingTop),
+ rows: rows.map((row) => ({
+ label: row.getAttribute("aria-label"),
+ top: row.getBoundingClientRect().top,
+ current: !!row.querySelector(
+ ".mark.active, .mark.waiting, .mark.bad",
+ ),
+ labelSize: Number.parseFloat(
+ getComputedStyle(
+ row.querySelector(".step-label")!,
+ ).fontSize,
+ ),
+ background: getComputedStyle(row).backgroundColor,
+ border: Number.parseFloat(
+ getComputedStyle(row).borderRightWidth,
+ ),
+ })),
+ };
+ });
+ const check = async () => {
+ await settled(page);
+ const now = await geometry();
+ expect(now.pageWidth).toBeLessThanOrEqual(width);
+ expect(now.pageHeight).toBeLessThanOrEqual(height);
+ expect(now.horizontalOverflow).toBe(false);
+ expect(now.bodyTop).toBeGreaterThanOrEqual(now.headerBottom - 1);
+ expect(now.bodyBottom).toBeLessThanOrEqual(now.footerTop + 1);
+ expect(now.footerBottom).toBeLessThanOrEqual(height);
+ expect(now.contentWidth).toBeLessThanOrEqual(600);
+ expect(Math.abs(now.centerX)).toBeLessThanOrEqual(1);
+ if (width === 1000 && now.contentHeight + 60 <= now.bodyHeight)
+ expect(Math.abs(now.centerY)).toBeLessThanOrEqual(1);
+ if (width === 720)
+ expect(Math.abs(now.topOffset)).toBeLessThanOrEqual(1);
+ const current = now.rows.findIndex((row) => row.current);
+ if (current >= 0) expect(current).toBe(0);
+ if (now.rows.length > 1 && now.rows[0]?.current) {
+ expect(now.rows[0].labelSize).toBeGreaterThan(
+ now.rows[1]!.labelSize,
+ );
+ expect(now.rows[0].border).toBe(0);
+ expect(now.rows[1]!.border).toBe(0);
+ expect(now.rows[1]!.top).toBeGreaterThan(now.rows[0].top);
+ }
+ return now;
+ };
+ const reach = async (label: string) => {
+ // Use actual Tab navigation; programmatic focus alone does not establish keyboard reachability.
+ let focused = false;
+ for (let n = 0; n < 30 && !focused; n++) {
+ await page.keyboard.press("Tab");
+ focused = await page.evaluate(
+ (label) => document.activeElement?.textContent?.trim() === label,
+ label,
+ );
+ }
+ expect(focused).toBe(true);
+ expect(
+ await page.evaluate((label) => {
+ const element = [
+ ...document.querySelectorAll(
+ ".install-layout button",
+ ),
+ ].find((e) => e.textContent?.trim() === label)!;
+ const r = element.getBoundingClientRect(),
+ hit = document.elementFromPoint(
+ r.x + r.width / 2,
+ r.y + r.height / 2,
+ );
+ const container = element
+ .closest(".setup-body, .setup-footer")!
+ .getBoundingClientRect();
+ return {
+ hit: !!hit && element.contains(hit),
+ visible:
+ r.top >= container.top - 1 &&
+ r.bottom <= container.bottom + 1 &&
+ r.bottom <= innerHeight &&
+ r.left >= 0 &&
+ r.right <= innerWidth,
+ enabled: !element.disabled,
+ };
+ }, label),
+ ).toEqual({ hit: true, visible: true, enabled: true });
+ };
+ try {
+ await open(page, "#licence-installing");
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .waitFor();
+ await page.evaluate(() => {
+ globalThis.__workbench!.setAnswer("prepare_installation", {
+ mode: "never",
+ });
+ globalThis.__workbench!.setAnswer("allow_podman_install", {
+ mode: "value",
+ value: true,
+ });
+ globalThis.__workbench!.setAnswer("set_up_local_eval", {
+ mode: "never",
+ });
+ });
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .click();
+ await page
+ .getByRole("button", { name: "Accept", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Installing OpenBot", exact: true })
+ .waitFor();
+ await emit({
+ step: "engine",
+ ok: true,
+ running: false,
+ detail: "The software OpenBot runs on is ready.",
+ });
+ await emit({
+ step: "images",
+ ok: true,
+ running: true,
+ detail: "Downloading local software.",
+ downloads: {
+ bytes: 568_900_000,
+ size: 872_800_000,
+ done: 2,
+ total: 5,
+ bytesPerSecond: 9_000_000,
+ },
+ });
+ await page
+ .getByText("568.9 MB of 872.8 MB", { exact: false })
+ .waitFor();
+ const download = await check();
+ expect(download.rows[0]?.label).toBe("Downloading OpenBot");
+ expect(download.rows[1]?.label).toBe("Preparing this computer");
+ expect(
+ await page
+ .getByRole("button", { name: "Cancel", exact: true })
+ .count(),
+ ).toBe(0);
+ await shot("download");
+ await emit({
+ step: "images",
+ ok: true,
+ running: true,
+ detail: "Unpacking local software.",
+ downloads: {
+ bytes: 872_800_000,
+ size: 872_800_000,
+ done: 2,
+ total: 5,
+ },
+ });
+ await page
+ .getByText("Unpacking OpenBot (3 of 5).", { exact: false })
+ .waitFor();
+ await check();
+ await shot("unpack");
+ // Before macOS's password prompt: why, and Continue, in reach at every size. The prompt
+ // comes only on Continue.
+ await emit({
+ step: "install-engine",
+ ok: true,
+ running: true,
+ asks: true,
+ beforePrompt: true,
+ detail:
+ "OpenBot needs to install the software it runs on. Choose Continue, then enter your Mac password when your Mac asks for it.",
+ });
+ await page
+ .getByRole("region", {
+ name: "Your Mac will ask for your password",
+ })
+ .waitFor();
+ await check();
+ await reach("Continue");
+ await shot("before-prompt");
+ await page
+ .getByRole("button", { name: "Continue", exact: true })
+ .click();
+ expect(
+ await page.evaluate(
+ () =>
+ globalThis
+ .__workbench!.calls()
+ .filter((c) => c.command === "allow_podman_install").length,
+ ),
+ ).toBe(1);
+ const asking =
+ "OpenBot needs your password to install what it needs to run. Try again to open the password prompt.";
+ await emit({
+ step: "install-engine",
+ ok: true,
+ running: true,
+ asks: true,
+ detail: asking,
+ });
+ await page
+ .getByRole("region", { name: "Your password is needed" })
+ .waitFor();
+ await check();
+ await reach("Try again");
+ await shot("prompt");
+ await page
+ .getByRole("button", { name: "Try again", exact: true })
+ .click();
+ expect(
+ await page.evaluate(
+ () =>
+ globalThis
+ .__workbench!.calls()
+ .filter((c) => c.command === "allow_podman_install").length,
+ ),
+ ).toBe(2);
+ await emit({
+ step: "install-engine",
+ ok: true,
+ running: false,
+ detail: "Ready.",
+ });
+ await emit({
+ step: "images",
+ ok: false,
+ running: false,
+ detail: "The download was interrupted.",
+ });
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("prepare_installation", {
+ mode: "fail",
+ problem: {
+ said: "The download was interrupted. Check your internet connection and retry installation.",
+ detail: "Connection reset while downloading OpenBot.",
+ },
+ }),
+ );
+ await page
+ .getByRole("button", { name: "Retry installation", exact: true })
+ .waitFor();
+ await check();
+ await reach("Back");
+ await reach("Retry installation");
+ await shot("failure");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("prepare_installation", {
+ mode: "value",
+ value: null,
+ }),
+ );
+ await page
+ .getByRole("button", { name: "Retry installation", exact: true })
+ .click();
+ // Successful installation advances automatically to AI, preserving the real flow.
+ await page
+ .getByRole("heading", { name: "Connect your AI" })
+ .waitFor();
+ await shot("complete");
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+ }
+ }
+});
+
+describe.skipIf(!asked)("approved layout: finishing", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const)
+ for (const colorScheme of ["light", "dark"] as const)
+ test(`${width}x${height} ${colorScheme}: current phases, cancellation and reachable recovery`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ const shot = async (state: string) => {
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/finish-${width}-${colorScheme}-${state}.png`,
+ });
+ };
+ const geometry = () =>
+ page.evaluate(() => {
+ const sheet =
+ document.querySelector(".finishing-layout")!;
+ const body = sheet.querySelector(".setup-body")!;
+ const content = body.querySelector(".setup-content")!;
+ const footer = sheet.querySelector(
+ ":scope > .setup-footer",
+ )!;
+ const checkbox = footer.querySelector(
+ 'input[type="checkbox"]',
+ )!;
+ const b = body.getBoundingClientRect(),
+ c = content.getBoundingClientRect(),
+ f = footer.getBoundingClientRect(),
+ a = checkbox.getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ a.x + a.width / 2,
+ a.y + a.height / 2,
+ );
+ const memory = globalThis as unknown as {
+ finishingConsent?: Element;
+ };
+ memory.finishingConsent ??= checkbox;
+ return {
+ sameConsent: memory.finishingConsent === checkbox,
+ settingsReads: globalThis
+ .__workbench!.calls()
+ .filter(
+ (call) =>
+ call.command === "plugin:openbot-desktop|usage_data",
+ ).length,
+ pageWidth: document.documentElement.scrollWidth,
+ pageHeight: document.documentElement.scrollHeight,
+ horizontalOverflow: body.scrollWidth > body.clientWidth,
+ bodyBottom: b.bottom,
+ footerTop: f.top,
+ checkbox: { x: a.x, y: a.y },
+ checkboxWhole: a.top >= 0 && a.bottom <= innerHeight,
+ checkboxHit: hit === checkbox,
+ contentWidth: c.width,
+ centerX: (c.left + c.right - b.left - b.right) / 2,
+ centerY: (c.top + c.bottom - b.top - b.bottom) / 2,
+ topOffset:
+ c.top -
+ b.top +
+ body.scrollTop -
+ Number.parseFloat(getComputedStyle(body).paddingTop),
+ fits: body.scrollHeight <= body.clientHeight + 1,
+ spinners: sheet.querySelectorAll(".step-spinner").length,
+ journey: sheet.querySelectorAll(".journey").length,
+ milestones: [
+ ...sheet.querySelectorAll(".setup-milestones > .step"),
+ ].map((row) => ({
+ running: row.querySelector(".step-spinner") !== null,
+ text: row.textContent ?? "",
+ })),
+ };
+ });
+ let consent: { x: number; y: number } | undefined;
+ let settingsReads: number | undefined;
+ const check = async (journey: boolean, state: string) => {
+ await settled(page);
+ const now = await geometry();
+ expect(now.sameConsent).toBe(true);
+ if (settingsReads === undefined) settingsReads = now.settingsReads;
+ expect(now.settingsReads).toBe(settingsReads);
+ expect(now.settingsReads).toBeGreaterThan(0);
+ expect(now.pageWidth).toBeLessThanOrEqual(width);
+ expect(now.pageHeight).toBeLessThanOrEqual(height);
+ expect(now.horizontalOverflow).toBe(false);
+ expect(now.bodyBottom).toBeLessThanOrEqual(now.footerTop + 1);
+ expect(now.checkboxWhole).toBe(true);
+ expect(now.checkboxHit).toBe(true);
+ expect(now.contentWidth).toBeLessThanOrEqual(600);
+ expect(Math.abs(now.centerX)).toBeLessThanOrEqual(1);
+ if (width === 720)
+ expect(Math.abs(now.topOffset)).toBeLessThanOrEqual(1);
+ else if (now.fits)
+ expect(Math.abs(now.centerY)).toBeLessThanOrEqual(1);
+ if (consent) expect(now.checkbox).toEqual(consent);
+ else consent = now.checkbox;
+ expect(now.journey).toBe(journey ? 1 : 0);
+ expect(now.spinners).toBe(journey ? 1 : 0);
+ if (journey)
+ for (const row of now.milestones) {
+ expect(row.running).toBe(false);
+ expect(row.text).not.toMatch(/Failed|Waiting|Paused/);
+ expect(row.text).toContain("Complete");
+ }
+ await page.evaluate(() => {
+ document.querySelector(
+ ".finishing-layout .setup-body",
+ )!.scrollTop = 0;
+ });
+ await shot(state);
+ };
+ const reach = async (name: string) => {
+ const button = page
+ .locator(".finishing-layout")
+ .getByRole("button", { name, exact: true });
+ await button.waitFor();
+ const result = await page.evaluate((name) => {
+ const button = [
+ ...document.querySelectorAll(
+ ".finishing-layout button",
+ ),
+ ].find((button) => button.textContent?.trim() === name)!;
+ button.scrollIntoView({ block: "nearest" });
+ button.focus();
+ const a = button.getBoundingClientRect();
+ const body = button
+ .closest(".setup-body")!
+ .getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ a.x + a.width / 2,
+ a.y + a.height / 2,
+ );
+ return {
+ focused: document.activeElement === button,
+ whole: a.top >= body.top - 1 && a.bottom <= body.bottom + 1,
+ hit: hit !== null && button.contains(hit),
+ };
+ }, name);
+ expect(result).toEqual({ focused: true, whole: true, hit: true });
+ };
+ const releaseSetup = async () =>
+ page.evaluate(() => (globalThis.__fake!.finishSetUp as () => void)());
+ const hold = async (command: string) =>
+ page.evaluate(
+ (command) =>
+ globalThis.__workbench!.setAnswer(command, { mode: "never" }),
+ command,
+ );
+ try {
+ await toTheAiStep(page);
+ await hold("connect_local_eval");
+ await hold("run_local_eval");
+ await hold("start_stack");
+ await page.getByText("Anthropic", { exact: true }).click();
+ await page
+ .getByRole("tab", { name: "Use an API key", exact: true })
+ .click();
+ await page
+ .getByLabel("Anthropic API key", { exact: true })
+ .fill("a-key-for-this-test");
+ await page
+ .getByRole("button", { name: "Continue", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Finishing setup" })
+ .waitFor();
+ await page.locator(".journey").waitFor();
+ await check(true, "setup");
+ await reach("Cancel");
+ await page
+ .getByRole("button", { name: "Cancel", exact: true })
+ .click();
+ await reach("Retry");
+ await check(false, "cancelled");
+ expect(
+ await page.evaluate(() =>
+ globalThis
+ .__workbench!.calls()
+ .some((call) => call.command === "cancel_local_eval"),
+ ),
+ ).toBe(true);
+ await page
+ .getByRole("button", { name: "Retry", exact: true })
+ .click();
+ await page.locator(".journey").waitFor();
+ await check(true, "setup-retry");
+ await releaseSetup();
+ await page
+ .getByText("Connecting OpenBot to its services", { exact: true })
+ .waitFor();
+ await check(true, "connect");
+ // Use recorded setup report instead of calling the paused run_local_eval command.
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("connect_local_eval", {
+ mode: "value",
+ value: {
+ outcome: "completed",
+ stack: { id: "local-abc123" },
+ reason: null,
+ conflicted: false,
+ },
+ }),
+ );
+ await page
+ .getByRole("listitem", { name: "Connecting OpenBot", exact: true })
+ .waitFor();
+ await check(true, "wait");
+ await reach("Cancel");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("run_local_eval", {
+ mode: "value",
+ value: {
+ outcome: "completed",
+ stack: {
+ id: "local-abc123",
+ installedRelease: "0.16.0-rc.10",
+ step: "ready",
+ urls: {
+ api: "http://127.0.0.1:64770",
+ dashboard: "http://127.0.0.1:64771",
+ gateway: "ws://127.0.0.1:64772",
+ },
+ hasFailedStep: false,
+ updateInProgress: false,
+ unfinishedUpdate: null,
+ observed: null,
+ },
+ reason: null,
+ readiness: "ready",
+ licence: "valid",
+ licenceExpiresAt: null,
+ checksPassed: false,
+ },
+ }),
+ );
+ await page.locator(".cannot-cancel").waitFor();
+ expect(
+ await page
+ .getByRole("button", { name: "Cancel", exact: true })
+ .count(),
+ ).toBe(0);
+ expect(await page.locator(".cannot-cancel").textContent()).toContain(
+ "half started",
+ );
+ await check(true, "start");
+ // Exercise a real failure and Retry from the native Start call.
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("start_stack", {
+ mode: "fail",
+ problem: {
+ said: "OpenBot could not start. Retry, and copy the logs if it stops again.",
+ },
+ }),
+ );
+ await reach("Retry");
+ const logActions = await page.evaluate(() =>
+ [...document.querySelectorAll(".finishing-layout button")]
+ .filter((button) =>
+ ["Copy logs", "Save to a file"].includes(
+ button.textContent?.trim() ?? "",
+ ),
+ )
+ .map((button) => button.textContent?.trim()),
+ );
+ // Check every offered log action before the exact-count assertion below.
+ const logsReachable = await page.evaluate(() =>
+ [
+ ...document.querySelectorAll(
+ ".finishing-layout button",
+ ),
+ ]
+ .filter((button) =>
+ ["Copy logs", "Save to a file"].includes(
+ button.textContent?.trim() ?? "",
+ ),
+ )
+ .map((button) => {
+ button.scrollIntoView({ block: "nearest" });
+ button.focus();
+ const a = button.getBoundingClientRect(),
+ b = button
+ .closest(".setup-body")!
+ .getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ a.x + a.width / 2,
+ a.y + a.height / 2,
+ );
+ return {
+ focused: document.activeElement === button,
+ whole: a.top >= b.top - 1 && a.bottom <= b.bottom + 1,
+ hit: !!hit && button.contains(hit),
+ };
+ }),
+ );
+ for (const reachable of logsReachable)
+ expect(reachable).toEqual({
+ focused: true,
+ whole: true,
+ hit: true,
+ });
+ await reach("Back");
+ await check(false, "failure");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("start_stack", { mode: "never" }),
+ );
+ await page
+ .getByRole("button", { name: "Retry", exact: true })
+ .click();
+ await page.locator(".journey").waitFor();
+ await check(true, "retry");
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("start_stack", {
+ mode: "fail",
+ problem: {
+ said: "OpenBot found data from a previous installation.",
+ leftover_reset: [
+ "openbot_agent-profiles",
+ "openbot-workspace-general-assistant",
+ ],
+ leftover_containers: ["openbot-agent-computer-1"],
+ },
+ }),
+ );
+ await page
+ .getByRole("heading", {
+ name: "A previous OpenBot installation left data here",
+ })
+ .waitFor();
+ await reach("Start fresh");
+ await reach("Back");
+ expect(
+ await page
+ .getByRole("button", { name: "Retry", exact: true })
+ .count(),
+ ).toBe(0);
+ await check(false, "leftover");
+ await page.evaluate(() =>
+ document
+ .querySelector(
+ '.usage-choice input[type="checkbox"]',
+ )!
+ .focus(),
+ );
+ await page.keyboard.press("Space");
+ await settled(page);
+ expect(
+ await page.evaluate(() =>
+ globalThis
+ .__workbench!.calls()
+ .filter(
+ (call) =>
+ call.command === "plugin:openbot-desktop|set_usage_data",
+ )
+ .map((call) => call.args?.share),
+ ),
+ ).toEqual([false]);
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelector(
+ '.usage-choice input[type="checkbox"]',
+ )!.checked,
+ ),
+ ).toBe(false);
+ await check(false, "consent-changed");
+ expect(logActions).toEqual(["Copy logs", "Save to a file"]);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+});
+
+/*
+ * Seen on a Mac with a 1024x768 screen: Start failed, and the window showed "Failed · OpenBot did
+ * not start." at the top while what went wrong, its logs and Retry sat below the fold, with nothing
+ * to say the window scrolls. The tester found them only with Page Down. What went wrong and Retry
+ * are in view as the failure arrives, at every size the window can be.
+ */
+describe.skipIf(!asked)("approved layout: failed start", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [1024, 768],
+ // The setup window on that 1024x768 screen, under the menu bar and above the Dock.
+ [990, 620],
+ [720, 560],
+ ] as const)
+ for (const colorScheme of ["light", "dark"] as const)
+ test(`${width}x${height} ${colorScheme}: what went wrong and Retry are in view without scrolling`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ try {
+ await toTheAiStep(page);
+ await page.evaluate(() => {
+ globalThis.__workbench!.setAnswer("connect_local_eval", {
+ mode: "value",
+ value: {
+ outcome: "completed",
+ stack: { id: "local-abc123" },
+ reason: null,
+ conflicted: false,
+ },
+ });
+ globalThis.__workbench!.setAnswer("run_local_eval", {
+ mode: "value",
+ value: {
+ outcome: "completed",
+ stack: {
+ id: "local-abc123",
+ installedRelease: "0.16.0-rc.10",
+ step: "ready",
+ urls: {
+ api: "http://127.0.0.1:64770",
+ dashboard: "http://127.0.0.1:64771",
+ gateway: "ws://127.0.0.1:64772",
+ },
+ hasFailedStep: false,
+ updateInProgress: false,
+ unfinishedUpdate: null,
+ observed: null,
+ },
+ reason: null,
+ readiness: "ready",
+ licence: "valid",
+ licenceExpiresAt: null,
+ checksPassed: false,
+ },
+ });
+ // The longest way forward Start says today, with the output behind it.
+ globalThis.__workbench!.setAnswer("start_stack", {
+ mode: "fail",
+ problem: {
+ said: "Docker Desktop isn't sharing your OpenBot folder, so OpenBot can't start. In Docker Desktop's Settings, open File sharing, add /Users/someone/OpenBot, and apply the change. Then try again.",
+ detail:
+ "Error response from daemon: mounts denied: The path /Users/someone/OpenBot is not shared from the host and is not known to Docker.",
+ },
+ });
+ });
+ await page.getByText("Anthropic", { exact: true }).click();
+ await page
+ .getByRole("tab", { name: "Use an API key", exact: true })
+ .click();
+ await page
+ .getByLabel("Anthropic API key", { exact: true })
+ .fill("a-key-for-this-test");
+ await page
+ .getByRole("button", { name: "Continue", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Finishing setup" })
+ .waitFor();
+ await page.evaluate(() =>
+ (globalThis.__fake!.finishSetUp as () => void)(),
+ );
+ await page
+ .locator(".finishing-layout")
+ .getByRole("button", { name: "Retry", exact: true })
+ .waitFor();
+ await settled(page);
+ // Measured as the failure arrived: nothing here scrolls the window.
+ const seen = await page.evaluate(() => {
+ const sheet =
+ document.querySelector(".finishing-layout")!;
+ const body = sheet.querySelector(".setup-body")!;
+ const card = sheet.querySelector(
+ '.blocker[role="alert"]',
+ )!;
+ const retry = [
+ ...sheet.querySelectorAll("button"),
+ ].find((button) => button.textContent?.trim() === "Retry")!;
+ const view = body.getBoundingClientRect();
+ const inView = (element: Element) => {
+ const box = element.getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ box.x + box.width / 2,
+ box.y + box.height / 2,
+ );
+ return (
+ box.height > 0 &&
+ box.top >= Math.max(0, view.top) - 1 &&
+ box.bottom <= Math.min(innerHeight, view.bottom) + 1 &&
+ hit !== null &&
+ element.contains(hit)
+ );
+ };
+ return {
+ heading: inView(card.querySelector("h2")!),
+ said: inView(card.querySelector("p")!),
+ retry: inView(retry),
+ retries: [
+ ...sheet.querySelectorAll("button"),
+ ].filter((button) => button.textContent?.trim() === "Retry")
+ .length,
+ pageWidth: document.documentElement.scrollWidth,
+ pageHeight: document.documentElement.scrollHeight,
+ horizontalOverflow: body.scrollWidth > body.clientWidth,
+ };
+ });
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/failed-start-${width}x${height}-${colorScheme}.png`,
+ });
+ expect(seen).toEqual({
+ heading: true,
+ said: true,
+ retry: true,
+ retries: 1,
+ pageWidth: seen.pageWidth,
+ pageHeight: seen.pageHeight,
+ horizontalOverflow: false,
+ });
+ expect(seen.pageWidth).toBeLessThanOrEqual(width);
+ expect(seen.pageHeight).toBeLessThanOrEqual(height);
+ // Everything else the failure offers is still there, under it.
+ for (const name of ["Copy logs", "Save to a file", "Back"])
+ expect(
+ await page
+ .locator(".finishing-layout")
+ .getByRole("button", { name, exact: true })
+ .count(),
+ ).toBe(1);
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+});
+
+describe.skipIf(!asked)("approved layout: finishing", () => {
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const)
+ for (const colorScheme of ["light", "dark"] as const)
+ test(`${width}x${height} ${colorScheme}: held setup, lost backend and Start fresh`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ const state = async () => {
+ await settled(page);
+ return page.evaluate(() => {
+ const sheet =
+ document.querySelector(".finishing-layout")!;
+ const body = sheet.querySelector(".setup-body")!;
+ const footer = sheet.querySelector(
+ ":scope > .setup-footer",
+ )!;
+ const checkbox = footer.querySelector(
+ 'input[type="checkbox"]',
+ )!;
+ const b = body.getBoundingClientRect(),
+ f = footer.getBoundingClientRect(),
+ a = checkbox.getBoundingClientRect();
+ const memory = globalThis as unknown as { heldConsent?: Element };
+ memory.heldConsent ??= checkbox;
+ return {
+ sameConsent: memory.heldConsent === checkbox,
+ settingsReads: globalThis
+ .__workbench!.calls()
+ .filter(
+ (call) =>
+ call.command === "plugin:openbot-desktop|usage_data",
+ ).length,
+ width: document.documentElement.scrollWidth,
+ height: document.documentElement.scrollHeight,
+ overflow: body.scrollWidth > body.clientWidth,
+ overlap: b.bottom > f.top + 1,
+ consent: { x: a.x, y: a.y },
+ consentWhole: a.top >= 0 && a.bottom <= innerHeight,
+ consentHit:
+ document.elementFromPoint(
+ a.x + a.width / 2,
+ a.y + a.height / 2,
+ ) === checkbox,
+ spinners: sheet.querySelectorAll(".step-spinner").length,
+ journeys: sheet.querySelectorAll(".journey").length,
+ };
+ });
+ };
+ const reach = async (name: string) => {
+ expect(
+ await page.evaluate((name) => {
+ const button = [
+ ...document.querySelectorAll(
+ ".finishing-layout button",
+ ),
+ ].find((button) => button.textContent?.trim() === name)!;
+ button.scrollIntoView({ block: "nearest" });
+ button.focus();
+ const b = button.getBoundingClientRect(),
+ body = button
+ .closest(".setup-body")!
+ .getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ b.x + b.width / 2,
+ b.y + b.height / 2,
+ );
+ return {
+ focused: document.activeElement === button,
+ whole: b.top >= body.top - 1 && b.bottom <= body.bottom + 1,
+ hit: hit !== null && button.contains(hit),
+ };
+ }, name),
+ ).toEqual({ focused: true, whole: true, hit: true });
+ };
+ const shot = async (name: string) => {
+ await page.evaluate(() => {
+ document.querySelector(
+ ".finishing-layout .setup-body",
+ )!.scrollTop = 0;
+ });
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/finish-${width}-${colorScheme}-${name}.png`,
+ });
+ };
+ try {
+ await open(page);
+ await page.getByRole("heading", { name: "Set up OpenBot" }).waitFor();
+ await page.evaluate(() => {
+ const shortfall = {
+ podman: true,
+ cpu: false,
+ memory: false,
+ disk: true,
+ diskGb: "7.4",
+ freeOnDrive: true,
+ mac: true,
+ neededGb: "13",
+ };
+ globalThis.__workbench!.setAnswer("set_up_local_eval", {
+ mode: "value",
+ value: {
+ outcome: "blocked",
+ stack: null,
+ reason: "resources-short",
+ readiness: "unknown",
+ licence: "unknown",
+ licenceExpiresAt: null,
+ checksPassed: false,
+ shortfall,
+ },
+ });
+ globalThis.__workbench!.setAnswer("local_eval_room", {
+ mode: "value",
+ value: shortfall,
+ });
+ });
+ await page
+ .getByRole("button", { name: "Install", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Connect your AI" })
+ .waitFor();
+ await page.getByText("Anthropic", { exact: true }).click();
+ await page
+ .getByRole("tab", { name: "Use an API key", exact: true })
+ .click();
+ await page
+ .getByLabel("Anthropic API key", { exact: true })
+ .fill("a-key-for-this-test");
+ await page
+ .getByRole("button", { name: "Continue", exact: true })
+ .click();
+ await page
+ .getByRole("heading", { name: "Finishing setup" })
+ .waitFor();
+ await page
+ .getByRole("button", { name: "Try again", exact: true })
+ .waitFor();
+ await reach("Try again");
+ await reach("Cancel");
+ const held = await state();
+ expect(held.width).toBeLessThanOrEqual(width);
+ expect(held.height).toBeLessThanOrEqual(height);
+ expect(held.overflow).toBe(false);
+ expect(held.overlap).toBe(false);
+ expect(held.sameConsent).toBe(true);
+ expect(held.settingsReads).toBeGreaterThan(0);
+ expect(held.consentWhole).toBe(true);
+ expect(held.consentHit).toBe(true);
+ expect(held.spinners).toBe(0);
+ expect(held.journeys).toBe(0);
+ await shot("held");
+ await page.evaluate(() => {
+ globalThis.__workbench!.setAnswer("local_eval_room", {
+ mode: "value",
+ value: null,
+ });
+ globalThis.__workbench!.setAnswer("set_up_local_eval", {
+ mode: "value",
+ value: {
+ outcome: "failed",
+ stack: null,
+ reason: "stack-lost",
+ readiness: "unknown",
+ licence: "unknown",
+ licenceExpiresAt: null,
+ checksPassed: false,
+ },
+ });
+ });
+ await page
+ .getByRole("button", { name: "Try again", exact: true })
+ .click();
+ await page
+ .getByRole("button", { name: "Start fresh", exact: true })
+ .waitFor();
+ await reach("Start fresh");
+ await reach("Back");
+ expect(
+ await page
+ .getByRole("button", { name: "Retry", exact: true })
+ .count(),
+ ).toBe(0);
+ const lost = await state();
+ expect(lost).toEqual(held);
+ await shot("stack-lost");
+ // A real Tab traversal reaches diagnostics from the last recovery action.
+ await page.keyboard.press("Tab");
+ expect(
+ await page.evaluate(() =>
+ document.activeElement?.matches(
+ '.usage-choice input[type="checkbox"]',
+ ),
+ ),
+ ).toBe(true);
+ await page.evaluate(() =>
+ globalThis.__workbench!.setAnswer("set_up_local_eval", {
+ mode: "never",
+ }),
+ );
+ await page
+ .getByRole("button", { name: "Start fresh", exact: true })
+ .click();
+ await page.locator(".finishing-layout .journey").waitFor();
+ const resumed = await state();
+ expect(resumed.journeys).toBe(1);
+ expect(resumed.spinners).toBe(1);
+ expect(resumed.consent).toEqual(held.consent);
+ expect(resumed.sameConsent).toBe(true);
+ expect(resumed.settingsReads).toBe(held.settingsReads);
+ expect(resumed.overlap).toBe(false);
+ expect(resumed.overflow).toBe(false);
+ await shot("fresh-recovery");
+ } finally {
+ await page.close();
+ }
+ }, 60_000);
+});
+
+describe.skipIf(!asked)("approved layout: booking", () => {
+ const calendarMessage = async (
+ page: Page,
+ event: string,
+ reportedHeight?: string,
+ ) => {
+ await page.evaluate(
+ ({ event, reportedHeight }) =>
+ new Promise((resolve, reject) => {
+ const frame = document.querySelector(
+ 'iframe[title="Booking calendar"]',
+ )!;
+ const send = () =>
+ frame.contentWindow!.postMessage(
+ { testCalendar: { event, payload: { height: reportedHeight } } },
+ "*",
+ );
+ const receive = (message: MessageEvent) => {
+ if (
+ message.origin === "https://calendly.com" &&
+ message.source === frame.contentWindow &&
+ message.data?.testCalendarAck
+ ) {
+ clearInterval(retry);
+ clearTimeout(timeout);
+ window.removeEventListener("message", receive);
+ resolve();
+ }
+ };
+ window.addEventListener("message", receive);
+ const retry = setInterval(send, 25);
+ const timeout = setTimeout(() => {
+ clearInterval(retry);
+ window.removeEventListener("message", receive);
+ reject(new Error("calendar fixture did not acknowledge message"));
+ }, 5000);
+ send();
+ }),
+ { event, reportedHeight },
+ );
+ await settled(page);
+ };
+ for (const [width, height] of [
+ [1000, 800],
+ [720, 560],
+ ] as const)
+ for (const colorScheme of ["light", "dark"] as const) {
+ test(`${width}x${height} ${colorScheme}: loading, ready and fallback reserve the same surface and Back`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ const shot = async (state: string) => {
+ await settled(page);
+ if (process.env.OPENBOT_APP_SHOTS)
+ await page.screenshot({
+ path: `${process.env.OPENBOT_APP_SHOTS}/booking-${state}-${width}x${height}-${colorScheme}.png`,
+ });
+ };
+ const geometry = () =>
+ page.evaluate(() => {
+ const owner = document.querySelector(".booking-step")!;
+ const body = owner.querySelector(".setup-body")!;
+ const surface = owner.querySelector(
+ ".setup-booking-surface",
+ )!;
+ const footer = owner.querySelector(".setup-footer")!;
+ const back = footer.querySelector("button")!;
+ const box = (element: HTMLElement) => {
+ const { x, y, width, height } = element.getBoundingClientRect();
+ return { x, y, width, height };
+ };
+ const b = back.getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ b.x + b.width / 2,
+ b.y + b.height / 2,
+ );
+ return {
+ surface: box(surface),
+ footer: box(footer),
+ back: box(back),
+ header: box(
+ owner.querySelector(".setup-header-block")!,
+ ),
+ body: box(body),
+ titleY: owner.querySelector("h2")!.getBoundingClientRect().y,
+ railY: document
+ .querySelector(".rail-title")!
+ .getBoundingClientRect().y,
+ pageHeight: document.documentElement.scrollHeight,
+ pageWidth: document.documentElement.scrollWidth,
+ sideways: [
+ ...owner.querySelectorAll(
+ ".setup-body, .setup-booking-surface, .setup-footer",
+ ),
+ ].some(
+ (element) => element.scrollWidth > element.clientWidth + 1,
+ ),
+ frame: owner.querySelector("iframe")
+ ? box(owner.querySelector("iframe")!)
+ : null,
+ bodyScrolls: body.scrollHeight > body.clientHeight + 1,
+ hit: hit === back || back.contains(hit),
+ };
+ });
+ const check = async () => {
+ const now = await geometry();
+ expect(now.pageHeight).toBeLessThanOrEqual(height);
+ expect(now.pageWidth).toBeLessThanOrEqual(width);
+ expect(now.sideways).toBe(false);
+ // The calendar fills the available body rather than a short fixed-height crop.
+ expect(now.surface.height).toBeGreaterThan(
+ width === 1000 ? 480 : 240,
+ );
+ expect(now.surface.y + now.surface.height).toBeLessThanOrEqual(
+ now.footer.y + 1,
+ );
+ expect(now.bodyScrolls).toBe(false);
+ if (now.frame) {
+ expect(now.frame.y).toBeGreaterThanOrEqual(now.surface.y);
+ expect(now.frame.y + now.frame.height).toBeLessThanOrEqual(
+ now.surface.y + now.surface.height,
+ );
+ }
+ expect(now.hit).toBe(true);
+ expect(Math.abs(now.titleY - now.railY)).toBeLessThanOrEqual(1);
+ expect(now.body.y).toBeGreaterThanOrEqual(
+ now.header.y + now.header.height - 1,
+ );
+ expect(now.body.y + now.body.height).toBeLessThanOrEqual(
+ now.footer.y + 1,
+ );
+ expect(now.back.y + now.back.height).toBeLessThanOrEqual(height);
+ // The calendar and its footer both stay inside the window.
+ return now;
+ };
+ try {
+ await routeCalendar(page, false);
+ await open(page, "", cloudBuilt);
+ await page.locator('label:has(input[value="business"])').click();
+ await page
+ .getByRole("button", { name: "Book a demo", exact: true })
+ .click();
+ await page
+ .getByText("Loading available times…", { exact: true })
+ .waitFor();
+ await shot("loading");
+ const initial = await check();
+ expect(await page.evaluate(() => document.activeElement?.id)).toBe(
+ "book-a-demo-title",
+ );
+ // Parent-origin and wrong-source messages must not mark the calendar ready.
+ await page.evaluate(() => {
+ window.postMessage(
+ { event: "calendly.page_height", payload: { height: "1000px" } },
+ "*",
+ );
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ origin: "https://calendly.com",
+ source: window,
+ data: {
+ event: "calendly.page_height",
+ payload: { height: "1000px" },
+ },
+ }),
+ );
+ });
+ await settled(page);
+ expect(
+ await page.locator(".booking-calendar[data-ready]").count(),
+ ).toBe(0);
+ const protocol = await page.evaluate(() => {
+ const frame = document.querySelector(
+ 'iframe[title="Booking calendar"]',
+ )!;
+ const url = new URL(frame.src);
+ return {
+ origin: url.origin,
+ path: url.pathname,
+ embed: url.searchParams.get("embed_type"),
+ domain: url.searchParams.get("embed_domain"),
+ details: url.searchParams.get("hide_event_type_details"),
+ gdpr: url.searchParams.get("hide_gdpr_banner"),
+ sandbox: frame.getAttribute("sandbox"),
+ referrer: frame.referrerPolicy,
+ };
+ });
+ expect(protocol.origin).toBe("https://calendly.com");
+ expect(protocol.path).toBe("/d/dwfr-k64-8d2/openbot-for-business");
+ expect(protocol.embed).toBe("Inline");
+ expect(protocol.domain).toBe("openbot.test");
+ expect(protocol.details).toBe("1");
+ expect(protocol.gdpr).toBe("1");
+ expect(protocol.sandbox).toBe(
+ "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
+ );
+ expect(protocol.referrer).toBe("strict-origin-when-cross-origin");
+ await calendarMessage(page, "calendly.page_height", "26px");
+ expect(
+ await page.locator(".booking-calendar[data-ready]").count(),
+ ).toBe(0);
+ await shot("first-height");
+ const first = await check();
+ await calendarMessage(page, "calendly.event_type_viewed");
+ await page.locator(".booking-calendar[data-ready]").waitFor();
+ const viewed = await check();
+ await calendarMessage(page, "calendly.page_height", "660px");
+ await page.locator(".booking-calendar[data-ready]").waitFor();
+ await page
+ .getByText("Loading available times…", { exact: true })
+ .waitFor({ state: "hidden" });
+ await shot("ready");
+ const ready = await check();
+ await calendarMessage(page, "calendly.page_height", "1200px");
+ const tall = await check();
+ await page.evaluate(() =>
+ document
+ .querySelector('iframe[title="Booking calendar"]')!
+ .dispatchEvent(new Event("error")),
+ );
+ await page
+ .getByText(
+ "Couldn't load the calendar. Book a demo opens it in your browser.",
+ { exact: true },
+ )
+ .waitFor();
+ await shot("fallback");
+ const failed = await check();
+ for (const now of [first, viewed, ready, tall, failed])
+ for (const key of ["surface", "footer", "back"] as const)
+ for (const dimension of ["x", "y", "width", "height"] as const)
+ expect(
+ Math.abs(now[key][dimension] - initial[key][dimension]),
+ ).toBeLessThanOrEqual(1);
+ expect(
+ await page.locator('iframe[title="Booking calendar"]').count(),
+ ).toBe(0);
+ expect(await page.evaluate(() => document.activeElement?.id)).toBe(
+ "book-a-demo-title",
+ );
+ // Reach fallback and Back through the keyboard, starting from the focused heading.
+ let reachedBack = false;
+ let reachedFallback = false;
+ for (let index = 0; index < 12; index++) {
+ await page.keyboard.press("Tab");
+ const focus = await page.evaluate(() => ({
+ back: document.activeElement?.classList.contains("booking-back"),
+ fallback:
+ document.activeElement?.closest(".book-a-demo-fallback") !==
+ null,
+ }));
+ if (focus.fallback) {
+ reachedFallback = true;
+ const link = await page.evaluate(() => {
+ const element = document.activeElement as HTMLAnchorElement;
+ const box = element.getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ box.x + box.width / 2,
+ box.y + box.height / 2,
+ );
+ return {
+ href: element.href,
+ hit: element === hit || element.contains(hit),
+ };
+ });
+ expect(link).toEqual({
+ href: "https://open.bot/business",
+ hit: true,
+ });
+ await page.keyboard.press("Enter");
+ expect(
+ await page.evaluate(() => globalThis.__fake!.opened),
+ ).toEqual(["https://open.bot/business"]);
+ }
+ if (focus.back) {
+ reachedBack = true;
+ break;
+ }
+ }
+ expect(reachedFallback).toBe(true);
+ expect(reachedBack).toBe(true);
+ await check();
+ await page.keyboard.press("Enter");
+ await page.locator(".business-features").waitFor();
+ expect(
+ await page.evaluate(() => document.activeElement?.textContent),
+ ).toBe("Book a demo");
+ } finally {
+ await page.close();
+ }
+ }, 30_000);
+
+ test(`${width}x${height} ${colorScheme}: card embed retains reported height`, async () => {
+ const page = await browser.newPage({
+ viewport: { width, height },
+ colorScheme,
+ });
+ try {
+ await routeCalendar(page, false);
+ await open(page, "#move-choice", cloudBuilt);
+ await page.locator('label:has(input[value="business"])').click();
+ await page.locator('iframe[title="Booking calendar"]').waitFor();
+ const size = () =>
+ page.evaluate(() => ({
+ height: document
+ .querySelector('iframe[title="Booking calendar"]')!
+ .getBoundingClientRect().height,
+ reserved: document.querySelectorAll(".setup-booking-surface")
+ .length,
+ pageHeight: document.documentElement.scrollHeight,
+ pageWidth: document.documentElement.scrollWidth,
+ }));
+ expect((await size()).height).toBe(700);
+ for (const reported of [660, 1100]) {
+ await calendarMessage(
+ page,
+ "calendly.page_height",
+ `${reported}px`,
+ );
+ await page.locator(".booking-calendar[data-ready]").waitFor();
+ await settled(page);
+ const now = await size();
+ expect(now.height).toBe(reported);
+ expect(now.reserved).toBe(0);
+ expect(now.pageHeight).toBeLessThanOrEqual(height);
+ expect(now.pageWidth).toBeLessThanOrEqual(width);
+ }
+ } finally {
+ await page.close();
+ }
+ }, 30_000);
+ }
+});
diff --git a/desktop/src/setupLayout.browser.harness.ts b/desktop/src/setupLayout.browser.harness.ts
new file mode 100644
index 0000000000..9ad2b4c374
--- /dev/null
+++ b/desktop/src/setupLayout.browser.harness.ts
@@ -0,0 +1,310 @@
+import { beforeAll } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { sharedChromium } from "../../tests/support/shared-browser";
+
+/*
+ * What the setup window's browser test files share (setupLayout*.browser.test.ts): the window built
+ * as the app builds it, served as the shell serves it, a browser to open it in, and the steps and
+ * stand-ins several of them take. The window's describes are spread over those files so the
+ * desktop setup window's job runs them side by side: in one file they took about ten minutes, the
+ * longest job of a run. Each file calls `withSetupWindow` for its own build and browser.
+ */
+export const asked = process.env.OPENBOT_APP_BROWSER === "1";
+
+/*
+ * Playwright comes from the root install, which the real-browser CI job has. The desktop's own
+ * jobs install only the desktop's dependencies and typecheck this file, so it names the module
+ * by a variable and types only the part of it used here.
+ */
+export const PLAYWRIGHT: string = "playwright-core";
+export type Box = {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+} | null;
+export type Locator = {
+ click(): Promise;
+ fill(value: string): Promise;
+ waitFor(options?: {
+ state?: "hidden" | "visible";
+ timeout?: number;
+ }): Promise;
+ boundingBox(): Promise;
+ textContent(): Promise;
+ count(): Promise;
+ getByRole(
+ role: string,
+ options?: { name: string | RegExp; exact?: boolean },
+ ): Locator;
+};
+export type Route = {
+ request(): { url(): string };
+ fulfill(response: {
+ status?: number;
+ contentType?: string;
+ headers?: Record;
+ body: string;
+ }): Promise;
+};
+export type Page = {
+ addInitScript(script: string): Promise;
+ route(url: string, handler: (route: Route) => Promise): Promise;
+ goto(url: string): Promise;
+ getByRole(
+ role: string,
+ options?: { name: string | RegExp; exact?: boolean },
+ ): Locator;
+ locator(selector: string, options?: { hasText?: string | RegExp }): Locator;
+ getByText(text: string | RegExp, options?: { exact?: boolean }): Locator;
+ getByLabel(text: string, options: { exact: boolean }): Locator;
+ evaluate(run: (arg: A) => T, arg?: A): Promise;
+ waitForTimeout(ms: number): Promise;
+ screenshot(options: { path: string }): Promise;
+ keyboard: {
+ press(key: string): Promise;
+ type(text: string): Promise;
+ };
+ mouse: {
+ click(x: number, y: number): Promise;
+ move(x: number, y: number): Promise;
+ wheel(deltaX: number, deltaY: number): Promise;
+ };
+ close(): Promise;
+};
+export type Browser = {
+ newPage(options: {
+ viewport: { width: number; height: number };
+ colorScheme?: "light" | "dark";
+ userAgent?: string;
+ }): Promise;
+ close(): Promise;
+};
+export type Chromium = {
+ launch(options: {
+ channel: string;
+ ignoreDefaultArgs?: string[];
+ args?: string[];
+ }): Promise;
+};
+
+export type Window = { script: string; style: string };
+
+/**
+ * `marks.ts` as Vite builds it: each vendored mark in `shared/marks` inlined as a data URI, by the
+ * file's name.
+ */
+export function vendoredMarks(): string {
+ const folder = new URL("../../shared/marks/", import.meta.url);
+ const marks = Object.fromEntries(
+ readdirSync(folder)
+ .filter((file) => file.endsWith(".svg"))
+ .map((file) => [
+ file.replace(/\.svg$/, ""),
+ `data:image/svg+xml;base64,${readFileSync(new URL(file, folder)).toString("base64")}`,
+ ]),
+ );
+ return `const byId = new Map(Object.entries(${JSON.stringify(marks)}));
+export function markFor(id) { return (id && byId.get(id)) ?? null; }`;
+}
+
+/**
+ * The window as the app builds it, with the native side scripted. `env` is Vite's build-time
+ * values; none set is a build without a whitelabel support page or OpenBot Cloud.
+ */
+export async function buildWindow(
+ env: Record = {},
+): Promise {
+ const built = await Bun.build({
+ entrypoints: [
+ new URL("./fakeNative/browserEntry.ts", import.meta.url).pathname,
+ ],
+ target: "browser",
+ format: "esm",
+ define: {
+ "process.env.NODE_ENV": '"production"',
+ "import.meta.env": JSON.stringify(env),
+ },
+ plugins: [
+ {
+ name: "scripted-native-side",
+ setup(build) {
+ build.onResolve({ filter: /^@tauri-apps\/api\/event$/ }, () => ({
+ path: new URL("./fakeNative/event.ts", import.meta.url).pathname,
+ }));
+ build.onResolve({ filter: /^@tauri-apps\/api\// }, () => ({
+ path: new URL("./fakeNative/core.ts", import.meta.url).pathname,
+ }));
+ /*
+ * Brand marks come from Vite's glob import, which this build has not got. The same files
+ * are inlined here instead, so the window draws every mark the app draws. Left out, the
+ * clouds OpenBot for Business runs on showed as four empty tiles.
+ */
+ build.onResolve({ filter: /^\.\/marks$/ }, () => ({
+ path: "marks",
+ namespace: "scripted",
+ }));
+ build.onLoad({ filter: /.*/, namespace: "scripted" }, () => ({
+ contents: vendoredMarks(),
+ loader: "js",
+ }));
+ },
+ },
+ ],
+ });
+ if (!built.success) throw new AggregateError(built.logs, "build failed");
+ const script = await built.outputs
+ .find((out) => out.kind === "entry-point")
+ ?.text();
+ const style = await built.outputs
+ .find((out) => out.path.endsWith(".css"))
+ ?.text();
+ if (!script) throw new Error("the build has no entry point");
+ return { script, style: style ?? "" };
+}
+
+/** Served as the shell serves the window: its page, its script and its stylesheet. */
+export async function open(
+ page: Page,
+ hash = "",
+ served: Window = built,
+ headers: Record = {},
+) {
+ await page.route("https://openbot.test/**", (route) => {
+ const path = new URL(route.request().url()).pathname;
+ if (path === "/main.js")
+ return route.fulfill({
+ contentType: "text/javascript",
+ body: served.script,
+ });
+ if (path === "/main.css")
+ return route.fulfill({ contentType: "text/css", body: served.style });
+ if (path === "/")
+ return route.fulfill({
+ contentType: "text/html",
+ headers,
+ body: '',
+ });
+ return route.fulfill({ status: 404, body: "" });
+ });
+ // A secure origin, as the shell's own is: the window's calls are named with `crypto.randomUUID`.
+ await page.goto(`https://openbot.test/${hash}`);
+}
+
+export let browser: Browser;
+export let built: Window;
+/** The same window from a build that turns OpenBot Cloud on. */
+export let cloudBuilt: Window;
+export let chromium: Chromium;
+
+/** Builds the window and opens the browser before the calling file's tests. Each file calls it. */
+export function withSetupWindow() {
+ beforeAll(async () => {
+ if (!asked) return;
+ built = await buildWindow();
+ cloudBuilt = await buildWindow({ VITE_OPENBOT_CLOUD_ENABLED: "true" });
+ const playwright = (await import(PLAYWRIGHT)) as {
+ chromium: Chromium;
+ webkit: { launch(): Promise };
+ };
+ ({ chromium } = playwright);
+ // The CI job installs full Chromium without the headless shell. `OPENBOT_APP_ENGINE=webkit` is
+ // for a look in the engine the Mac window draws with, on a machine that has it installed.
+ // Never closed: the browser test files of a run share it (see sharedChromium).
+ browser =
+ process.env.OPENBOT_APP_ENGINE === "webkit"
+ ? await sharedChromium(() => playwright.webkit.launch(), "webkit")
+ : await sharedChromium(() => chromium.launch({ channel: "chromium" }));
+ // bun gives a hook 5 s. Two builds and a browser launch can take longer on a busy machine, and
+ // a hook that runs out of time skips the file's tests while it still runs.
+ }, 120_000);
+}
+
+/**
+ * The window come to rest: its fonts loaded, every entrance animation ended (the infinite ones,
+ * spinners and the download bar, left running), and two frames drawn after.
+ *
+ * A fixed wait is not enough. The card's `settle` entrance runs 420 ms on an ease that is still a
+ * ten-thousandth of a pixel from home at 400 ms, and a box measured on that offset came back
+ * 22.000015 px tall: a one-line name read as two lines about one run in three.
+ */
+export async function settled(page: Page) {
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ await Promise.all(
+ document
+ .getAnimations()
+ .filter((animation) =>
+ Number.isFinite(
+ Number(animation.effect?.getComputedTiming().endTime),
+ ),
+ )
+ .map((animation) => animation.finished.catch(() => undefined)),
+ );
+ for (let frame = 0; frame < 2; frame++)
+ await new Promise((drawn) => requestAnimationFrame(drawn));
+ });
+}
+
+/** Where the form's first field is, and how tall the page is: what the window is sized to. */
+export async function measure(page: Page) {
+ const field = await page
+ .getByLabel("Base URL", { exact: true })
+ .boundingBox();
+ const advanced = await page
+ .getByText("Advanced compatible endpoint options")
+ .boundingBox();
+ const height = await page.evaluate(
+ () => document.documentElement.scrollHeight,
+ );
+ return { field: field?.y, advanced: advanced?.y, height };
+}
+
+/**
+ * Calendly, as far as the window can tell: a page in the calendar's frame that says its height, as
+ * Calendly's inline embed does once it is drawn. The real one is on the web, which a test never is.
+ */
+export async function routeCalendar(page: Page, automatic = true) {
+ await page.route("https://calendly.com/**", (route) =>
+ route.fulfill({
+ contentType: "text/html",
+ body: `Booking calendar (stand-in for Calendly)`,
+ }),
+ );
+}
+
+/** Goes from the first screen to "Connect your AI", as a first run does. */
+export async function toTheAiStep(page: Page, hash = "") {
+ await open(page, hash);
+ await page.getByRole("button", { name: "Install", exact: true }).click();
+ await page.getByRole("heading", { name: "Connect your AI" }).waitFor();
+ // The entrance animation settles before anything is measured.
+ await page.waitForTimeout(600);
+}
+
+export const emitProgress = (page: Page, payload: Record) =>
+ page.evaluate(
+ (sent) =>
+ (
+ globalThis as unknown as {
+ __fake: { emit: (name: string, payload: unknown) => void };
+ }
+ ).__fake.emit("setup:progress", sent),
+ payload,
+ );
+
+export const DOCKER_STARTING =
+ "Docker Desktop is starting in its own window. If it asks you to accept its terms or sign in, do that there. OpenBot comes back when Docker is ready.";
+
+/** The native commands the window has asked for, in order. */
+export const calls = (page: Page) =>
+ page.evaluate(
+ () =>
+ (globalThis as unknown as { __fake: { calls: string[] } }).__fake.calls,
+ );
diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts
index b241eede3a..86dc1f07ba 100644
--- a/desktop/src/setupLayout.browser.test.ts
+++ b/desktop/src/setupLayout.browser.test.ts
@@ -1,9 +1,27 @@
-import { beforeAll, describe, expect, test } from "bun:test";
+import { describe, expect, test } from "bun:test";
import { createHash } from "node:crypto";
-import { readdirSync, readFileSync } from "node:fs";
+import { readFileSync } from "node:fs";
import { AGENT_ORB_CSS } from "../../shared/agent-orb";
import { BOOKING_CALENDAR_ORIGIN } from "../../shared/openbot-for-business";
import { sharedChromium } from "../../tests/support/shared-browser";
+import {
+ asked,
+ type Box,
+ browser,
+ built,
+ calls,
+ chromium,
+ cloudBuilt,
+ DOCKER_STARTING,
+ emitProgress,
+ measure,
+ open,
+ type Page,
+ routeCalendar,
+ settled,
+ toTheAiStep,
+ withSetupWindow,
+} from "./setupLayout.browser.harness";
/**
* The AI step's form holds still while the install behind it comes and goes.
@@ -20,247 +38,12 @@ import { sharedChromium } from "../../tests/support/shared-browser";
* passed, the rest of OpenBot setting up behind the step, its download arriving and ending.
*
* OPENBOT_APP_BROWSER=1 bun test src/setupLayout.browser.test.ts
- */
-const asked = process.env.OPENBOT_APP_BROWSER === "1";
-
-/*
- * Playwright comes from the root install, which the real-browser CI job has. The desktop's own
- * jobs install only the desktop's dependencies and typecheck this file, so it names the module
- * by a variable and types only the part of it used here.
- */
-const PLAYWRIGHT: string = "playwright-core";
-type Box = { x: number; y: number; width: number; height: number } | null;
-type Locator = {
- click(): Promise;
- fill(value: string): Promise;
- waitFor(options?: {
- state?: "hidden" | "visible";
- timeout?: number;
- }): Promise;
- boundingBox(): Promise;
- textContent(): Promise;
- count(): Promise;
- getByRole(
- role: string,
- options?: { name: string | RegExp; exact?: boolean },
- ): Locator;
-};
-type Route = {
- request(): { url(): string };
- fulfill(response: {
- status?: number;
- contentType?: string;
- headers?: Record;
- body: string;
- }): Promise;
-};
-type Page = {
- addInitScript(script: string): Promise;
- route(url: string, handler: (route: Route) => Promise): Promise;
- goto(url: string): Promise;
- getByRole(
- role: string,
- options?: { name: string | RegExp; exact?: boolean },
- ): Locator;
- locator(selector: string, options?: { hasText?: string | RegExp }): Locator;
- getByText(text: string | RegExp, options?: { exact?: boolean }): Locator;
- getByLabel(text: string, options: { exact: boolean }): Locator;
- evaluate(run: (arg: A) => T, arg?: A): Promise;
- waitForTimeout(ms: number): Promise;
- screenshot(options: { path: string }): Promise;
- keyboard: {
- press(key: string): Promise;
- type(text: string): Promise;
- };
- mouse: {
- click(x: number, y: number): Promise;
- move(x: number, y: number): Promise;
- wheel(deltaX: number, deltaY: number): Promise;
- };
- close(): Promise;
-};
-type Browser = {
- newPage(options: {
- viewport: { width: number; height: number };
- colorScheme?: "light" | "dark";
- userAgent?: string;
- }): Promise;
- close(): Promise;
-};
-type Chromium = {
- launch(options: {
- channel: string;
- ignoreDefaultArgs?: string[];
- args?: string[];
- }): Promise;
-};
-
-type Window = { script: string; style: string };
-
-/**
- * `marks.ts` as Vite builds it: each vendored mark in `shared/marks` inlined as a data URI, by the
- * file's name.
- */
-function vendoredMarks(): string {
- const folder = new URL("../../shared/marks/", import.meta.url);
- const marks = Object.fromEntries(
- readdirSync(folder)
- .filter((file) => file.endsWith(".svg"))
- .map((file) => [
- file.replace(/\.svg$/, ""),
- `data:image/svg+xml;base64,${readFileSync(new URL(file, folder)).toString("base64")}`,
- ]),
- );
- return `const byId = new Map(Object.entries(${JSON.stringify(marks)}));
-export function markFor(id) { return (id && byId.get(id)) ?? null; }`;
-}
-
-/**
- * The window as the app builds it, with the native side scripted. `env` is Vite's build-time
- * values; none set is a build without a whitelabel support page or OpenBot Cloud.
- */
-async function buildWindow(env: Record = {}): Promise {
- const built = await Bun.build({
- entrypoints: [
- new URL("./fakeNative/browserEntry.ts", import.meta.url).pathname,
- ],
- target: "browser",
- format: "esm",
- define: {
- "process.env.NODE_ENV": '"production"',
- "import.meta.env": JSON.stringify(env),
- },
- plugins: [
- {
- name: "scripted-native-side",
- setup(build) {
- build.onResolve({ filter: /^@tauri-apps\/api\/event$/ }, () => ({
- path: new URL("./fakeNative/event.ts", import.meta.url).pathname,
- }));
- build.onResolve({ filter: /^@tauri-apps\/api\// }, () => ({
- path: new URL("./fakeNative/core.ts", import.meta.url).pathname,
- }));
- /*
- * Brand marks come from Vite's glob import, which this build has not got. The same files
- * are inlined here instead, so the window draws every mark the app draws. Left out, the
- * clouds OpenBot for Business runs on showed as four empty tiles.
- */
- build.onResolve({ filter: /^\.\/marks$/ }, () => ({
- path: "marks",
- namespace: "scripted",
- }));
- build.onLoad({ filter: /.*/, namespace: "scripted" }, () => ({
- contents: vendoredMarks(),
- loader: "js",
- }));
- },
- },
- ],
- });
- if (!built.success) throw new AggregateError(built.logs, "build failed");
- const script = await built.outputs
- .find((out) => out.kind === "entry-point")
- ?.text();
- const style = await built.outputs
- .find((out) => out.path.endsWith(".css"))
- ?.text();
- if (!script) throw new Error("the build has no entry point");
- return { script, style: style ?? "" };
-}
-
-/** Served as the shell serves the window: its page, its script and its stylesheet. */
-async function open(
- page: Page,
- hash = "",
- served: Window = built,
- headers: Record = {},
-) {
- await page.route("https://openbot.test/**", (route) => {
- const path = new URL(route.request().url()).pathname;
- if (path === "/main.js")
- return route.fulfill({
- contentType: "text/javascript",
- body: served.script,
- });
- if (path === "/main.css")
- return route.fulfill({ contentType: "text/css", body: served.style });
- if (path === "/")
- return route.fulfill({
- contentType: "text/html",
- headers,
- body: '',
- });
- return route.fulfill({ status: 404, body: "" });
- });
- // A secure origin, as the shell's own is: the window's calls are named with `crypto.randomUUID`.
- await page.goto(`https://openbot.test/${hash}`);
-}
-
-let browser: Browser;
-let built: Window;
-/** The same window from a build that turns OpenBot Cloud on. */
-let cloudBuilt: Window;
-let chromium: Chromium;
-
-beforeAll(async () => {
- if (!asked) return;
- built = await buildWindow();
- cloudBuilt = await buildWindow({ VITE_OPENBOT_CLOUD_ENABLED: "true" });
- const playwright = (await import(PLAYWRIGHT)) as {
- chromium: Chromium;
- webkit: { launch(): Promise };
- };
- ({ chromium } = playwright);
- // The CI job installs full Chromium without the headless shell. `OPENBOT_APP_ENGINE=webkit` is
- // for a look in the engine the Mac window draws with, on a machine that has it installed.
- // Never closed: the browser test files of a run share it (see sharedChromium).
- browser =
- process.env.OPENBOT_APP_ENGINE === "webkit"
- ? await sharedChromium(() => playwright.webkit.launch(), "webkit")
- : await sharedChromium(() => chromium.launch({ channel: "chromium" }));
- // bun gives a hook 5 s. Two builds and a browser launch can take longer on a busy machine, and
- // a hook that runs out of time skips the file's tests while it still runs.
-}, 120_000);
-
-/**
- * The window come to rest: its fonts loaded, every entrance animation ended (the infinite ones,
- * spinners and the download bar, left running), and two frames drawn after.
*
- * A fixed wait is not enough. The card's `settle` entrance runs 420 ms on an ease that is still a
- * ten-thousandth of a pixel from home at 400 ms, and a box measured on that offset came back
- * 22.000015 px tall: a one-line name read as two lines about one run in three.
+ * The window's longest describes are in files of their own beside this one, so the desktop setup
+ * window's job runs them side by side: setupLayout.moveToCloud.browser.test.ts and
+ * setupLayout.approved.browser.test.ts. What they share is setupLayout.browser.harness.ts.
*/
-async function settled(page: Page) {
- await page.evaluate(async () => {
- await document.fonts.ready;
- await Promise.all(
- document
- .getAnimations()
- .filter((animation) =>
- Number.isFinite(
- Number(animation.effect?.getComputedTiming().endTime),
- ),
- )
- .map((animation) => animation.finished.catch(() => undefined)),
- );
- for (let frame = 0; frame < 2; frame++)
- await new Promise((drawn) => requestAnimationFrame(drawn));
- });
-}
-
-/** Where the form's first field is, and how tall the page is: what the window is sized to. */
-async function measure(page: Page) {
- const field = await page
- .getByLabel("Base URL", { exact: true })
- .boundingBox();
- const advanced = await page
- .getByText("Advanced compatible endpoint options")
- .boundingBox();
- const height = await page.evaluate(
- () => document.documentElement.scrollHeight,
- );
- return { field: field?.y, advanced: advanced?.y, height };
-}
+withSetupWindow();
/*
* Seen on Windows F: the window opened at 1016x839, grew to 853 when the sign-in card appeared,
@@ -1299,25 +1082,6 @@ describe.skipIf(!asked)("the first screen at the window's default size", () => {
}
});
-/**
- * Calendly, as far as the window can tell: a page in the calendar's frame that says its height, as
- * Calendly's inline embed does once it is drawn. The real one is on the web, which a test never is.
- */
-async function routeCalendar(page: Page, automatic = true) {
- await page.route("https://calendly.com/**", (route) =>
- route.fulfill({
- contentType: "text/html",
- body: `Booking calendar (stand-in for Calendly)`,
- }),
- );
-}
-
describe.skipIf(!asked)("approved layout: Cloud hosting narrow", () => {
for (const colorScheme of ["light", "dark"] as const)
test(`720x560 ${colorScheme}: all three choices, local install, connect and calendar stay reachable`, async () => {
@@ -1845,15 +1609,6 @@ describe.skipIf(!asked)("the offer to pause the person's Podman", () => {
}
});
-/** Goes from the first screen to "Connect your AI", as a first run does. */
-async function toTheAiStep(page: Page, hash = "") {
- await open(page, hash);
- await page.getByRole("button", { name: "Install", exact: true }).click();
- await page.getByRole("heading", { name: "Connect your AI" }).waitFor();
- // The entrance animation settles before anything is measured.
- await page.waitForTimeout(600);
-}
-
describe.skipIf(!asked)("restored provider focus", () => {
test("at 720x560, Change and Escape reveal the whole previous provider and reselection reveals the form start", async () => {
const page = await browser.newPage({
@@ -3012,17 +2767,6 @@ async function toStart(page: Page) {
await page.waitForTimeout(600);
}
-const emitProgress = (page: Page, payload: Record) =>
- page.evaluate(
- (sent) =>
- (
- globalThis as unknown as {
- __fake: { emit: (name: string, payload: unknown) => void };
- }
- ).__fake.emit("setup:progress", sent),
- payload,
- );
-
describe.skipIf(!asked)("the Start screen's words and card", () => {
/*
* Seen on Windows G: "Starting OpenBot" said "This usually takes a minute or two" over a card
@@ -3285,8 +3029,6 @@ describe.skipIf(!asked)("the Start screen's words and card", () => {
* Run with `OPENBOT_APP_ENGINE=webkit` too, the engine the Mac window draws with.
* `OPENBOT_APP_SHOTS=` keeps a screenshot of each, taken before anything is asserted.
*/
-const DOCKER_STARTING =
- "Docker Desktop is starting in its own window. If it asks you to accept its terms or sign in, do that there. OpenBot comes back when Docker is ready.";
/** The update screen as a person sees it: its words, and where the progress and the note sit. */
describe.skipIf(!asked)("approved layout: shutdown Progress rail", () => {
@@ -3744,281 +3486,6 @@ describe.skipIf(!asked)(
},
);
-/*
- * 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 this app is too old for", () => {
- const shots = process.env.OPENBOT_SHOTS_DIR;
- const states: {
- name: string;
- at: string;
- said: string;
- way: { role: "button" | "link"; name: string };
- /** The window's heading, where the state's screen is OpenBot on this computer running. */
- heading?: 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-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",
- 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" },
- heading: "Update OpenBot",
- },
- // Found running by a launch that did not start it: the same screen as when Start finds it.
- {
- // Start refused: the release on this computer needs a newer launcher contract (launcherApi).
- name: "local-launcher-ahead",
- at: "#local-launcher-ahead",
- 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-launcher-ahead-with-offer",
- at: "?offer#local-launcher-ahead",
- 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" },
- heading: "Update OpenBot",
- },
- {
- 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: "The OpenBot at openbot.example.com ended your sign-in.",
- way: { role: "button", name: "Sign in again" },
- },
- // A launch offline with a saved sign-in: still opening, saying why, and reconnecting by
- // itself, with the way to the first screen in view.
- {
- name: "connected-offline-reconnecting",
- at: "#connect-offline",
- said: "You're offline, or openbot.example.com isn't answering.",
- way: { role: "button", name: "Stop reconnecting" },
- },
- // The window signed in at OpenBot's own address, and its page couldn't trade the browser's
- // code for its session: the connect screen says which, with the way on.
- {
- name: "window-sign-in-expired",
- at: "#connect-window-expired",
- said: "Your sign-in at openbot.example.com didn't go through.",
- way: { role: "button", name: "Sign in again" },
- },
- {
- name: "window-sign-in-refused",
- at: "#connect-window-refused",
- said: "OpenBot couldn't sign you in at openbot.example.com.",
- way: { role: "button", name: "Sign in again" },
- },
- {
- name: "window-sign-in-unreachable",
- at: "#connect-window-unreachable",
- said: "OpenBot couldn't reach openbot.example.com.",
- way: { role: "button", name: "Try 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);
- // Running, so never "OpenBot is stopped" with a Start: Show OpenBot and Stop OpenBot.
- if (state.heading) {
- const screen = await page.evaluate(() => ({
- heading: document.querySelector("h1")?.textContent?.trim(),
- buttons: [...document.querySelectorAll("button")].map(
- (button) => button.textContent?.trim(),
- ),
- }));
- expect(screen.heading).toBe(state.heading);
- expect(screen.buttons).not.toContain("Start OpenBot");
- expect(screen.buttons).toContain("Show OpenBot");
- expect(screen.buttons).toContain("Stop OpenBot");
- }
- // 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);
- }
- }
-
- /*
- * On a build that never updates itself, the line that says so is part of the notice, in the
- * notice's type, on the connect screen as on the screen for the OpenBot on this computer. Seen on
- * a Mac: on the connect screen it sat under the notice in body type.
- */
- for (const state of [
- {
- name: "connected-app-too-old-internal",
- at: "?internal#connect-app-too-old",
- said: "needs a newer version of this app. Update OpenBot, then connect again.",
- },
- {
- name: "local-app-too-old-internal",
- at: "?internal#local-app-too-old",
- said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.",
- },
- ]) {
- test(`${state.name}: "doesn't update itself" is in the notice, in the notice's type`, async () => {
- for (const colorScheme of ["light", "dark"] as const) {
- const page = await browser.newPage({
- viewport: { width: 1000, height: 800 },
- colorScheme,
- });
- try {
- await open(page, state.at);
- await page.getByText(state.said, { exact: false }).waitFor();
- // The update's own line (Updates, folded under the buttons, says it too).
- await page
- .locator('p[role="status"]', { hasText: "doesn't update itself" })
- .waitFor();
- await page.waitForTimeout(1200);
- const placed = await page.evaluate((said) => {
- const notice = [...document.querySelectorAll(".local-alert")].find(
- (element) => element.textContent?.includes(said),
- );
- const sentence = [...(notice?.querySelectorAll("p") ?? [])].find(
- (element) => element.textContent?.includes(said),
- );
- const line = [
- ...document.querySelectorAll('p[role="status"]'),
- ].find((element) =>
- element.textContent?.includes("doesn't update itself"),
- );
- const size = (element: Element | undefined) =>
- element ? getComputedStyle(element).fontSize : null;
- return {
- inside: Boolean(notice && line && notice.contains(line)),
- line: size(line),
- notice: size(sentence),
- updates: [...document.querySelectorAll("button")].filter(
- (button) => button.textContent?.trim() === "Update and restart",
- ).length,
- };
- }, state.said);
- expect(placed.notice).not.toBeNull();
- expect(placed).toEqual({
- inside: true,
- line: placed.notice,
- notice: placed.notice,
- updates: 0,
- });
- if (shots)
- await page.screenshot({
- path: `${shots}/${state.name}-${colorScheme}.png`,
- });
- } finally {
- await page.close();
- }
- }
- }, 30_000);
- }
-});
-
/*
* After Stop, the Status window's App row said Stopped and offered nothing, while the services row
* under it offered Start. The App row offers Start now, laid out as the services row's: the same
@@ -4206,901 +3673,46 @@ describe.skipIf(!asked)(
);
/*
- * The move to OpenBot Cloud, each of its screens in the first screen's card, at the window's
- * default size (1000x800, tauri.conf.json), that less a title bar (1000x760), and its smallest
- * (720x560). The page never scrolls, and every one of a screen's buttons is whole in the window and
- * in the card's view, not under anything, as the screen opens. At 1000x760 every common case fits
- * with nothing scrolled inside the card; what is taller scrolls inside the card above its buttons.
- *
- * Seen on 1.2.0-rc.2: a move that failed showed its technical details, the screen ran past the
- * card's foot, and Try again and Keep OpenBot on this computer were out of view. The person quit
- * and reopened OpenBot to get past it. `OPENBOT_APP_SHOTS=` keeps a screenshot of each,
- * light and dark, taken before anything is asserted.
+ * FOUND ON 1.2.0-rc.3, a Mac, after an update: the setup window stayed a plain ground with nothing
+ * on it, across two launches, while its page's code still ran. A screen that failed to draw took
+ * every screen with it, leaving only the ground behind them. Now it shows "OpenBot hit a problem"
+ * on the setup window's own failure box, with Reload and the logs, readable in light and dark.
+ * `OPENBOT_APP_SHOTS=` keeps a screenshot of each.
*/
-describe.skipIf(!asked)(
- "the move to OpenBot Cloud at the window's size",
- () => {
- const shots = process.env.OPENBOT_APP_SHOTS;
- const engine = process.env.OPENBOT_APP_ENGINE ?? "chromium";
- const SIZES = [
- [1000, 760],
- [1000, 800],
- [720, 560],
- ] as const;
- const SCREENS: {
- hash: string;
- /** The test's and the screenshot's name, when one hash shows two ways. */
- name?: string;
- heading: string;
- /** Pressed on the confirm screen, once what moves has loaded. */
- move?: boolean;
- /** Technical details opened, as the person would. */
- openDetail?: boolean;
- /** Scrolls inside the card at 1000x760. */
- scrolls?: boolean;
- /** Nothing to press: sending, past signing in, has no Cancel. */
- noButtons?: boolean;
- }[] = [
- { hash: "#move-choice", heading: "Move to OpenBot Cloud?" },
- { hash: "#move-confirm", heading: "Move to OpenBot Cloud" },
- { hash: "#move-confirm-loading", heading: "Move to OpenBot Cloud" },
- {
- hash: "#move-confirm-many",
- heading: "Move to OpenBot Cloud",
- scrolls: true,
- },
- { hash: "#move-signin", heading: "Moving to OpenBot Cloud", move: true },
- {
- hash: "#move-midway",
- heading: "Moving to OpenBot Cloud",
- move: true,
- noButtons: true,
- },
- { hash: "#move-failed", heading: "The move didn't finish", move: true },
- // In more than one organization on OpenBot Cloud: where the Bots go, one of them held.
- {
- hash: "#move-where",
- heading: "Where should your Bots go?",
- move: true,
- },
- {
- hash: "#move-not-allowed",
- heading: "Your Bots can't move there",
- move: true,
- },
- {
- hash: "#move-failed-detail",
- heading: "The move didn't finish",
- move: true,
- scrolls: true,
- },
- {
- hash: "#move-failed-detail",
- name: "move-failed-detail-open",
- heading: "The move didn't finish",
- move: true,
- openDetail: true,
- scrolls: true,
- },
- // OpenBot Cloud's own three-line sentence: a few pixels past the card, the buttons in view.
- {
- hash: "#move-stopped",
- heading: "The move didn't finish",
- move: true,
- scrolls: true,
- },
- { hash: "#move-done", heading: "You're on OpenBot Cloud", move: true },
- {
- hash: "#move-done-held",
- heading: "You're on OpenBot Cloud",
- move: true,
- },
- {
- hash: "#move-done-left",
- heading: "You're on OpenBot Cloud",
- move: true,
- },
- { hash: "#move-done-ai", heading: "You're on OpenBot Cloud", move: true },
- // Apps connected with a key come across connected, apart from those signed in to again: two
- // lists, which scroll inside the card above its buttons, as many apps do.
- {
- hash: "#move-confirm-carried",
- heading: "Move to OpenBot Cloud",
- scrolls: true,
- },
- {
- hash: "#move-done-carried",
- heading: "You're on OpenBot Cloud",
- move: true,
- scrolls: true,
- },
- {
- hash: "#move-done-ai-carried",
- heading: "You're on OpenBot Cloud",
- move: true,
- scrolls: true,
- },
- ];
- /*
- * The move screen's choices: OpenBot Cloud, then OpenBot for Business as the first screen draws
- * it, then OpenBot (Self-Contained), one above the other at one width. Business's four clouds
- * are drawn, on one line, inside its row past its words.
- */
- const MOVE_CHOICE_ROWS = {
- names: [
- "OpenBot Cloud Recommended",
- "OpenBot for Business",
- "OpenBot (Self-Contained)",
- ],
- stacked: true,
- drawn: [
- ["aws", true],
- ["azure", true],
- ["google-cloud", true],
- ["kubernetes", true],
- ],
- marks: true,
- };
- const moveChoiceRows = async (page: Page) => {
- await page.evaluate(async () => {
- await document.fonts.ready;
- });
- return page.evaluate(() => {
- const rows = [
- ...document.querySelectorAll("fieldset.picker.hosting > .tile"),
- ];
- const boxes = rows.map((row) => row.getBoundingClientRect());
- const business = document.querySelector(
- "fieldset.picker.hosting > .tile.with-marks",
- );
- const box = business?.getBoundingClientRect();
- const words = business
- ?.querySelector(".tile-summary")
- ?.getBoundingClientRect();
- const marks = [
- ...(business?.querySelectorAll(".cloud-mark") ?? []),
- ].map((mark) => mark.getBoundingClientRect());
- return {
- names: rows.map(
- (row) => row.querySelector(".tile-name")?.textContent ?? "",
- ),
- stacked: boxes.every(
- (row, at) =>
- row.width === boxes[0]?.width &&
- (at === 0 || row.top >= (boxes[at - 1]?.bottom ?? 0)),
- ),
- drawn: [
- ...(business?.querySelectorAll(
- ".cloud-mark img",
- ) ?? []),
- ].map((image) => [
- image.dataset.mark,
- image.complete && image.naturalWidth > 0,
- ]),
- marks:
- marks.length === 4 &&
- !!box &&
- !!words &&
- marks.every(
- (mark) =>
- mark.top >= box.top &&
- mark.bottom <= box.bottom &&
- mark.right <= box.right &&
- mark.left >= words.right &&
- mark.top === marks[0]?.top,
- ),
- };
+describe.skipIf(!asked)("a screen that fails to draw", () => {
+ for (const colorScheme of ["light", "dark"] as const)
+ test(`shows OpenBot hit a problem, never the bare ground (${colorScheme})`, async () => {
+ const page = await browser.newPage({
+ viewport: { width: 1000, height: 800 },
+ colorScheme,
});
- };
- for (const [width, height] of SIZES)
- for (const colorScheme of ["light", "dark"] as const) {
- for (const screen of SCREENS) {
- const name = screen.name ?? screen.hash.slice(1);
- test(`at ${width}x${height}, ${name} fits the window, its buttons in view (${colorScheme})`, async () => {
- const page = await browser.newPage({
- viewport: { width, height },
- colorScheme,
- });
- try {
- await open(page, screen.hash, cloudBuilt);
- if (screen.move) {
- await page.getByRole("list", { name: "What moves" }).waitFor();
- await page
- .getByRole("button", { name: "Move to OpenBot Cloud" })
- .click();
- }
- await page
- .getByRole("heading", { name: screen.heading, exact: true })
- .waitFor();
- if (
- screen.hash === "#move-confirm" ||
- screen.hash === "#move-confirm-carried"
- )
- await page.getByRole("list", { name: "What moves" }).waitFor();
- if (screen.openDetail) {
- await page
- .getByText("Technical details", { exact: true })
- .click();
- await page.waitForTimeout(100);
- // Opened, they show: whole, in the card's view, clear of its pinned foot.
- const shown = await page.evaluate(() => {
- const sheet = document.querySelector("main > .sheet");
- const said = document.querySelector("main details pre");
- const foot = document.querySelector(
- "main > .sheet > .step-footer",
- );
- const box = said?.getBoundingClientRect();
- return {
- top: box?.top ?? 0,
- bottom: box?.bottom ?? 0,
- ceiling: sheet?.getBoundingClientRect().top ?? 0,
- floor: Math.min(
- foot?.getBoundingClientRect().top ??
- Number.POSITIVE_INFINITY,
- sheet?.getBoundingClientRect().bottom ?? 0,
- ),
- };
- });
- expect(shown.bottom).toBeGreaterThan(shown.top);
- expect(shown.top).toBeGreaterThanOrEqual(shown.ceiling);
- // Within the pixel the card's scroll snaps to.
- expect(shown.bottom).toBeLessThanOrEqual(shown.floor + 1);
- }
- // The card's entrance over, and the pointer off whatever it pressed.
- await page.mouse.move(0, 0);
- await page.waitForTimeout(600);
- if (shots)
- await page.screenshot({
- path: `${shots}/${name}-${width}x${height}-${colorScheme}-${engine}.png`,
- });
- // What scrolls inside the card, scrolled to its end for a look, then back.
- if (shots && screen.scrolls) {
- await page.evaluate(() => {
- const sheet = document.querySelector("main > .sheet");
- if (sheet) sheet.scrollTop = sheet.scrollHeight;
- });
- await page.waitForTimeout(200);
- await page.screenshot({
- path: `${shots}/${name}-scrolled-${width}x${height}-${colorScheme}-${engine}.png`,
- });
- await page.evaluate(() => {
- const sheet = document.querySelector("main > .sheet");
- if (sheet) sheet.scrollTop = 0;
- });
- }
- const fit = await page.evaluate(() => {
- const sheet = document.querySelector("main > .sheet");
- const card = sheet?.getBoundingClientRect();
- const style = sheet ? getComputedStyle(sheet) : null;
- // The card's view: inside its border, and inside the window.
- const top = Math.max(
- 0,
- (card?.top ?? 0) +
- (Number.parseFloat(style?.borderTopWidth ?? "") || 0),
- );
- const bottom = Math.min(
- window.innerHeight,
- (card?.bottom ?? 0) -
- (Number.parseFloat(style?.borderBottomWidth ?? "") || 0),
- );
- // The screen's own buttons, not those in a list inside it.
- const buttons = [
- ...document.querySelectorAll(
- "main > .sheet > .row button, main > .sheet > .step-footer button",
- ),
- ];
- return {
- cardScrolls: sheet
- ? sheet.scrollHeight > sheet.clientHeight + 1
- : true,
- pageScrolls:
- document.documentElement.scrollHeight >
- window.innerHeight ||
- document.documentElement.scrollWidth > window.innerWidth,
- buttons: buttons.length,
- outOfView: buttons
- .filter((button) => {
- const box = button.getBoundingClientRect();
- const hit = document.elementFromPoint(
- box.left + box.width / 2,
- box.top + box.height / 2,
- );
- return !(
- box.top >= top &&
- box.bottom <= bottom &&
- box.left >= 0 &&
- box.right <= window.innerWidth &&
- hit !== null &&
- button.contains(hit)
- );
- })
- .map((button) => button.textContent),
- };
- });
- if (screen.noButtons) expect(fit.buttons).toBe(0);
- else expect(fit.buttons).toBeGreaterThan(0);
- expect({
- pageScrolls: fit.pageScrolls,
- outOfView: fit.outOfView,
- }).toEqual({ pageScrolls: false, outOfView: [] });
- if (height === 760)
- expect(fit.cardScrolls).toBe(screen.scrolls === true);
- // The result says the figure the move screens said, counted the same way.
- const said = await page.evaluate(
- () => document.querySelector("main")?.textContent ?? "",
- );
- if (screen.hash === "#move-choice") {
- expect(said).toContain(
- "This removes about 20.2 GB of OpenBot files from this computer.",
- );
- expect(await moveChoiceRows(page)).toEqual(MOVE_CHOICE_ROWS);
- }
- if (screen.hash === "#move-confirm")
- expect(said).toContain(
- "Removes about 20.2 GB of OpenBot files.",
- );
- if (screen.hash.startsWith("#move-done"))
- expect(said).toContain("20.2 GB of OpenBot files removed");
- // Their own organization first and picked, then the others; one held, saying why.
- if (screen.hash === "#move-where")
- expect(
- await page.evaluate(() =>
- [
- ...document.querySelectorAll(
- "fieldset.picker > .tile > .tile-input",
- ),
- ].map((input) => [
- input.closest(".tile")?.querySelector(".tile-name")
- ?.textContent,
- input.checked,
- input.disabled,
- input.closest(".tile")?.querySelector(".tile-summary")
- ?.textContent,
- ]),
- ),
- ).toEqual([
- ["Sam's organization", true, false, "Your own organization."],
- [
- "Northwind Traders",
- false,
- false,
- "An organization you belong to.",
- ],
- [
- "Research Lab",
- false,
- true,
- "An admin of this organization hasn't let you use Bots here.",
- ],
- ]);
- if (screen.hash === "#move-not-allowed")
- expect(said).toContain(
- "Nothing was removed from this computer.",
- );
- expect(said.includes("of that is free space on your disk")).toBe(
- screen.hash === "#move-done-held",
- );
- // Still needing an AI: Connect your AI leads, and no Reconnect skips it.
- if (screen.hash === "#move-done-ai") {
- expect(said).toContain("Connect your AI first");
- expect(said).toContain("Then reconnect your apps");
- const buttons = await page.evaluate(() =>
- [...document.querySelectorAll("main button")].map(
- (button) => button.textContent,
- ),
- );
- expect(buttons).toEqual(["Connect your AI"]);
- }
- } finally {
- await page.close();
- }
- }, 30_000);
- }
- }
-
- // Keep, pressed where it shows with nothing scrolled first, leaves the move for OpenBot here.
- for (const [width, height] of [
- [1000, 800],
- [720, 560],
- ] as const)
- test(`at ${width}x${height}, Keep on a failed move with its technical details open opens OpenBot here`, async () => {
- const page = await browser.newPage({ viewport: { width, height } });
- try {
- await open(page, "#move-failed-detail", cloudBuilt);
- await page.getByRole("list", { name: "What moves" }).waitFor();
- await page
- .getByRole("button", { name: "Move to OpenBot Cloud" })
- .click();
- await page
- .getByRole("heading", {
- name: "The move didn't finish",
- exact: true,
- })
- .waitFor();
- await page.getByText("Technical details", { exact: true }).click();
- await page.evaluate(() => {
- const sheet = document.querySelector("main > .sheet");
- if (sheet) sheet.scrollTop = 0;
+ try {
+ await open(page, "?throws");
+ await page
+ .getByRole("heading", { name: "OpenBot hit a problem" })
+ .waitFor();
+ await page.waitForTimeout(300);
+ const shots = process.env.OPENBOT_APP_SHOTS;
+ if (shots)
+ await page.screenshot({
+ path: `${shots}/page-problem-${colorScheme}-${process.env.OPENBOT_APP_ENGINE ?? "chromium"}.png`,
});
- await page.waitForTimeout(600);
- const keep = await page
- .getByRole("button", { name: "Keep OpenBot on this computer" })
- .boundingBox();
- expect(keep).not.toBeNull();
- if (!keep) return;
- expect(keep.y + keep.height).toBeLessThanOrEqual(height);
- // The mouse, not a locator's click, which would scroll the button into view first.
- await page.mouse.click(
- keep.x + keep.width / 2,
- keep.y + keep.height / 2,
- );
- for (let i = 0; i < 50; i += 1) {
- if ((await calls(page)).includes("show_openbot")) break;
- await page.waitForTimeout(100);
- }
- const made = await calls(page);
- expect(made).toContain("keep_self_contained");
- expect(made).toContain("show_openbot");
- expect(made.indexOf("show_openbot")).toBeGreaterThan(
- made.indexOf("keep_self_contained"),
- );
- await page
- .getByRole("heading", {
- name: "The move didn't finish",
- exact: true,
- })
- .waitFor({ state: "hidden" });
- } finally {
- await page.close();
- }
- }, 30_000);
-
- /*
- * OpenBot for Business, picked on the move screen: the first screen's booker under the rows,
- * Book a demo in view at once, and nothing that moves or keeps. Taller than the window, it
- * scrolls in the card as it does on the first screen; the page never does, and nothing runs off
- * the card's side. OpenBot Cloud again brings back Continue and its promise, fitting as before.
- */
- for (const [width, height] of [
- [1000, 760],
- [720, 560],
- ] as const)
- for (const colorScheme of ["light", "dark"] as const)
- test(`at ${width}x${height}, OpenBot for Business on the move screen books a demo in the card and moves nothing (${colorScheme})`, async () => {
- const page = await browser.newPage({
- viewport: { width, height },
- colorScheme,
- });
- try {
- await routeCalendar(page);
- await open(page, "#move-choice", cloudBuilt);
- await page
- .getByRole("heading", {
- name: "Move to OpenBot Cloud?",
- exact: true,
- })
- .waitFor();
- await page
- .getByText("Your own cloud or on-prem. Book a demo.")
- .click();
- await page
- .locator(
- '.booking-calendar[data-ready] iframe[title="Booking calendar"]',
- )
- .waitFor();
- await page.mouse.move(0, 0);
- await page.waitForTimeout(600);
- if (shots)
- await page.screenshot({
- path: `${shots}/move-choice-business-${width}x${height}-${colorScheme}-${engine}.png`,
- });
- expect(await moveChoiceRows(page)).toEqual(MOVE_CHOICE_ROWS);
- const shape = await page.evaluate(() => {
- const card = document.querySelector(
- "main > .sheet",
- ) as HTMLElement;
- const view = card.getBoundingClientRect();
- const rows = [
- ...document.querySelectorAll("fieldset.picker.hosting > .tile"),
- ];
- const last = rows[rows.length - 1]?.getBoundingClientRect();
- const booker = document
- .querySelector(".business-booker")
- ?.getBoundingClientRect();
- const book = [...document.querySelectorAll("button")]
- .find((button) => button.textContent === "Book a demo")
- ?.getBoundingClientRect();
- const wider = [...card.querySelectorAll("*")].filter(
- (element) =>
- element.getBoundingClientRect().right > view.right + 0.5,
- );
- return {
- page:
- document.documentElement.scrollHeight <= window.innerHeight &&
- document.documentElement.scrollWidth <= window.innerWidth,
- cardScrolls: card.scrollHeight > card.clientHeight + 1,
- sideways: card.scrollWidth - card.clientWidth <= 0,
- wider: wider.map((element) => element.className),
- chosen: document.querySelector(".tile.chosen .tile-name")
- ?.textContent,
- underRows: !!booker && !!last && booker.top >= last.bottom,
- // Its first line shows under the rows without a scroll, at every size.
- bookerShows: !!booker && booker.top + 24 <= view.bottom,
- bookInView:
- !!book && book.top >= view.top && book.bottom <= view.bottom,
- // The screen's own buttons: none moves and none keeps.
- own: [
- ...document.querySelectorAll(
- "main > .sheet > .row button, main > .sheet > .step-footer button",
- ),
- ].map((button) => button.textContent),
- footnote: document.querySelector("main > .sheet > .footnote")
- ?.textContent,
- };
- });
- const { bookInView, ...laid } = shape;
- expect(laid).toEqual({
- page: true,
- cardScrolls: true,
- sideways: true,
- wider: [],
- chosen: "OpenBot for Business",
- underRows: true,
- bookerShows: true,
- own: [],
- footnote: undefined,
- });
- // At the window's default size Book a demo is in view at once; in the smallest window
- // the card scrolls to it, as it does to anything below the rows.
- if (height === 760) expect(bookInView).toBe(true);
- const scrolled = await page.evaluate(() => {
- const card = document.querySelector(
- "main > .sheet",
- ) as HTMLElement;
- const button = [...document.querySelectorAll("button")].find(
- (each) => each.textContent === "Book a demo",
- );
- button?.scrollIntoView({ block: "nearest" });
- const view = card.getBoundingClientRect();
- const box = button?.getBoundingClientRect();
- return (
- !!box &&
- box.top >= view.top &&
- box.bottom <= Math.min(window.innerHeight, view.bottom)
- );
- });
- expect(scrolled).toBe(true);
- const made = await calls(page);
- expect(made).not.toContain("move_preview");
- expect(made).not.toContain("move_to_cloud");
- expect(made).not.toContain("keep_self_contained");
- // OpenBot Cloud again: Continue and the promise, in view, the calendar gone.
- await page.getByText(/move to your OpenBot Cloud account/).click();
- await page
- .getByRole("button", { name: "Continue", exact: true })
- .waitFor();
- await page.mouse.move(0, 0);
- await page.waitForTimeout(300);
- const back = await page.evaluate(() => {
- const card = document.querySelector(
- "main > .sheet",
- ) as HTMLElement;
- const view = card.getBoundingClientRect();
- const go = [...document.querySelectorAll("button")]
- .find((button) => button.textContent === "Continue")
- ?.getBoundingClientRect();
- return {
- calendar: document.querySelectorAll(
- 'iframe[title="Booking calendar"]',
- ).length,
- continueInView:
- !!go &&
- go.top >= Math.max(0, view.top) &&
- go.bottom <= Math.min(window.innerHeight, view.bottom),
- footnote: document.querySelector("main > .sheet > .footnote")
- ?.textContent,
- };
- });
- expect(back).toEqual({
- calendar: 0,
- continueInView: true,
- footnote:
- "Nothing is removed from this computer until everything has arrived in OpenBot Cloud and been checked.",
- });
- } finally {
- await page.close();
- }
- }, 30_000);
- },
-);
-
-/** The commands that start or update OpenBot or its backend on this computer. */
-const STARTS_OR_UPDATES = [
- "wake_engine",
- "run_local_eval",
- "set_up_local_eval",
- "connect_local_eval",
- "upgrade_and_start",
- "start_stack",
-];
-
-/** The native commands the window has asked for, in order. */
-const calls = (page: Page) =>
- page.evaluate(
- () =>
- (globalThis as unknown as { __fake: { calls: string[] } }).__fake.calls,
- );
-
-/** Every heading the window shows from now on, kept as it shows. */
-const watchHeadings = (page: Page) =>
- page.evaluate(() => {
- const seen: string[] = [];
- (globalThis as unknown as { __headings: string[] }).__headings = seen;
- const note = () => {
- const heading = document.querySelector("main h1")?.textContent ?? "";
- if (heading && seen[seen.length - 1] !== heading) seen.push(heading);
- };
- note();
- new MutationObserver(note).observe(document.body, {
- subtree: true,
- childList: true,
- characterData: true,
- });
- });
-
-const headingsSeen = (page: Page) =>
- page.evaluate(
- () => (globalThis as unknown as { __headings: string[] }).__headings,
- );
-
-/*
- * A dogfooding report on 1.2.0-rc.1: installed over OpenBot (Self-Contained) on a Mac, the window
- * showed "Updating OpenBot" for about three minutes, and only then asked "Move to
- * OpenBot Cloud?". OpenBot Cloud is the default, so the question comes first now, before anything
- * starts or updates. Picking OpenBot Cloud updates and starts OpenBot under the move's own screen,
- * which fills in what moves once it can read it; Keep runs the update as it always has. In
- * Chromium, and with `OPENBOT_APP_ENGINE=webkit` in the engine the Mac window draws with.
- * `OPENBOT_APP_SHOTS=` keeps a screenshot of each screen.
- */
-describe.skipIf(!asked)(
- "the move to OpenBot Cloud, due at a relaunch that would update OpenBot",
- () => {
- const shots = process.env.OPENBOT_APP_SHOTS;
- const engine = process.env.OPENBOT_APP_ENGINE ?? "chromium";
- const shoot = async (page: Page, name: string) => {
- await page.mouse.move(0, 0);
- await page.waitForTimeout(500);
- if (shots)
- await page.screenshot({
- path: `${shots}/move-first-${name}-${engine}.png`,
- });
- };
-
- test("OpenBot Cloud: asked before any update, then no Self-Contained update screen, and the move completes", async () => {
- const page = await browser.newPage({
- viewport: { width: 1000, height: 760 },
- });
- try {
- await open(page, "#move-first", cloudBuilt);
- await page
- .getByRole("heading", { name: "Move to OpenBot Cloud?", exact: true })
- .waitFor();
- await watchHeadings(page);
- await shoot(page, "choice");
- // Nothing started or updated before the question.
- expect(
- (await calls(page)).filter((call) =>
- STARTS_OR_UPDATES.includes(call),
- ),
- ).toEqual([]);
-
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByText(
- "Getting your Bots ready to move. This can take a few minutes.",
- )
- .waitFor();
- // OpenBot updates behind the move's screen.
- for (let i = 0; i < 50; i += 1) {
- if ((await calls(page)).includes("upgrade_and_start")) break;
- await page.waitForTimeout(100);
- }
- expect(await calls(page)).toContain("upgrade_and_start");
- await shoot(page, "getting-ready");
- expect(
- await page.evaluate(
- () => document.querySelector("main h1")?.textContent,
- ),
- ).toBe("Move to OpenBot Cloud");
-
- await page.evaluate(() =>
- (
- globalThis as unknown as { __fake: { finishUpdate: () => void } }
- ).__fake.finishUpdate(),
- );
- await page.getByRole("list", { name: "What moves" }).waitFor();
- await shoot(page, "confirm");
- await page
- .getByRole("button", { name: "Move to OpenBot Cloud" })
- .click();
- await page
- .getByRole("heading", { name: "You're on OpenBot Cloud" })
- .waitFor();
- await shoot(page, "done");
-
- const made = await calls(page);
- expect(made).toContain("move_preview");
- expect(made).toContain("move_to_cloud");
- expect(made).not.toContain("show_openbot");
- expect(made).not.toContain("keep_self_contained");
- // What moves was read only once OpenBot was up.
- expect(made.indexOf("move_preview")).toBeGreaterThan(
- made.indexOf("upgrade_and_start"),
- );
- const headings = await headingsSeen(page);
- expect(headings).not.toContain("Updating OpenBot");
- expect(headings).not.toContain("Starting OpenBot");
- // Only the move's own screens, from the question to the end.
- expect(
- headings.filter(
- (heading) =>
- ![
- "Move to OpenBot Cloud?",
- "Move to OpenBot Cloud",
- "Moving to OpenBot Cloud",
- "You're on OpenBot Cloud",
- ].includes(heading),
- ),
- ).toEqual([]);
- } finally {
- await page.close();
- }
- }, 40_000);
-
- /*
- * FOUND IN A MAC UPGRADE CHECK of 1.2: the choice said the move removes about 23.1 GB and the
- * next screen 26.6 GB, measured after the update added the new release's files. The choice says
- * no figure while the update is still to come, and the next screen says the updated one only.
- */
- for (const colorScheme of ["light", "dark"] as const)
- test(`one size for what the move removes, from the updated OpenBot (${colorScheme})`, async () => {
- const page = await browser.newPage({
- viewport: { width: 1000, height: 760 },
- colorScheme,
- });
- const sized = async (name: string) => {
- await page.mouse.move(0, 0);
- await page.waitForTimeout(500);
- if (shots)
- await page.screenshot({
- path: `${shots}/move-first-size-${name}-${colorScheme}-${engine}.png`,
- });
- return page.evaluate(() => document.body.innerText);
- };
- try {
- await open(page, "#move-first", cloudBuilt);
- await page
- .getByRole("heading", {
- name: "Move to OpenBot Cloud?",
- exact: true,
- })
- .waitFor();
- const choice = await sized("choice");
- await page.getByRole("button", { name: "Continue" }).click();
- await page
- .getByText(
- "Getting your Bots ready to move. This can take a few minutes.",
- )
- .waitFor();
- const ready = await sized("getting-ready");
- await page.evaluate(() =>
- (
- globalThis as unknown as {
- __fake: { finishUpdate: () => void };
- }
- ).__fake.finishUpdate(),
- );
- await page.getByRole("list", { name: "What moves" }).waitFor();
- const confirm = await sized("confirm");
- expect(choice).toContain("move to your OpenBot Cloud account.");
- expect(choice).not.toContain("GB");
- expect(ready).not.toContain("GB");
- expect(confirm).toContain("Removes about 26.6 GB of OpenBot files.");
- expect(confirm).not.toContain("23.1 GB");
- } finally {
- await page.close();
- }
- }, 40_000);
-
- test("Keep: asked before any update, then the update runs as before and OpenBot opens", async () => {
- const page = await browser.newPage({
- viewport: { width: 1000, height: 760 },
- });
- try {
- await open(page, "#move-first", cloudBuilt);
- await page
- .getByRole("heading", { name: "Move to OpenBot Cloud?", exact: true })
- .waitFor();
- expect(
- (await calls(page)).filter((call) =>
- STARTS_OR_UPDATES.includes(call),
- ),
- ).toEqual([]);
- await page
- .getByText("Everything stays on this computer, as it is now.")
- .click();
- await shoot(page, "keep-picked");
- await page
- .getByRole("button", { name: "Keep OpenBot on this computer" })
- .click();
- await page.getByRole("heading", { name: "Updating OpenBot" }).waitFor();
- await shoot(page, "keep-updating");
- const made = await calls(page);
- expect(made.indexOf("keep_self_contained")).toBeGreaterThan(-1);
- expect(made.indexOf("upgrade_and_start")).toBeGreaterThan(
- made.indexOf("keep_self_contained"),
- );
-
- await page.evaluate(() =>
- (
- globalThis as unknown as { __fake: { finishUpdate: () => void } }
- ).__fake.finishUpdate(),
- );
- for (let i = 0; i < 50; i += 1) {
- if ((await calls(page)).includes("show_openbot")) break;
- await page.waitForTimeout(100);
- }
- const after = await calls(page);
- expect(after).toContain("show_openbot");
- expect(after).not.toContain("move_preview");
- } finally {
- await page.close();
- }
- }, 40_000);
- },
-);
-
-/*
- * FOUND ON 1.2.0-rc.3, a Mac, after an update: the setup window stayed a plain ground with nothing
- * on it, across two launches, while its page's code still ran. A screen that failed to draw took
- * every screen with it, leaving only the ground behind them. Now it shows "OpenBot hit a problem"
- * on the setup window's own failure box, with Reload and the logs, readable in light and dark.
- * `OPENBOT_APP_SHOTS=` keeps a screenshot of each.
- */
-describe.skipIf(!asked)("a screen that fails to draw", () => {
- for (const colorScheme of ["light", "dark"] as const)
- test(`shows OpenBot hit a problem, never the bare ground (${colorScheme})`, async () => {
- const page = await browser.newPage({
- viewport: { width: 1000, height: 800 },
- colorScheme,
- });
- try {
- await open(page, "?throws");
- await page
- .getByRole("heading", { name: "OpenBot hit a problem" })
- .waitFor();
- await page.waitForTimeout(300);
- const shots = process.env.OPENBOT_APP_SHOTS;
- if (shots)
- await page.screenshot({
- path: `${shots}/page-problem-${colorScheme}-${process.env.OPENBOT_APP_ENGINE ?? "chromium"}.png`,
- });
- const seen = await page.evaluate(() => {
- const shown = (selector: string) => {
- const element = document.querySelector(selector);
- const rect = element?.getBoundingClientRect();
- const style = element ? getComputedStyle(element) : null;
- return Boolean(
- rect &&
- rect.width > 0 &&
- rect.height > 0 &&
- rect.bottom <= window.innerHeight &&
- style?.visibility !== "hidden" &&
- style?.color !== style?.backgroundColor,
- );
- };
- const buttons = [...document.querySelectorAll("main button")].map(
- (button) => button.textContent,
+ const seen = await page.evaluate(() => {
+ const shown = (selector: string) => {
+ const element = document.querySelector(selector);
+ const rect = element?.getBoundingClientRect();
+ const style = element ? getComputedStyle(element) : null;
+ return Boolean(
+ rect &&
+ rect.width > 0 &&
+ rect.height > 0 &&
+ rect.bottom <= window.innerHeight &&
+ style?.visibility !== "hidden" &&
+ style?.color !== style?.backgroundColor,
+ );
+ };
+ const buttons = [...document.querySelectorAll("main button")].map(
+ (button) => button.textContent,
);
return {
// What a person reads, as the browser lays it out: not the bare ground.
@@ -5127,2350 +3739,6 @@ describe.skipIf(!asked)("a screen that fails to draw", () => {
});
});
-/** Approved account study: fixed heading, centered interaction and a top-safe scroll body. */
-describe.skipIf(!asked)("approved layout: account", () => {
- for (const [width, height] of [
- [1000, 800],
- [720, 560],
- ] as const) {
- for (const colorScheme of ["light", "dark"] as const) {
- test(`${width}x${height} ${colorScheme}: checking, code, engine wait and recovery remain reachable`, async () => {
- const page = await browser.newPage({
- viewport: { width, height },
- colorScheme,
- });
- const shot = async (state: string) => {
- await settled(page);
- if (process.env.OPENBOT_APP_SHOTS)
- await page.screenshot({
- path: `${process.env.OPENBOT_APP_SHOTS}/account-${state}-${width}x${height}-${colorScheme}.png`,
- });
- };
- const geometry = () =>
- page.evaluate(() => {
- const sheet =
- document.querySelector(".account-layout")!;
- const header = sheet
- .querySelector(".setup-header-block")!
- .getBoundingClientRect();
- const title = sheet
- .querySelector("h1")!
- .getBoundingClientRect();
- const body = sheet.querySelector(".setup-body")!;
- const content = sheet
- .querySelector(".setup-content")!
- .getBoundingClientRect();
- const box = body.getBoundingClientRect();
- const rail = document
- .querySelector(".rail-title")!
- .getBoundingClientRect();
- return {
- titleY: title.y,
- railY: rail.y,
- headerBottom: header.bottom,
- bodyTop: box.top,
- bodyBottom: box.bottom,
- bodyHeight: box.height,
- contentTop: content.top,
- contentBottom: content.bottom,
- contentHeight: content.height,
- centerOffset:
- (content.top + content.bottom - box.top - box.bottom) / 2,
- contentWidth: content.width,
- bodyScroll: body.scrollHeight,
- bodyClient: body.clientHeight,
- pageHeight: document.documentElement.scrollHeight,
- pageWidth: document.documentElement.scrollWidth,
- horizontalOverflow: [
- ...sheet.querySelectorAll(
- ".setup-body, .setup-content, .setup-panel, .sign-in-wait, .sign-in-code-row",
- ),
- ].some(
- (element) => element.scrollWidth > element.clientWidth + 1,
- ),
- };
- });
- // Scroll through the real body and check each action's center is unobstructed and focusable.
- const reachable = async (selector: string) => {
- const action = await page.evaluate((selector) => {
- const element = document.querySelector(selector)!;
- element.scrollIntoView({ block: "nearest" });
- element.focus();
- const box = element.getBoundingClientRect();
- const body = element
- .closest(".setup-body")!
- .getBoundingClientRect();
- const hit = document.elementFromPoint(
- box.x + box.width / 2,
- box.y + box.height / 2,
- );
- return {
- focused: document.activeElement === element,
- hit: element === hit || element.contains(hit),
- top: box.top,
- bottom: box.bottom,
- left: box.left,
- right: box.right,
- bodyTop: body.top,
- bodyBottom: body.bottom,
- };
- }, selector);
- expect(action.focused).toBe(true);
- expect(action.hit).toBe(true);
- expect(action.top).toBeGreaterThanOrEqual(action.bodyTop - 1);
- expect(action.bottom).toBeLessThanOrEqual(action.bodyBottom + 1);
- expect(action.left).toBeGreaterThanOrEqual(0);
- expect(action.right).toBeLessThanOrEqual(width);
- };
- const check = async (titleY?: number) => {
- const now = await geometry();
- expect(now.pageHeight).toBeLessThanOrEqual(height);
- expect(now.pageWidth).toBeLessThanOrEqual(width);
- expect(now.horizontalOverflow).toBe(false);
- expect(Math.abs(now.titleY - now.railY)).toBeLessThanOrEqual(1);
- if (titleY !== undefined) expect(now.titleY).toBe(titleY);
- expect(now.bodyTop).toBeGreaterThanOrEqual(now.headerBottom - 1);
- expect(now.bodyBottom).toBeLessThanOrEqual(height);
- expect(now.contentWidth).toBeLessThanOrEqual(600);
- if (
- now.contentHeight + (width === 1000 ? 60 : 36) <=
- now.bodyHeight
- ) {
- if (width === 720) {
- expect(
- Math.abs(now.contentTop - now.bodyTop - 18),
- ).toBeLessThanOrEqual(1);
- } else {
- expect(Math.abs(now.centerOffset)).toBeLessThanOrEqual(1);
- expect(now.contentTop - now.headerBottom).toBeGreaterThan(29);
- }
- } else {
- expect(now.bodyScroll).toBeGreaterThan(now.bodyClient);
- }
- return now;
- };
- try {
- await open(page, "#signin");
- await page
- .getByRole("button", { name: "Install", exact: true })
- .waitFor();
- await page.evaluate(() => {
- globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
- mode: "never",
- });
- globalThis.__workbench!.setAnswer("copilotkit_sign_in_page", {
- mode: "value",
- value: null,
- });
- });
- await page
- .getByRole("button", { name: "Install", exact: true })
- .click();
- await page
- .getByText("Checking your OpenBot account…", { exact: true })
- .waitFor();
- await shot("checking");
- const initial = await check();
- expect(await page.locator(".sign-in-wait h3").count()).toBe(0);
- expect(
- await page.locator(".sign-in-wait .step-spinner").count(),
- ).toBe(1);
- await reachable(".sign-in-wait button");
- await page.evaluate(() =>
- globalThis.__workbench!.setAnswer("copilotkit_sign_in_page", {
- mode: "value",
- value: {
- url: "https://dashboard.copilotkit.ai/cli-auth/device?user_code=WXYZ-2345",
- userCode: "WXYZ-2345",
- },
- }),
- );
- await page.getByText("WXYZ-2345", { exact: true }).waitFor();
- await page.evaluate(() => {
- document.querySelector(".setup-body")!.scrollTop = 0;
- });
- await shot("code");
- await check(initial.titleY);
- const code = await page.evaluate(() => {
- const element =
- document.querySelector(".sign-in-code")!;
- const box = element.getBoundingClientRect();
- const row = element.parentElement!.getBoundingClientRect();
- const group = element.closest(".sign-in-wait")!;
- const instruction = group.querySelector("h3")!;
- const status = group.querySelector(".status-line")!;
- return {
- instruction: instruction.textContent,
- status: status.textContent,
- spinners: group.querySelectorAll(".step-spinner").length,
- instructionSize: Number.parseFloat(
- getComputedStyle(instruction).fontSize,
- ),
- statusSize: Number.parseFloat(getComputedStyle(status).fontSize),
- instructionBottom: instruction.getBoundingClientRect().bottom,
- statusTop: status.getBoundingClientRect().top,
- statusBottom: status.getBoundingClientRect().bottom,
- codeTop: row.top,
- left: box.left,
- right: box.right,
- rowLeft: row.left,
- rowRight: row.right,
- width: element.scrollWidth,
- client: element.clientWidth,
- help: group.textContent?.includes("open the sign-in page again"),
- actions: [...group.querySelectorAll("button, a")].map(
- (el) => el.textContent,
- ),
- };
- });
- expect(code.instruction).toBe(
- "Finish signing in to OpenBot in your browser…",
- );
- expect(code.status).toBe("Waiting for you to finish signing in…");
- expect(code.spinners).toBe(1);
- expect(code.instructionSize).toBeGreaterThan(code.statusSize);
- expect(code.instructionBottom).toBeLessThanOrEqual(code.statusTop);
- expect(code.statusBottom).toBeLessThanOrEqual(code.codeTop);
- expect(code.left).toBeGreaterThanOrEqual(code.rowLeft);
- expect(code.right).toBeLessThanOrEqual(code.rowRight);
- expect(code.width).toBeLessThanOrEqual(code.client + 1);
- expect(code.help).toBe(true);
- expect(code.actions).toEqual(["Open the sign-in page", "Cancel"]);
- await reachable(".sign-in-wait a");
- await page
- .getByRole("link", { name: "Open the sign-in page" })
- .click();
- expect(await page.evaluate(() => globalThis.__fake!.opened)).toEqual([
- "https://dashboard.copilotkit.ai/cli-auth/device?user_code=WXYZ-2345",
- ]);
- await page.keyboard.press("Tab");
- expect(
- await page.evaluate(() => document.activeElement?.textContent),
- ).toBe("Cancel");
- await reachable(".sign-in-wait button");
- // A failed browser approval retains a reachable retry, then starts a fresh attempt.
- await page.evaluate(() =>
- globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
- mode: "fail",
- problem: { said: "Sign-in was interrupted." },
- }),
- );
- await page
- .getByText("Sign-in didn’t finish. Try again.", { exact: true })
- .waitFor();
- await shot("sign-in-failure");
- await check(initial.titleY);
- await reachable(".setup-panel .row button");
- await page.evaluate(() =>
- globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
- mode: "never",
- }),
- );
- await page
- .getByRole("button", { name: "Try again", exact: true })
- .click();
- await page.getByText("WXYZ-2345", { exact: true }).waitFor();
- await page
- .getByRole("button", { name: "Cancel", exact: true })
- .click();
- await page
- .getByRole("button", {
- name: "Sign in for a free local license key",
- })
- .waitFor();
- expect(
- await page.evaluate(() =>
- globalThis.__fake!.calls?.includes("cancel_local_eval"),
- ),
- ).toBe(true);
- await page
- .getByRole("button", {
- name: "Sign in for a free local license key",
- })
- .click();
- await page.getByText("WXYZ-2345", { exact: true }).waitFor();
- await page.evaluate(() => {
- globalThis.__workbench!.setAnswer("local_eval_terms", {
- mode: "value",
- value: { status: "engine-not-ready" },
- });
- globalThis.__workbench!.setAnswer("sign_in_to_copilotkit", {
- mode: "value",
- value: { signedIn: true },
- });
- });
- await page
- .getByRole("heading", { name: "Setting up this computer" })
- .waitFor();
- await shot("engine-wait");
- await check(initial.titleY);
- expect(await page.locator(".sign-in-code").count()).toBe(0);
- await page.evaluate(() => {
- globalThis.__workbench!.setAnswer("connect_copilotkit_apps", {
- mode: "fail",
- problem: {
- said:
- "OpenBot couldn't connect your apps. " +
- "Check the internet connection and the organization's sign-in settings before trying again. ".repeat(
- 12,
- ),
- detail: "The connection was reset while connecting apps.",
- },
- });
- globalThis.__workbench!.setAnswer("local_eval_terms", {
- mode: "value",
- value: { status: "not-required" },
- });
- });
- await page
- .getByRole("heading", { name: "Connect your apps" })
- .waitFor();
- await shot("long-failure");
- await check(initial.titleY);
- await reachable(".setup-panel .row button");
- await page.keyboard.press("Tab");
- expect(
- await page.evaluate(() => document.activeElement?.textContent),
- ).toBe("Continue");
- await reachable(".setup-panel .row button.quiet");
- await shot("failure-recovery");
- await page
- .getByRole("button", { name: "Continue", exact: true })
- .click();
- await page
- .getByRole("heading", { name: "Connect your AI" })
- .waitFor();
- } finally {
- await page.close();
- }
- }, 30_000);
- }
- }
-});
-
-/** The approved agreement keeps the document, explanation, Read and Accept in one centered group. */
-describe.skipIf(!asked)("approved layout: agreement", () => {
- for (const [width, height] of [
- [1000, 800],
- [720, 560],
- ] as const) {
- for (const colorScheme of ["dark", "light"] as const) {
- test(`${width}x${height} ${colorScheme}: agreement is whole and centered`, async () => {
- const page = await browser.newPage({
- viewport: { width, height },
- colorScheme,
- });
- try {
- await open(page, "#licence-installing");
- await page
- .getByRole("button", { name: "Install", exact: true })
- .click();
- await page
- .getByRole("heading", { name: "Accept the license agreement" })
- .waitFor();
- await settled(page);
- if (process.env.OPENBOT_APP_SHOTS)
- await page.screenshot({
- path: `${process.env.OPENBOT_APP_SHOTS}/license-${width}-${colorScheme}.png`,
- });
- const geometry = await page.evaluate(() => {
- const sheet =
- document.querySelector