From 36847223443a2e671eabc6c3451163953097592a Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:06:06 -0800 Subject: [PATCH 01/21] CI: reuse tested merge trees and run browser engines separately --- .github/ci-budgets.json | 1 + .github/workflows/ci.yml | 26 ++++- scripts/ci-changes.test.ts | 76 +++++++++++++++ scripts/ci-changes.ts | 194 +++++++++++++++++++++++++++++-------- 4 files changed, 253 insertions(+), 44 deletions(-) diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json index f220da6538..cfc92d785f 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)": 12, "app (real browser, WebKit)": 12, "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 f7a4580907..dde89693a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -100,6 +100,18 @@ 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: + name: ci-tested-tree-${{ github.run_id }}-${{ github.run_attempt }} + 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 @@ -597,7 +609,13 @@ jobs: # instead of 5, and the job has an hour. A test's own timeout and every bound a test asserts stay # as they are. On the larger runners nothing changes: eight workers, 5 seconds, 30 minutes. app-browser-webkit: - name: app (real browser, WebKit) + name: app (real browser, ${{ matrix.engine }}) + # Each engine keeps all its coverage, on its own runner. A failure reruns only that engine, + # and eight workers no longer host Chromium and WebKit together on the same runner. + strategy: + fail-fast: false + matrix: + engine: [Chromium, WebKit] needs: changes # 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. @@ -613,6 +631,7 @@ 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' }} + BROWSER_ENGINE: ${{ matrix.engine == 'WebKit' && 'webkit' || 'chromium' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -695,12 +714,13 @@ 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" "${files[@]}" # 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. - - run: | + - if: matrix.engine == 'WebKit' + run: | docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index f8c893b1eb..72aa73f53c 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -23,6 +23,7 @@ import { queuedPullRequest, SHARDS, SUITE_RULE, + testedCheckout, } from "./ci-changes"; import type { CiRun } from "./release-ci-gate"; @@ -858,6 +859,32 @@ describe("a merge group", () => { const COMPONENTS = CI_RULES.find((rule) => rule.output === "components") ?.checks as string[]; const GROUP: MergeGroup = { head: "g", pr: { labels: [], head: "h" } }; + + test("compares a PR's passing jobs with its tested merge tree, never its untested head", () => { + // h needs a fix on main. CI passed on merge m with that fix. Main later reverted it: + // g equals h, but differs from the actual passing merge m, so its checks are owed. + const base = groupDeps({ + passed: { b: ALL_CI, h: ALL_CI }, + changes: { b: ["app/src/feature.ts"], h: [], m: ["shared/fix.ts"] }, + }); + const proof = { + ...base, + testedTrees: (sha: string) => + sha === "h" ? ["m"] : sha === "b" ? ["b"] : [], + }; + const result = decideMergeGroup("ci", ["app/src/feature.ts"], proof, GROUP); + expect(result.run.suite).toBe(true); + expect(result.run.app_browser).toBe(true); + expect(result.run.build).toBe(true); + }); + + test("full-ci forces checks even for docs alone", () => { + const result = decideMergeGroup("ci", ["README.md"], REAL, { + head: "g", + pr: { labels: ["full-ci"] }, + }); + expect(running(result)).toEqual(everyJob); + }); /** The pull request changed the app; main changed a harness since the pull request branched. */ const APP_PR_HARNESS_MAIN = { passed: { @@ -967,6 +994,30 @@ describe("a merge group", () => { }); }); +describe("the checkout a passing run proves", () => { + const head = "a".repeat(40); + const merge = "b".repeat(40); + test("CI's PR run requires its recorded merge commit, with no fallback to its head", () => { + expect(testedCheckout("ci", head, "pull_request")).toBeUndefined(); + expect(testedCheckout("ci", head, "pull_request", `${merge}\n`)).toBe( + merge, + ); + for (const invalid of ["", "main", "b".repeat(39), `${merge}\n${head}`]) { + expect( + testedCheckout("ci", head, "pull_request", invalid), + ).toBeUndefined(); + } + }); + test("main and merge groups prove their SHA, and Desktop explicitly tests the PR head", () => { + expect(testedCheckout("ci", head, "push")).toBe(head); + expect(testedCheckout("ci", head, "merge_group")).toBe(head); + expect(testedCheckout("desktop", head, "pull_request")).toBe(head); + expect( + testedCheckout("ci", head, "pull_request_target", merge), + ).toBeUndefined(); + }); +}); + describe("main's run of a push", () => { const SHA = "cad6dc08eb158054ed3fc37c0aa7b9d0cb3dc4eb"; const REPOSITORY = "CopilotKit/OpenBot"; @@ -1273,6 +1324,31 @@ function jobNames(workflow: string): string[] { } describe("the rules name the jobs the workflows run", () => { + test("the cross-browser list runs each engine in a separate job, retaining both required results", () => { + const ci = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: Record< + string, + { + strategy?: { matrix?: { engine?: string[] }; "fail-fast"?: boolean }; + steps: { run?: string; if?: string }[]; + } + >; + }; + const job = ci.jobs["app-browser-webkit"]; + expect(job.strategy?.matrix?.engine).toEqual(["Chromium", "WebKit"]); + expect(job.strategy?.["fail-fast"]).toBe(false); + const rule = CI_RULES.find((rule) => rule.output === "app_browser_webkit"); + expect(rule?.checks).toEqual([ + "app (real browser, Chromium)", + "app (real browser, WebKit)", + ]); + const clipboard = job.steps.find((step) => + step.run?.includes("copies with one press"), + ); + expect(clipboard?.if).toBe("matrix.engine == 'WebKit'"); + }); test("ci.yml: every check a rule waits on is a job, and the shards are the matrix's", () => { const names = jobNames("ci.yml"); for (const check of ALL_CI) expect(names).toContain(check); diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index a311ff90d1..d4bf05b6a5 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -47,7 +47,8 @@ */ import { randomBytes } from "node:crypto"; -import { appendFileSync, readFileSync } from "node:fs"; +import { appendFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { changedFiles } from "./release-candidate-check"; import { @@ -258,7 +259,7 @@ export const CI_RULES: Rule[] = [ // the packages the app imports and its own tests, and no server: a pull request runs it when one // of those changes. A merge group and main run it every time. output: "app_browser_webkit", - checks: ["app (real browser, WebKit)"], + checks: ["app (real browser, Chromium)", "app (real browser, WebKit)"], reads: (path) => (isCode(path) && appInputs(path)) || ciInputs(path), }, { @@ -375,6 +376,8 @@ export type PullRequest = { headRepository: string; repository: string; head: string; + /** The actual CI checkout (a PR's synthetic merge). Desktop's jobs test the head itself. */ + checkout?: string; base: string; }; @@ -385,6 +388,8 @@ export type Deps = { ancestors: (head: string) => string[]; /** The job names that passed on a commit in this workflow's runs, the current run left out. */ passed: (sha: string) => Set; + /** Actual checkout trees where these jobs passed, rather than the run's PR head SHA. */ + testedTrees?: (sha: string, checks: string[]) => string[]; /** What changed between two commits. */ diff: (from: string, to: string) => Change[]; /** The suite's test files that name any of these paths. */ @@ -481,7 +486,12 @@ export function decide( // A release PR that changes more than the release files is checked like any other PR. } - return decideFrom(workflow, pr.head, [deps.ancestors(pr.head)], deps); + return decideFrom( + workflow, + pr.checkout ?? pr.head, + [deps.ancestors(pr.head)], + deps, + ); } /** @@ -509,14 +519,17 @@ function decideFrom( }; /** Along each history, the newest commit where every one of these checks passed. */ const baselinesOf = (checks: string[]) => - histories - .map((ancestors) => - ancestors.find((sha) => { - const names = passed(sha); - return checks.every((check) => names.has(check)); - }), - ) - .filter((sha): sha is string => sha !== undefined); + histories.flatMap((ancestors) => { + for (const sha of ancestors) { + const trees = deps.testedTrees + ? deps.testedTrees(sha, checks) + : checks.every((check) => passed(sha).has(check)) + ? [sha] + : []; + if (trees.length > 0) return trees; + } + return []; + }); const changesSince = new Map(); const since = (sha: string) => { let changes = changesSince.get(sha); @@ -894,6 +907,16 @@ export function decideMergeGroup( group?: MergeGroup, ): Decision & { ignoredOnly: boolean } { const rules = rulesOf(workflow); + // The explicit override applies even when every changed file is a document. + if (group?.pr?.labels.includes("full-ci")) { + return { + ...everything( + rules, + "A merge group of a pull request labelled full-ci: everything runs.", + ), + ignoredOnly: false, + }; + } // A file no job's rule reads: CHANGELOG.md, and the docs. A test that names a doc still runs. const unread = (path: string) => isIgnored(path) || @@ -964,6 +987,7 @@ export function decideMergeGroup( const decision = decideFrom(workflow, group.head, histories, { ancestors, passed, + testedTrees: deps.testedTrees, diff, releaseViolations, mentions: deps.mentions, @@ -998,10 +1022,31 @@ function exec(cmd: string[], allowFailure = false): string { type ApiRun = { id: number; path: string; + event: string; + run_attempt: number; head_repository?: { full_name?: string } | null; }; type ApiJob = { name: string; conclusion: string | null }; +/** The run API's SHA proves CI's PR head only when checkout explicitly used it (Desktop). */ +export function testedCheckout( + workflow: Workflow, + head: string, + event: string, + proof?: string, +): string | undefined { + const sha = /^[0-9a-f]{40}$/; + if (!sha.test(head)) return undefined; + if ( + workflow === "desktop" || + ["push", "merge_group", "schedule", "workflow_dispatch"].includes(event) + ) + return head; + if (event === "pull_request" && sha.test(proof?.trim() ?? "")) + return proof?.trim(); + return undefined; +} + function liveDeps( workflow: Workflow, repository: string, @@ -1009,7 +1054,101 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); + const records = new Map>>(); + const recordsAt = (sha: string): Map> => { + const cached = records.get(sha); + if (cached) return cached; + const trees = new Map>(); + const runs = ( + JSON.parse( + exec([ + "gh", + "api", + `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, + ]), + ).workflow_runs as ApiRun[] + ).filter( + (run) => + run.path === WORKFLOW_PATH[workflow] && + run.id !== currentRun && + trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), + ); + for (const run of runs) { + let tree = testedCheckout(workflow, sha, run.event); + if (workflow === "ci" && run.event === "pull_request") { + // Actions attributes this run to the PR head, but checkout tested its temporary merge. + // Runs before this proof existed, expired artifacts and unreachable trees never stand in. + const directory = mkdtempSync(join(tmpdir(), "openbot-ci-tree-")); + try { + const downloaded = Bun.spawnSync( + [ + "gh", + "run", + "download", + String(run.id), + "--repo", + repository, + "--name", + `ci-tested-tree-${run.id}-${run.run_attempt}`, + "--dir", + directory, + ], + { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, + ); + if (downloaded.exitCode !== 0) continue; + tree = testedCheckout( + workflow, + sha, + run.event, + readFileSync(join(directory, "ci-tested-tree.txt"), "utf8"), + ); + if (!tree) continue; + const present = () => + Bun.spawnSync(["git", "cat-file", "-e", `${tree}^{commit}`], { + stdout: "pipe", + stderr: "pipe", + }).exitCode === 0; + if (!present()) { + const fetched = Bun.spawnSync( + [ + "git", + "fetch", + "--no-tags", + "--filter=blob:none", + "origin", + tree, + ], + { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, + ); + if (fetched.exitCode !== 0 || !present()) continue; + } + } catch { + continue; + } finally { + rmSync(directory, { recursive: true, force: true }); + } + } + if (!tree) continue; + const names = trees.get(tree) ?? new Set(); + const jobs = JSON.parse( + exec([ + "gh", + "api", + `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, + ]), + ).jobs as ApiJob[]; + for (const job of jobs) + if (job.conclusion === "success") names.add(job.name); + trees.set(tree, names); + } + records.set(sha, trees); + return trees; + }; return { + testedTrees: (sha, checks) => + [...recordsAt(sha)] + .filter(([, names]) => checks.every((check) => names.has(check))) + .map(([tree]) => tree), ancestors: (head) => exec([ "git", @@ -1020,36 +1159,8 @@ function liveDeps( ]) .split("\n") .filter(Boolean), - passed: (sha) => { - const names = new Set(); - const runs = ( - JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, - ]), - ).workflow_runs as ApiRun[] - ).filter( - (run) => - run.path === WORKFLOW_PATH[workflow] && - run.id !== currentRun && - trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), - ); - for (const run of runs) { - const jobs = JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, - ]), - ).jobs as ApiJob[]; - for (const job of jobs) { - if (job.conclusion === "success") names.add(job.name); - } - } - return names; - }, + passed: (sha) => + new Set([...recordsAt(sha).values()].flatMap((names) => [...names])), diff: (from, to) => { const out = exec([ "git", @@ -1248,6 +1359,7 @@ if (import.meta.main) { headRepository: pull.head.repo?.full_name ?? "", repository, head: pull.head.sha, + checkout: workflow === "ci" ? process.env.GITHUB_SHA : undefined, base: pull.base.sha, }; // main's own run of a push. Not the release's call of these checks, which sees the push that From 3baeceb6511c88d0c022b31205b54838c8cb1984 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:15:39 -0800 Subject: [PATCH 02/21] CI: preserve required coverage when reusing passing checks --- .github/workflows/ci.yml | 10 +- scripts/ci-changes.test.ts | 392 ++++++++++++++++++++++++++++++++++- scripts/ci-changes.ts | 88 ++++++-- scripts/ci-run-tests.test.ts | 154 ++++++++++++++ scripts/ci-run-tests.ts | 9 + 5 files changed, 622 insertions(+), 31 deletions(-) create mode 100644 scripts/ci-run-tests.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dde89693a2..167a833fc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,8 +54,9 @@ jobs: # files alone run just those tests, 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 @@ -108,7 +109,8 @@ jobs: - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'pull_request' with: - name: ci-tested-tree-${{ github.run_id }}-${{ github.run_attempt }} + # 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 @@ -916,7 +918,7 @@ 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 - name: Run the changed tests env: diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 72aa73f53c..ac33818e4b 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1,5 +1,14 @@ import { describe, expect, test } from "bun:test"; -import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { CACHE_WRITERS, @@ -125,6 +134,114 @@ const isBrowserFile = (file: string) => /** This checkout, as the merge group's `changes` job reads it. */ const REAL = { mentions: realMentions, read: readTracked }; +/** Runs the real Actions entry point with a local repository and recorded GitHub responses. */ +function actionsDecision(options: { + event: "pull_request" | "merge_group" | "push"; + responses: (sha: string) => Record; + proof?: boolean | string; +}) { + const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); + try { + const git = (...args: string[]) => { + const result = Bun.spawnSync(["git", ...args], { cwd: directory }); + if (result.exitCode !== 0) throw new Error(result.stderr.toString()); + return result.stdout.toString().trim(); + }; + git("init", "--quiet"); + git( + "-c", + "user.name=CI", + "-c", + "user.email=ci@example.test", + "commit", + "--quiet", + "--allow-empty", + "-m", + "test", + ); + const sha = git("rev-parse", "HEAD"); + const repository = "CopilotKit/OpenBot"; + const fixture = join(directory, "fixture.json"); + writeFileSync( + fixture, + JSON.stringify({ + responses: options.responses(sha), + proof: options.proof, + sha, + }), + ); + const gh = join(directory, "gh"); + writeFileSync( + gh, + `#!${process.execPath} +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +const fixture = JSON.parse(readFileSync(process.env.CI_FIXTURE, "utf8")); +const args = process.argv.slice(2); +if (args[0] === "run" && args[1] === "download") { + if (!fixture.proof || args[args.indexOf("--name") + 1] !== "ci-tested-tree-1") process.exit(1); + writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), typeof fixture.proof === "string" ? fixture.proof : fixture.sha); +} else { + const endpoint = args.find((arg) => arg.startsWith("repos/")); + if (!(endpoint in fixture.responses)) process.exit(1); + const response = fixture.responses[endpoint]; + console.log(JSON.stringify(args.includes("--slurp") && !Array.isArray(response) ? [response] : response)); +} +`, + ); + chmodSync(gh, 0o755); + const event = join(directory, "event.json"); + writeFileSync( + event, + JSON.stringify({ + before: "b".repeat(40), + pull_request: { + labels: [], + head: { ref: "fix", sha, repo: { full_name: repository } }, + base: { sha }, + }, + merge_group: { + base_sha: "b".repeat(40), + head_sha: sha, + head_ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha}`, + }, + }), + ); + const output = join(directory, "outputs"); + const result = Bun.spawnSync( + [process.execPath, join(ROOT, "scripts/ci-changes.ts"), "ci"], + { + cwd: directory, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH}`, + CI_FIXTURE: fixture, + GITHUB_EVENT_NAME: options.event, + GITHUB_EVENT_PATH: event, + GITHUB_REPOSITORY: repository, + GITHUB_SHA: sha, + GITHUB_REF: + options.event === "push" ? "refs/heads/main" : "refs/pull/7/merge", + GITHUB_RUN_ID: "2", + WORKFLOW_NAME: "CI", + GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: "", + }, + }, + ); + expect(result.exitCode).toBe(0); + return Object.fromEntries( + [ + ...readFileSync(output, "utf8").matchAll( + /^(\w+)<<([^\n]+)\n([^\n]*)\n\2$/gm, + ), + ].map((match) => [match[1], match[3]]), + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + const PR: PullRequest = { labels: [], headRef: "fix/a-thing", @@ -252,6 +369,48 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("compares the current PR's tested synthetic merge rather than its head", () => { + const base = deps({ passed: { c2: ALL_CI }, changes: {} }); + const decision = decide( + "ci", + { ...PR, checkout: "merge" }, + { + ...base, + diff: (from, to) => { + expect(from).toBe("c2"); + return to === "merge" + ? [{ path: "app/src/main.tsx", deleted: false }] + : []; + }, + }, + ); + expect(decision.run.suite).toBe(true); + }); + + test("a suite whose shards passed but aggregate failed must run again", () => { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI.filter((check) => check !== "tests") }, + changes: { c2: ["README.md"] }, + }), + ); + expect(decision.run.suite).toBe(true); + }); + + test("API examples read by the WebKit clipboard scenario require its browser jobs", () => { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: ["api/openapi.yaml"] }, + }), + ); + expect(decision.run.app_browser_webkit).toBe(true); + }); + test("one test file changed since a green push runs that test and the lint, nothing else", () => { const decision = decide( "ci", @@ -734,6 +893,53 @@ describe("CHANGELOG.md", () => { describe("a merge group", () => { const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); + test("a source file renamed to a document cannot use the docs-only shortcut", () => { + const result = actionsDecision({ + event: "merge_group", + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + files: [ + { + filename: "README.md", + previous_filename: "server/src/main.ts", + status: "renamed", + }, + ], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { workflow_runs: [] }, + }), + }); + expect(result.ignored_only).toBe("false"); + expect(result.suite).toBe("true"); + expect(result.build).toBe("true"); + }); + + test("rename expansion does not mistake 150 complete API entries for the 300-file cap", () => { + const result = actionsDecision({ + event: "merge_group", + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + files: Array.from({ length: 150 }, (_, index) => ({ + filename: `docs/new-${index}.md`, + previous_filename: `docs/old-${index}.md`, + status: "renamed", + })), + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + }), + }); + expect(result.ignored_only).toBe("true"); + expect(result.suite).toBe("false"); + }); + test("that changes only CHANGELOG.md runs nothing, not even the tests that name it", () => { const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL); expect(running(decision)).toEqual([]); @@ -995,6 +1201,74 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("a successful partial rerun reuses the original run-scoped checkout proof", () => { + const result = actionsDecision({ + event: "pull_request", + proof: true, + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + path: ".github/workflows/ci.yml", + event: "pull_request", + run_attempt: 2, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + }), + }); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + }); + + test("missing or malformed artifacts cannot stand in for a tested checkout", () => { + for (const proof of [false, "not a commit"]) { + const result = actionsDecision({ + event: "pull_request", + proof, + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + path: ".github/workflows/ci.yml", + event: "pull_request", + run_attempt: 2, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + }), + }); + expect(result.suite).toBe("true"); + expect(result.static).toBe("true"); + } + }); + + test("the proof uploader uses the same run-scoped name across attempts", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: { + changes: { steps: { uses?: string; with?: { name?: string } }[] }; + }; + }; + const artifact = workflow.jobs.changes.steps.find((step) => + step.uses?.startsWith("actions/upload-artifact@"), + ); + expect(artifact?.with?.name).toBe( + `ci-tested-tree-${expression("github.run_id")}`, + ); + }); + const head = "a".repeat(40); const merge = "b".repeat(40); test("CI's PR run requires its recorded merge commit, with no fallback to its head", () => { @@ -1037,11 +1311,101 @@ describe("main's run of a push", () => { }); const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); - test("a commit the merge queue passed runs none of the checks again, and names the queue's run", () => { - const decision = decideMainPush([ciRun()], SHA, REPOSITORY, [ - "app/src/lib/marks.ts", + test("main runs the macOS startup omitted by a queue that ran Windows startup", () => { + const decision = decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["app/src/main.tsx"], + () => [{ name: "startup (windows-latest)", conclusion: "success" }], + ); + expect(running(decision)).toEqual(["startup"]); + }); + + test("main reuses a queue's safely skipped startup", () => { + const decision = decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["app/src/main.tsx"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ); + expect(running(decision)).toEqual([]); + }); + + test("main reuses an explicitly skipped whole startup matrix", () => { + const decision = decideMainPush([ciRun()], SHA, REPOSITORY, [], () => [ + { name: `startup (${expression("matrix.os")})`, conclusion: "skipped" }, ]); expect(running(decision)).toEqual([]); + }); + + test("main runs startup when queue jobs are missing or unreadable", () => { + for (const read of [ + () => [], + () => { + throw new Error("unreadable jobs"); + }, + ]) { + expect( + decideMainPush([ciRun()], SHA, REPOSITORY, [], read).run.startup, + ).toBe(true); + } + }); + + test("main reads every page of actual queue jobs and handles unreadable results", () => { + for (const conclusion of ["success", "skipped", undefined]) { + const result = actionsDecision({ + event: "push", + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/workflows/ci.yml/runs?head_sha=${sha}&event=merge_group&per_page=100`]: + { workflow_runs: [ciRun({ id: 1, head_sha: sha })] }, + [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + files: [{ filename: "app/src/main.tsx" }], + }, + ...(conclusion + ? { + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + [ + { jobs: [{ name: "build", conclusion: "success" }] }, + { + jobs: [{ name: "startup (windows-latest)", conclusion }], + }, + ], + } + : {}), + }), + }); + expect(result.startup).toBe(conclusion === "skipped" ? "false" : "true"); + expect(result.suite).toBe("false"); + } + }); + + test("the latest attempt's explicit startup skip supersedes older queue attempts", () => { + const result = decideMainPush([ciRun()], SHA, REPOSITORY, [], () => [ + { + name: "startup (windows-latest)", + conclusion: "success", + run_attempt: 1, + }, + { + name: "startup (windows-latest)", + conclusion: "skipped", + run_attempt: 2, + }, + ]); + expect(result.run.startup).toBe(false); + }); + + test("a commit the merge queue passed runs none of the checks again, and names the queue's run", () => { + const decision = decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["app/src/lib/marks.ts"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ); + expect(running(decision)).toEqual([]); expect(decision.queueRun?.html_url).toBe( "https://github.com/CopilotKit/OpenBot/actions/runs/46561913641", ); @@ -1081,16 +1445,24 @@ describe("main's run of a push", () => { test("a queue-tested push still runs the jobs whose cache key it changed", () => { expect( running( - decideMainPush([ciRun()], SHA, REPOSITORY, [ - "mobile/package-lock.json", - ]), + decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["mobile/package-lock.json"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ), ), ).toEqual(["mobile"]); expect( running( - decideMainPush([ciRun()], SHA, REPOSITORY, [ - "agent-crewai/requirements.txt", - ]), + decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["agent-crewai/requirements.txt"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ), ), ).toEqual(["python_harness"]); // Files it could not read run every job that writes a cache, never a check it can skip less. diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index d4bf05b6a5..0963125531 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -24,7 +24,8 @@ * * main's own run of a commit the merge queue merged runs none of CI's checks again: the queue's run * tested that very commit, so it skips them and names that run (decideMainPush), keeping only the - * jobs that write a cache the push changed the key of. A push the queue did not test (an admin's + * jobs that write a cache the push changed the key of, and macOS startup when the queue ran only + * Windows. A push the queue did not test (an admin's * merge, a direct push) runs everything. A merge group (decideMergeGroup) runs nothing when all it * changes is files no check reads (CHANGELOG.md, docs no test names); otherwise each job is decided * from two histories, main's and the queued pull request's, and runs unless nothing it reads changed @@ -176,6 +177,8 @@ const appInputs = matcher( "tests/**", "desktop/src/**", "scripts/**", + // connect-your-ai's browser fixture reads the API's own response examples. + "api/openapi.yaml", "package.json", "bun.lock", "bunfig.toml", @@ -318,13 +321,16 @@ export const CI_RULES: Rule[] = [ }, ]; -/** The suite: every shard must have passed on the commit it stands in from. */ +/** The suite: every shard and the aggregate count/floor check must have passed. */ export const SUITE_RULE: Rule = { output: "suite", - checks: Array.from( - { length: SHARDS }, - (_, index) => `tests (shard ${index + 1} of ${SHARDS})`, - ), + checks: [ + ...Array.from( + { length: SHARDS }, + (_, index) => `tests (shard ${index + 1} of ${SHARDS})`, + ), + "tests", + ], reads: isCode, }; @@ -789,9 +795,9 @@ export function queueRunAt( /** * Decides main's run of CI for a push. A commit the merge queue merged is the very commit the queue's - * run tested, so when that run passed nothing is run again but the jobs that write a cache whose key - * this push changed. `pushed` is the files the push changed, or undefined when they could not be read, - * which runs every cache writer. Any other push (an admin's merge past the queue, a direct push) runs + * run tested, so when that run passed only startup coverage omitted by the queue and the jobs that + * write a cache whose key this push changed run. `pushed` is the files the push changed, or undefined + * when they could not be read, which runs every cache writer. Any other push (an admin's merge past the queue, a direct push) runs * everything, as before. */ export function decideMainPush( @@ -799,6 +805,7 @@ export function decideMainPush( sha: string, repository: string, pushed: string[] | undefined, + queueJobs?: (run: CiRun) => ApiJob[], ): Decision & { queueRun?: CiRun } { const queueRun = queueRunAt(runs, sha, repository); if (!queueRun) { @@ -812,6 +819,30 @@ export function decideMainPush( const reasons = [ `Tested in the merge queue: ${queueRun.html_url}. Its checks are not run again on the same commit.`, ]; + // A queue that runs startup omits macOS. Only an explicitly skipped Windows job (or the whole + // matrix) proves it reused a baseline for both platforms. Missing/unreadable jobs owe startup too. + try { + const startup = queueJobs?.(queueRun) + .filter( + (job) => + job.name === "startup (windows-latest)" || + job.name === `startup (\${{ matrix.os }})`, + ) + .sort((a, b) => (b.run_attempt ?? 0) - (a.run_attempt ?? 0))[0]; + run.startup = startup?.conclusion !== "skipped"; + if (run.startup) { + reasons.push( + startup?.conclusion === "success" + ? "startup: runs, the merge queue tested Windows but omitted macOS." + : "startup: runs, the merge queue's skipped startup could not be proved.", + ); + } + } catch (error) { + run.startup = true; + reasons.push( + `startup: runs, the merge queue's jobs could not be read: ${String(error)}.`, + ); + } for (const writer of CACHE_WRITERS) { const changed = pushed?.filter(writer.key); if (changed && changed.length === 0) continue; @@ -1026,7 +1057,21 @@ type ApiRun = { run_attempt: number; head_repository?: { full_name?: string } | null; }; -type ApiJob = { name: string; conclusion: string | null }; +type ApiJob = { name: string; conclusion: string | null; run_attempt?: number }; + +/** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ +function jobsOf(repository: string, run: CiRun): ApiJob[] { + const pages = JSON.parse( + exec([ + "gh", + "api", + "--paginate", + "--slurp", + `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, + ]), + ) as { jobs: ApiJob[] }[]; + return pages.flatMap((page) => page.jobs); +} /** The run API's SHA proves CI's PR head only when checkout explicitly used it (Desktop). */ export function testedCheckout( @@ -1089,7 +1134,7 @@ function liveDeps( "--repo", repository, "--name", - `ci-tested-tree-${run.id}-${run.run_attempt}`, + `ci-tested-tree-${run.id}`, "--dir", directory, ], @@ -1318,13 +1363,21 @@ function pushedFiles( ): string[] | undefined { if (!before || /^0+$/.test(before)) return undefined; try { - const files = ( - JSON.parse( - exec(["gh", "api", `repos/${repository}/compare/${before}...${sha}`]), - ).files ?? [] - ).map((file: { filename: string }) => file.filename) as string[]; + const files = (JSON.parse( + exec(["gh", "api", `repos/${repository}/compare/${before}...${sha}`]), + ).files ?? []) as { filename: string; previous_filename?: string }[]; // The compare API lists at most 300 files. - return files.length < 300 ? files : undefined; + if (files.length >= 300) return undefined; + // A rename removes its old path too. A source file moved into docs must not look docs-only. + return [ + ...new Set( + files.flatMap((file) => + file.previous_filename + ? [file.filename, file.previous_filename] + : [file.filename], + ), + ), + ]; } catch { return undefined; } @@ -1386,6 +1439,7 @@ if (import.meta.main) { sha, repository, pushedFiles(repository, event.before, sha), + (run) => jobsOf(repository, run), ); } else if (eventName === "merge_group" && event.merge_group) { decision = decideMergeGroup( diff --git a/scripts/ci-run-tests.test.ts b/scripts/ci-run-tests.test.ts new file mode 100644 index 0000000000..aac9487dc1 --- /dev/null +++ b/scripts/ci-run-tests.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, test } from "bun:test"; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { data, Evaluator, Lexer, Parser } from "@actions/expressions"; + +const ROOT = join(import.meta.dir, ".."); +const SETUP_TEST = "desktop/src/setupLayout.browser.test.ts"; + +function runDesktopTests(files: string[], failWebKit = false) { + const directory = mkdtempSync(join(tmpdir(), "openbot-ci-run-tests-")); + try { + mkdirSync(join(directory, "desktop/src"), { recursive: true }); + for (const file of files) writeFileSync(join(directory, file), ""); + const log = join(directory, "calls.jsonl"); + const bun = join(directory, "bun"); + writeFileSync( + bun, + `#!${process.execPath} +import { appendFileSync } from "node:fs"; +appendFileSync(process.env.TEST_CALLS, JSON.stringify({ + args: process.argv.slice(2), cwd: process.cwd(), + browser: process.env.OPENBOT_APP_BROWSER, + engine: process.env.OPENBOT_APP_ENGINE ?? "chromium", +}) + "\\n"); +console.error("Ran 1 test across 1 file."); +if (process.env.FAIL_WEBKIT === "1" && process.env.OPENBOT_APP_ENGINE === "webkit") process.exit(1); +`, + ); + chmodSync(bun, 0o755); + const result = Bun.spawnSync( + [process.execPath, join(ROOT, "scripts/ci-run-tests.ts")], + { + cwd: directory, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH}`, + TEST_CALLS: log, + FAIL_WEBKIT: failWebKit ? "1" : "0", + TESTS: "[]", + BROWSER_TESTS: "[]", + WEBKIT_TESTS: "[]", + DESKTOP_BROWSER_TESTS: JSON.stringify(files), + OPENBOT_APP_ENGINE: "", + }, + }, + ); + const calls = readFileSync(log, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)) as { + args: string[]; + cwd: string; + browser: string; + engine: string; + }[]; + return { + status: result.exitCode, + calls, + cwd: realpathSync(join(directory, "desktop")), + }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +describe("changed desktop browser tests", () => { + test("setup-window test-only edits retain the full job's WebKit scenario", () => { + const result = runDesktopTests([ + SETUP_TEST, + "desktop/src/other.browser.test.ts", + ]); + expect(result.status).toBe(0); + expect(result.calls).toEqual([ + { + args: [ + "test", + "./src/setupLayout.browser.test.ts", + "./src/other.browser.test.ts", + ], + cwd: result.cwd, + browser: "1", + engine: "", + }, + { + args: [ + "test", + "-t", + "the key field and the tab row", + "./src/setupLayout.browser.test.ts", + ], + cwd: result.cwd, + browser: "1", + engine: "webkit", + }, + ]); + }); + + test("a failed WebKit setup-window scenario fails the changed-tests job", () => { + expect(runDesktopTests([SETUP_TEST], true).status).toBe(1); + }); + + test("other desktop browser tests do not add a WebKit run", () => { + const result = runDesktopTests(["desktop/src/other.browser.test.ts"]); + expect(result.status).toBe(0); + expect(result.calls).toHaveLength(1); + }); + + test("the changed-tests job installs WebKit for the setup-window scenario", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { jobs: Record }; + const condition = workflow.jobs["changed-tests"].steps.find( + (step) => step.name === "Install WebKit", + )?.if; + expect(condition).toBeDefined(); + const tree = new Parser( + new Lexer(condition ?? "").lex().tokens, + ["needs"], + [], + ).parse(); + const needed = (desktop: string[], webkit: string[] = []) => { + const context = JSON.parse( + JSON.stringify({ + needs: { + changes: { + outputs: { + desktop_browser_tests: JSON.stringify(desktop), + webkit_tests: JSON.stringify(webkit), + }, + }, + }, + }), + data.reviver, + ) as data.Dictionary; + return new Evaluator(tree, context).evaluate(); + }; + expect(needed([SETUP_TEST])).toEqual(new data.BooleanData(true)); + expect(needed(["desktop/src/other.browser.test.ts"])).toEqual( + new data.BooleanData(false), + ); + expect(needed([], ["app/tests/browser.test.tsx"])).toEqual( + new data.BooleanData(true), + ); + }); +}); diff --git a/scripts/ci-run-tests.ts b/scripts/ci-run-tests.ts index 3712b782a2..ed15643fd0 100644 --- a/scripts/ci-run-tests.ts +++ b/scripts/ci-run-tests.ts @@ -103,6 +103,15 @@ if (import.meta.main) { desktop.map((path) => `./${path.slice("desktop/".length)}`), { cwd: "desktop", env: browserEnv }, ), + // Match the desktop browser job's WebKit coverage for test-only edits too. + await runGroup( + "Changed desktop setup-window test, in WebKit", + ["bun", "test", "-t", "the key field and the tab row"], + desktop + .filter((path) => path === "desktop/src/setupLayout.browser.test.ts") + .map((path) => `./${path.slice("desktop/".length)}`), + { cwd: "desktop", env: { ...browserEnv, OPENBOT_APP_ENGINE: "webkit" } }, + ), ]; if (results.some((passed) => !passed)) process.exitCode = 1; } From 2c1127e3e18f93ef3bd77b0d302cddef90a963cc Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:27:56 -0800 Subject: [PATCH 03/21] CI: keep browser obligations and complete reuse evidence --- .github/workflows/ci.yml | 8 +- scripts/ci-changes.test.ts | 247 +++++++++++++++++++++++++++++++++++-- scripts/ci-changes.ts | 107 +++++++++++----- 3 files changed, 320 insertions(+), 42 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 167a833fc8..bebb5d1779 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,8 @@ 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`, any job whose cache key the push changed, and startup when the queue @@ -155,6 +156,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 diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index ac33818e4b..b9db408ca3 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -185,7 +185,7 @@ if (args[0] === "run" && args[1] === "download") { const endpoint = args.find((arg) => arg.startsWith("repos/")); if (!(endpoint in fixture.responses)) process.exit(1); const response = fixture.responses[endpoint]; - console.log(JSON.stringify(args.includes("--slurp") && !Array.isArray(response) ? [response] : response)); + console.log(JSON.stringify(args.includes("--slurp") ? (Array.isArray(response) ? response : [response]) : (Array.isArray(response) ? response[0] : response))); } `, ); @@ -369,6 +369,140 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("an outstanding WebKit test survives a docs-only push after Chromium passed", () => { + const file = "app/tests/composer-dictation-language.test.tsx"; + for (const recovered of [false, true]) { + const base = deps({ + passed: { + c2: recovered + ? ALL_CI + : ALL_CI.filter((name) => name !== "app (real browser, WebKit)"), + c1: ALL_CI, + }, + changes: { + c2: ["README.md"], + c1: ["server/src/main.ts", file, "README.md"], + }, + files: { + [file]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + }, + }); + const result = decide("ci", PR, { + ...base, + // The whole PR still includes the older edit; current passing baselines must supersede it. + diff: (from, to) => + from === PR.base + ? [{ path: file, deleted: false }] + : base.diff(from, to), + }); + expect(result.run.app_browser).toBe(false); + expect(result.run.app_browser_webkit).toBe(false); + expect(result.browserTests).toEqual(recovered ? [] : [file]); + expect(result.webkitTests).toEqual(recovered ? [] : [file]); + } + }); + + test("an edited unlisted browser file runs even when no reusable baseline exists", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + const base = deps({ passed: {}, changes: {} }); + const result = decide( + "ci", + { ...PR, checkout: "merge" }, + { + ...base, + diff: (from, to) => { + expect(from).toBe(PR.base); + expect(to).toBe("merge"); + return [{ path: file, deleted: false }]; + }, + read: () => "process.env.OPENBOT_APP_BROWSER", + }, + ); + expect(result.run.app_browser).toBe(true); + expect(result.browserTests).toEqual([file]); + expect(result.webkitTests).toEqual([file]); + }); + + test("cross-browser candidates importing their engines still run in WebKit", () => { + const file = "app/tests/with-shared-engines.test.tsx"; + const result = decide( + "ci", + PR, + deps({ + passed: { + c2: ALL_CI.filter((name) => name !== "app (real browser, WebKit)"), + c1: ALL_CI, + }, + changes: { c2: ["README.md"], c1: [file, "README.md"] }, + files: { + [file]: + 'import { engines } from "./browser-support"; process.env.OPENBOT_APP_BROWSER;', + }, + }), + ); + expect(result.browserTests).toEqual([file]); + expect(result.webkitTests).toEqual([file]); + }); + + test("mixed code and test edits run browser files outside the full jobs' fixed lists", () => { + for (const source of [false, true]) { + const app = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/another.browser.test.ts"; + const result = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { + c2: [...(source ? ["server/src/main.ts"] : []), app, desktop], + }, + files: { [app]: "process.env.OPENBOT_APP_BROWSER" }, + }), + ); + expect(result.run.app_browser).toBe(source); + expect(result.run.suite).toBe(source); + expect(result.browserTests).toEqual([app]); + expect(result.desktopBrowserTests).toEqual([desktop]); + } + }); + + test("code-only full browser runs do not repeat the same browser files in the partial job", () => { + const source = "app/src/main.tsx"; + const file = "app/tests/existing-layout.test.tsx"; + const result = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: [source] }, + mentions: { [source]: [file] }, + files: { + [file]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + }, + }), + ); + expect(result.run.app_browser).toBe(true); + expect(result.run.app_browser_webkit).toBe(true); + expect(result.run.partial).toBe(false); + }); + + test("removing a Bun test reruns the suite to validate its aggregate floor", () => { + // Change records expose paths/deletions, not how many cases remain inside a retained test file. + const file = "tests/removed.test.ts"; + const result = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: [file] }, + deleted: [file], + }), + ); + expect(result.run.suite).toBe(true); + expect(result.tests).toEqual([]); + }); test("compares the current PR's tested synthetic merge rather than its head", () => { const base = deps({ passed: { c2: ALL_CI }, changes: {} }); const decision = decide( @@ -534,6 +668,12 @@ describe("a pull request push", () => { ); expect(decision.run.app_browser).toBe(true); expect(decision.run.app_browser_webkit).toBe(true); + expect(decision.browserTests).toContain( + "app/tests/composer-dictation-language.test.tsx", + ); + expect(decision.webkitTests).toContain( + "app/tests/composer-dictation-language.test.tsx", + ); }); test("a change to a package the app imports runs the app's list in WebKit", () => { @@ -662,7 +802,7 @@ describe("a pull request push", () => { expect(decision.tests).toEqual([]); }); - test("a changed browser test runs in a browser, with WebKit when it asks for it", () => { + test("changed browser files retain browser coverage from both browser baselines", () => { const decision = decide( "ci", PR, @@ -691,13 +831,14 @@ describe("a pull request push", () => { ]); expect(decision.webkitTests).toEqual([ "app/tests/composer-dictation-language.test.tsx", + "app/tests/maths-rendering.test.tsx", ]); expect(decision.desktopBrowserTests).toEqual([ "desktop/src/setupLayout.browser.test.ts", ]); }); - test("a deleted test is not run, a test that names it is", () => { + test("a deleted test is not selected; the full suite runs tests that name it", () => { const decision = decide( "ci", PR, @@ -708,7 +849,8 @@ describe("a pull request push", () => { mentions: { "tests/old.test.ts": ["scripts/test-floor.test.ts"] }, }), ); - expect(decision.tests).toEqual(["scripts/test-floor.test.ts"]); + expect(decision.run.suite).toBe(true); + expect(decision.tests).toEqual([]); }); test("a change to CI itself runs every job", () => { @@ -1066,6 +1208,23 @@ describe("a merge group", () => { ?.checks as string[]; const GROUP: MergeGroup = { head: "g", pr: { labels: [], head: "h" } }; + test("a merge group without passing baselines retains changed browser files from its event base", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + const base = groupDeps({ passed: {}, changes: { "event-base": [file] } }); + const result = decideMergeGroup( + "ci", + [file], + { + ...base, + read: () => "process.env.OPENBOT_APP_BROWSER", + }, + { ...GROUP, base: "event-base" }, + ); + expect(result.run.app_browser).toBe(true); + expect(result.browserTests).toEqual([file]); + expect(result.webkitTests).toEqual([file]); + }); + test("compares a PR's passing jobs with its tested merge tree, never its untested head", () => { // h needs a fix on main. CI passed on merge m with that fix. Main later reverted it: // g equals h, but differs from the actual passing merge m, so its checks are owed. @@ -1201,7 +1360,7 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { - test("a successful partial rerun reuses the original run-scoped checkout proof", () => { + test("passing checks on later job pages remain reusable after partial reruns", () => { const result = actionsDecision({ event: "pull_request", proof: true, @@ -1213,17 +1372,52 @@ describe("the checkout a passing run proves", () => { id: 1, path: ".github/workflows/ci.yml", event: "pull_request", - run_attempt: 2, + run_attempt: 3, head_repository: { full_name: "CopilotKit/OpenBot" }, }, ], }, "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + [ + { + jobs: Array.from({ length: 100 }, () => ({ + name: "app (real browser)", + conclusion: "failure", + })), + }, + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + ], }), }); expect(result.suite).toBe("false"); - expect(result.static).toBe("false"); + expect(result.app_browser).toBe("false"); + expect(result.app_browser_webkit).toBe("false"); + }); + test("first attempts and successful partial reruns reuse the run-scoped checkout proof", () => { + for (const attempt of [1, 2]) { + const result = actionsDecision({ + event: "pull_request", + proof: true, + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + path: ".github/workflows/ci.yml", + event: "pull_request", + run_attempt: attempt, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + }), + }); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + } }); test("missing or malformed artifacts cannot stand in for a tested checkout", () => { @@ -1585,6 +1779,43 @@ describe("a release PR", () => { describe("the Desktop workflow", () => { const ALL_DESKTOP = DESKTOP_RULES.flatMap((rule) => rule.checks); + test("a Desktop test-only edit gets a frozen install and Desktop types in static CI", () => { + for (const source of [false, true]) { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { + c2: [ + "desktop/src/App.test.tsx", + ...(source ? ["server/src/main.ts"] : []), + ], + }, + }), + ); + expect(decision.run.static).toBe(true); + } + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: { + static: { steps: { run?: string; "working-directory"?: string }[] }; + }; + }; + const steps = workflow.jobs.static.steps; + const check = steps.findIndex( + (step) => + step["working-directory"] === "desktop" && + step.run === "bun run typecheck", + ); + expect(check).toBeGreaterThanOrEqual(0); + expect(steps.slice(0, check)).toContainEqual({ + run: "bun install --frozen-lockfile", + "working-directory": "desktop", + }); + }); + test("a release commit on main builds nothing; any other push, or one it cannot read, builds everything", () => { // v1.2.7's release commit (843b8029f): CHANGELOG.md, and package.json, backend-images.env and // Cargo's two files each by their version alone, which releaseFileViolations reads as no violation. diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 0963125531..c6b1597d1e 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -11,7 +11,7 @@ * * Three shapes of change come out small: * - * - Test files only. The suite's shards are skipped and the changed test files run on their own, + * - Test files only, with none removed. The suite's shards are skipped and changed files run on their own, * with any test that names one of them, in `tests (changed files)`; `format, lint, types` still * runs, since it formats, lints and type checks the tests. A test file that drives a real browser * runs in one there. @@ -497,6 +497,7 @@ export function decide( pr.checkout ?? pr.head, [deps.ancestors(pr.head)], deps, + () => deps.diff(pr.base, pr.checkout ?? pr.head), ); } @@ -512,6 +513,7 @@ function decideFrom( head: string, histories: string[][], deps: Deps, + currentChanges?: () => Change[], ): Decision { const rules = rulesOf(workflow); const passedAt = new Map>(); @@ -629,7 +631,13 @@ function decideFrom( ); } } - decideSuite(decision, changesFor(SUITE_RULE), changesFor, deps); + decideSuite( + decision, + changesFor(SUITE_RULE), + changesFor, + deps, + currentChanges, + ); } return decision; } @@ -640,11 +648,19 @@ function decideSuite( suiteChanges: Change[] | undefined, changesFor: (rule: Rule) => Change[] | undefined, deps: Deps, + currentChanges?: () => Change[], ) { const { run, reasons } = decision; const code = suiteChanges?.filter((change) => isCode(change.path)); - run.suite = !suiteChanges || (code?.length ?? 0) > 0; - if (suiteChanges && code && code.length > 0) { + const removed = suiteChanges?.filter( + (change) => change.deleted && isBunTest(change.path), + ); + run.suite = !suiteChanges || (code?.length ?? 0) + (removed?.length ?? 0) > 0; + if (suiteChanges && removed && removed.length > 0) { + reasons.push( + `suite: runs, ${describe(removed)} removed; the aggregate test floor must be checked again.`, + ); + } else if (suiteChanges && code && code.length > 0) { reasons.push(`suite: runs, ${describe(code)} changed.`); } else if (suiteChanges) { reasons.push( @@ -652,13 +668,23 @@ function decideSuite( ); } - // The test files to run on their own: the ones changed since the suite last passed, and every test - // that names a changed file. Those the full suite or the browser job runs anyway are left out. + // Non-browser tests can reuse the suite. Browser jobs run fixed file lists, so changed browser + // files remain candidates even when those jobs run. Each browser rule has its own passing tree. const candidates = new Set(); - const add = (changes: Change[] | undefined, browser: boolean) => { + const webkit = new Set(); + const add = ( + changes: Change[] | undefined, + browser: boolean, + fullJob = false, + forceWebKit = false, + ) => { if (!changes) return; const named = changes - .filter((change) => !manualOnly(change.path)) + .filter( + (change) => + !manualOnly(change.path) && + (!fullJob || isTestFile(change.path) || isDocs(change.path)), + ) .map((change) => change.path); const files = [ ...changes @@ -667,18 +693,27 @@ function decideSuite( ...deps.mentions(named), ]; for (const file of files) { - if (isBunTest(file) && isBrowserTest(file, deps) === browser) + if (isBunTest(file) && isBrowserTest(file, deps) === browser) { candidates.add(file); + if (forceWebKit && !file.startsWith("desktop/")) webkit.add(file); + } } }; if (!run.suite) add(suiteChanges, false); - if (!run.app_browser) { - add( - changesFor( - CI_RULES.find((rule) => rule.output === "app_browser") as Rule, - ), - true, + let current: Change[] | undefined; + for (const output of ["app_browser", "app_browser_webkit"]) { + // Without a historical pass, full jobs still cannot cover edited files outside their lists. + // Only then fall back to this PR/group's diff; an old PR edit may already have passed later. + let changes = changesFor( + CI_RULES.find((rule) => rule.output === output) as Rule, ); + if (!changes) { + current ??= currentChanges?.().filter( + (change) => !isIgnored(change.path), + ); + changes = current; + } + add(changes, true, run[output], output === "app_browser_webkit"); } for (const file of [...candidates].sort()) { @@ -688,7 +723,10 @@ function decideSuite( decision.desktopBrowserTests.push(file); } else { decision.browserTests.push(file); - if (deps.read(file)?.includes("OPENBOT_APP_ENGINES")) { + if ( + webkit.has(file) || + deps.read(file)?.includes("OPENBOT_APP_ENGINES") + ) { decision.webkitTests.push(file); } } @@ -902,6 +940,8 @@ export function decideDesktopMainPush( export type MergeGroup = { /** The group's commit: main, or the groups queued ahead, with this pull request on top. */ head: string; + /** The event's base commit, before the queued changes. */ + base?: string; /** The queued pull request, or undefined when it could not be read. */ pr?: { labels: string[]; @@ -1015,15 +1055,21 @@ export function decideMergeGroup( } const histories = [ancestors(group.head)]; if (group.pr?.head) histories.push(ancestors(group.pr.head)); - const decision = decideFrom(workflow, group.head, histories, { - ancestors, - passed, - testedTrees: deps.testedTrees, - diff, - releaseViolations, - mentions: deps.mentions, - read: deps.read, - }); + const decision = decideFrom( + workflow, + group.head, + histories, + { + ancestors, + passed, + testedTrees: deps.testedTrees, + diff, + releaseViolations, + mentions: deps.mentions, + read: deps.read, + }, + () => diff(group.base ?? histories[0]?.[1] ?? group.head, group.head), + ); decision.reasons.unshift( group.pr?.head ? "A merge group: each job runs unless nothing it reads changed since it passed on main or on the pull request." @@ -1060,7 +1106,7 @@ type ApiRun = { type ApiJob = { name: string; conclusion: string | null; run_attempt?: number }; /** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ -function jobsOf(repository: string, run: CiRun): ApiJob[] { +function jobsOf(repository: string, run: Pick): ApiJob[] { const pages = JSON.parse( exec([ "gh", @@ -1175,13 +1221,7 @@ function liveDeps( } if (!tree) continue; const names = trees.get(tree) ?? new Set(); - const jobs = JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, - ]), - ).jobs as ApiJob[]; + const jobs = jobsOf(repository, run); for (const job of jobs) if (job.conclusion === "success") names.add(job.name); trees.set(tree, names); @@ -1455,6 +1495,7 @@ if (import.meta.main) { ]), { head: event.merge_group.head_sha, + base: event.merge_group.base_sha, pr: queuedPull(repository, event.merge_group.head_ref), }, ); From 3989214d37017e5ef53b1bf667516a127968ac98 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:40:38 -0800 Subject: [PATCH 04/21] CI: retain partial browser failures through full-check transitions --- .github/workflows/ci.yml | 6 +- scripts/ci-changes.test.ts | 264 +++++++++++++++++++++++++-- scripts/ci-changes.ts | 131 +++++++++++-- scripts/workflow-concurrency.test.ts | 20 +- 4 files changed, 375 insertions(+), 46 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bebb5d1779..e88581ca0c 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 the commit the release # PR merged onto (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 before it, and that commit never got a @@ -34,7 +36,7 @@ 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 +# A pull request's newer push or label starts a replacement run. 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: diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index b9db408ca3..82a8b1532d 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import { chmodSync, existsSync, + mkdirSync, mkdtempSync, readFileSync, readdirSync, @@ -9,7 +10,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { CACHE_WRITERS, type Change, @@ -40,6 +41,10 @@ const ROOT = join(import.meta.dir, ".."); /** Every check a full CI run passes, by the job names the Actions API reports. */ const ALL_CI = [...CI_RULES, SUITE_RULE].flatMap((rule) => rule.checks); +const API_BASELINE_JOBS = [ + ...ALL_CI.map((name) => ({ name, conclusion: "success" })), + { name: "tests (changed files)", conclusion: "skipped" }, +]; /** The tests that name CHANGELOG.md, as `git grep -l CHANGELOG.md -- '*.test.ts'` finds them. */ const NAME_CHANGELOG = [ @@ -137,8 +142,12 @@ const REAL = { mentions: realMentions, read: readTracked }; /** Runs the real Actions entry point with a local repository and recorded GitHub responses. */ function actionsDecision(options: { event: "pull_request" | "merge_group" | "push"; - responses: (sha: string) => Record; + responses: (sha: string, commits: string[]) => Record; proof?: boolean | string; + proofs?: (commits: string[]) => Record; + commits?: Record[]; + base?: string; + expectFailure?: boolean; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -159,14 +168,34 @@ function actionsDecision(options: { "-m", "test", ); - const sha = git("rev-parse", "HEAD"); + const commits = [git("rev-parse", "HEAD")]; + for (const files of options.commits ?? []) { + for (const [file, content] of Object.entries(files)) { + mkdirSync(dirname(join(directory, file)), { recursive: true }); + writeFileSync(join(directory, file), content); + } + git("add", "--all"); + git( + "-c", + "user.name=CI", + "-c", + "user.email=ci@example.test", + "commit", + "--quiet", + "-m", + "next", + ); + commits.push(git("rev-parse", "HEAD")); + } + const sha = commits.at(-1) as string; const repository = "CopilotKit/OpenBot"; const fixture = join(directory, "fixture.json"); writeFileSync( fixture, JSON.stringify({ - responses: options.responses(sha), + responses: options.responses(sha, commits), proof: options.proof, + proofs: options.proofs?.(commits), sha, }), ); @@ -179,8 +208,10 @@ import { join } from "node:path"; const fixture = JSON.parse(readFileSync(process.env.CI_FIXTURE, "utf8")); const args = process.argv.slice(2); if (args[0] === "run" && args[1] === "download") { - if (!fixture.proof || args[args.indexOf("--name") + 1] !== "ci-tested-tree-1") process.exit(1); - writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), typeof fixture.proof === "string" ? fixture.proof : fixture.sha); + const name = args[args.indexOf("--name") + 1]; + const proof = fixture.proofs?.[name] ?? (fixture.proof && name === "ci-tested-tree-1" ? (typeof fixture.proof === "string" ? fixture.proof : fixture.sha) : undefined); + if (!proof) process.exit(1); + writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), proof); } else { const endpoint = args.find((arg) => arg.startsWith("repos/")); if (!(endpoint in fixture.responses)) process.exit(1); @@ -198,10 +229,10 @@ if (args[0] === "run" && args[1] === "download") { pull_request: { labels: [], head: { ref: "fix", sha, repo: { full_name: repository } }, - base: { sha }, + base: { sha: options.base ?? commits[0] }, }, merge_group: { - base_sha: "b".repeat(40), + base_sha: options.commits?.length ? commits[0] : "b".repeat(40), head_sha: sha, head_ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha}`, }, @@ -229,6 +260,11 @@ if (args[0] === "run" && args[1] === "download") { }, }, ); + if (options.expectFailure) { + expect(result.exitCode).not.toBe(0); + expect(existsSync(output)).toBe(false); + return {}; + } expect(result.exitCode).toBe(0); return Object.fromEntries( [ @@ -974,6 +1010,54 @@ describe("manual Workbench changes", () => { }); describe("everything runs", () => { + test("full-ci retains changed app and Desktop browser files without history lookups", () => { + const app = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/unlisted.browser.test.ts"; + for (const event of ["pull_request", "merge_group"]) { + const base = deps({ + passed: {}, + changes: {}, + files: { [app]: "process.env.OPENBOT_APP_BROWSER" }, + }); + const noHistory = { + ...base, + ancestors: () => { + throw new Error("full-ci must not read history"); + }, + passed: () => { + throw new Error("full-ci must not read history"); + }, + diff: (from: string, to: string) => { + expect(from).toBe("base"); + expect(to).toBe("checkout"); + return [app, desktop].map((path) => ({ path, deleted: false })); + }, + }; + const result = + event === "pull_request" + ? decide( + "ci", + { + ...PR, + base: "base", + checkout: "checkout", + labels: ["full-ci"], + }, + noHistory, + ) + : decideMergeGroup("ci", [app, desktop], noHistory, { + head: "checkout", + base: "base", + pr: { labels: ["full-ci"] }, + }); + expect(result.browserTests).toEqual([app]); + expect(result.webkitTests).toEqual([app]); + expect(result.desktopBrowserTests).toEqual([desktop]); + expect(result.run.partial).toBe(true); + for (const rule of [...CI_RULES, SUITE_RULE]) + expect(result.run[rule.output]).toBe(true); + } + }); test("on any event but a pull request: main, the release's call, a schedule", () => { const decision = decide("ci", undefined, deps({ passed: {}, changes: {} })); expect(running(decision)).toEqual( @@ -1038,8 +1122,9 @@ describe("a merge group", () => { test("a source file renamed to a document cannot use the docs-only shortcut", () => { const result = actionsDecision({ event: "merge_group", - responses: (sha) => ({ - [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + commits: [{ "README.md": "renamed source body" }], + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { files: [ { filename: "README.md", @@ -1124,7 +1209,10 @@ describe("a merge group", () => { "scripts/release-note-check.fixtures/pr-2654.md", ]) { const decision = decideMergeGroup("ci", [path], REAL); - expect({ path, run: running(decision) }).toEqual({ + expect({ + path, + run: running(decision).filter((job) => job !== "partial"), + }).toEqual({ path, run: everyJob, }); @@ -1139,15 +1227,18 @@ describe("a merge group", () => { ["README.md", "app/src/lib/marks.ts"], ]) { const decision = decideMergeGroup("ci", files, REAL); - expect(running(decision)).toEqual(everyJob); + expect(running(decision).filter((job) => job !== "partial")).toEqual( + everyJob, + ); expect(decision.ignoredOnly).toBe(false); } }); - test("whose files could not be read, or are none, runs everything", () => { - for (const files of [undefined, []]) { - expect(running(decideMergeGroup("ci", files, REAL))).toEqual(everyJob); - } + test("an empty group runs everything; unreadable changed paths cannot claim browser coverage", () => { + expect(running(decideMergeGroup("ci", [], REAL))).toEqual(everyJob); + expect(() => decideMergeGroup("ci", undefined, REAL)).toThrow( + "changed browser files", + ); }); test("ci.yml: the image builds follow the group's `components` decision, and always run on main", () => { @@ -1248,7 +1339,9 @@ describe("a merge group", () => { head: "g", pr: { labels: ["full-ci"] }, }); - expect(running(result)).toEqual(everyJob); + expect(running(result).filter((job) => job !== "partial")).toEqual( + everyJob, + ); }); /** The pull request changed the app; main changed a harness since the pull request branched. */ const APP_PR_HARNESS_MAIN = { @@ -1360,6 +1453,121 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("a docs push retains failed partial browser work until the latest partial attempt passes", () => { + const app = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/unlisted.browser.test.ts"; + for (const state of [ + "failure", + "cancelled", + "missing", + "unreadable", + "success", + "skipped", + "retry", + ]) { + const recovered = ["success", "skipped", "retry"].includes(state); + const result = actionsDecision({ + event: "pull_request", + commits: [ + { + "app/src/main.tsx": "changed source", + [app]: "process.env.OPENBOT_APP_BROWSER", + [desktop]: "", + }, + { "README.md": "docs-only followup" }, + ], + proofs: (commits) => ({ "ci-tested-tree-3": commits[1] }), + responses: (sha, commits) => { + const run = (id: number, event: string) => ({ + id, + event, + path: ".github/workflows/ci.yml", + run_attempt: state === "retry" ? 2 : 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }); + const partial = + state === "missing" + ? [] + : [ + ...(state === "retry" + ? [ + { + name: "tests (changed files)", + conclusion: "failure", + run_attempt: 1, + }, + ] + : []), + { + name: "tests (changed files)", + conclusion: + state === "unreadable" + ? null + : state === "retry" + ? "success" + : state, + run_attempt: state === "retry" ? 2 : 1, + }, + ]; + const full = ALL_CI.map((name) => ({ name, conclusion: "success" })); + return { + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { workflow_runs: [] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[1]}&per_page=100`]: + { workflow_runs: [run(3, "pull_request")] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[0]}&per_page=100`]: + { workflow_runs: [run(1, "push")] }, + "repos/CopilotKit/OpenBot/actions/runs/3/jobs?filter=all&per_page=100": + { jobs: [...full, ...partial] }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { + jobs: [ + ...full, + { name: "tests (changed files)", conclusion: "skipped" }, + ], + }, + }; + }, + }); + expect(JSON.parse(result.browser_tests)).toEqual(recovered ? [] : [app]); + expect(JSON.parse(result.desktop_browser_tests)).toEqual( + recovered ? [] : [desktop], + ); + expect(result.partial).toBe(String(!recovered)); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + expect(result.build).toBe("false"); + } + }, 15_000); + + test("historical API failure still runs changed browser files from the local PR diff", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + for (const event of ["pull_request", "merge_group"] as const) { + const result = actionsDecision({ + event, + commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + responses: () => ({}), + }); + expect(result.suite).toBe("true"); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + expect(result.partial).toBe("true"); + } + }); + + test("unreadable historical evidence and local changes fail the changes job", () => { + actionsDecision({ + event: "pull_request", + commits: [ + { + "app/tests/access-requests-layout.test.tsx": + "process.env.OPENBOT_APP_BROWSER", + }, + ], + base: "b".repeat(40), + expectFailure: true, + responses: () => ({}), + }); + }); test("passing checks on later job pages remain reusable after partial reruns", () => { const result = actionsDecision({ event: "pull_request", @@ -1385,7 +1593,7 @@ describe("the checkout a passing run proves", () => { conclusion: "failure", })), }, - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + { jobs: API_BASELINE_JOBS }, ], }), }); @@ -1412,7 +1620,7 @@ describe("the checkout a passing run proves", () => { ], }, "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + { jobs: API_BASELINE_JOBS }, }), }); expect(result.suite).toBe("false"); @@ -1439,7 +1647,7 @@ describe("the checkout a passing run proves", () => { ], }, "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + { jobs: API_BASELINE_JOBS }, }), }); expect(result.suite).toBe("true"); @@ -1927,6 +2135,22 @@ function jobNames(workflow: string): string[] { } describe("the rules name the jobs the workflows run", () => { + test("adding a label triggers replacement CI with the normal changes and verify jobs", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + on: { pull_request: { types?: string[] } | null }; + jobs: Record; + }; + expect(workflow.on.pull_request?.types).toEqual([ + "opened", + "synchronize", + "reopened", + "labeled", + ]); + expect(workflow.jobs.changes.if).toBeUndefined(); + expect(workflow.jobs.verify.if).toBe("always()"); + }); test("the cross-browser list runs each engine in a separate job, retaining both required results", () => { const ci = Bun.YAML.parse( readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index c6b1597d1e..be2148d555 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -464,6 +464,20 @@ export function rulesOf(workflow: Workflow): Rule[] { return workflow === "ci" ? [...CI_RULES, SUITE_RULE] : DESKTOP_RULES; } +/** Full fixed-list jobs still need the browser files changed outside those lists. No history read. */ +function fullDecision( + workflow: Workflow, + why: string, + deps: Pick, + currentChanges: () => Change[], +): Decision { + const decision = everything(rulesOf(workflow), why); + if (workflow === "ci") { + decideSuite(decision, undefined, () => undefined, deps, currentChanges); + } + return decision; +} + /** * Decides every job of a workflow for one pull request push. `pr` undefined is any other event, * which runs everything. @@ -476,7 +490,12 @@ export function decide( const rules = rulesOf(workflow); if (!pr) return everything(rules, "Not a pull request: everything runs."); if (pr.labels.includes("full-ci")) { - return everything(rules, "Labelled full-ci: everything runs."); + return fullDecision( + workflow, + "Labelled full-ci: everything runs.", + deps, + () => deps.diff(pr.base, pr.checkout ?? pr.head), + ); } if (releaseShaped(pr)) { @@ -647,7 +666,7 @@ function decideSuite( decision: Decision, suiteChanges: Change[] | undefined, changesFor: (rule: Rule) => Change[] | undefined, - deps: Deps, + deps: Pick, currentChanges?: () => Change[], ) { const { run, reasons } = decision; @@ -978,15 +997,26 @@ export function decideMergeGroup( group?: MergeGroup, ): Decision & { ignoredOnly: boolean } { const rules = rulesOf(workflow); + const currentChanges = () => { + if (group?.base && deps.diff) return deps.diff(group.base, group.head); + if (changed) + return changed.map((path) => ({ + path, + deleted: deps.read(path) === undefined, + })); + throw new Error( + "Could not determine this merge group's changed browser files.", + ); + }; + const full = (why: string) => ({ + ...fullDecision(workflow, why, deps, currentChanges), + ignoredOnly: false, + }); // The explicit override applies even when every changed file is a document. if (group?.pr?.labels.includes("full-ci")) { - return { - ...everything( - rules, - "A merge group of a pull request labelled full-ci: everything runs.", - ), - ignoredOnly: false, - }; + return full( + "A merge group of a pull request labelled full-ci: everything runs.", + ); } // A file no job's rule reads: CHANGELOG.md, and the docs. A test that names a doc still runs. const unread = (path: string) => @@ -1030,10 +1060,6 @@ export function decideMergeGroup( } return decision; } - const full = (why: string) => ({ - ...everything(rulesOf(workflow), why), - ignoredOnly: false, - }); if (!changed) { return full( "A merge group whose files could not be read: everything runs.", @@ -1103,7 +1129,12 @@ type ApiRun = { run_attempt: number; head_repository?: { full_name?: string } | null; }; -type ApiJob = { name: string; conclusion: string | null; run_attempt?: number }; +type ApiJob = { + name: string; + conclusion: string | null; + run_attempt?: number; + id?: number; +}; /** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ function jobsOf(repository: string, run: Pick): ApiJob[] { @@ -1145,6 +1176,11 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); + const browserChecks = new Set( + CI_RULES.filter((rule) => + ["app_browser", "app_browser_webkit"].includes(rule.output), + ).flatMap((rule) => rule.checks), + ); const records = new Map>>(); const recordsAt = (sha: string): Map> => { const cached = records.get(sha); @@ -1222,8 +1258,25 @@ function liveDeps( if (!tree) continue; const names = trees.get(tree) ?? new Set(); const jobs = jobsOf(repository, run); + // A fixed browser list cannot discharge a failed unlisted-file obligation. Failed-only + // reruns retain older jobs, so only the latest partial result establishes that coverage. + const partial = jobs + .filter((job) => job.name === "tests (changed files)") + .sort( + (a, b) => + (b.run_attempt ?? 0) - (a.run_attempt ?? 0) || + (b.id ?? 0) - (a.id ?? 0), + )[0]; + const browserCovered = + workflow !== "ci" || + partial?.conclusion === "success" || + partial?.conclusion === "skipped"; for (const job of jobs) - if (job.conclusion === "success") names.add(job.name); + if ( + job.conclusion === "success" && + (browserCovered || !browserChecks.has(job.name)) + ) + names.add(job.name); trees.set(tree, names); } records.set(sha, trees); @@ -1439,6 +1492,7 @@ if (import.meta.main) { const repository = process.env.GITHUB_REPOSITORY ?? ""; const eventName = process.env.GITHUB_EVENT_NAME ?? ""; let decision: Decision & { queueRun?: CiRun; ignoredOnly?: boolean }; + let fallbackChanges: { base: string; head: string } | undefined; try { const event = ( process.env.GITHUB_EVENT_PATH @@ -1455,6 +1509,27 @@ if (import.meta.main) { checkout: workflow === "ci" ? process.env.GITHUB_SHA : undefined, base: pull.base.sha, }; + if (workflow === "ci" && pr) { + fallbackChanges = { base: pr.base, head: pr.checkout ?? pr.head }; + } else if ( + workflow === "ci" && + eventName === "merge_group" && + event.merge_group + ) { + fallbackChanges = { + base: event.merge_group.base_sha, + head: event.merge_group.head_sha, + }; + } + if ( + workflow === "ci" && + ["pull_request", "merge_group"].includes(eventName) && + (!fallbackChanges?.base || !fallbackChanges.head) + ) { + throw new Error( + "The event does not identify the base and checkout needed to check changed browser files.", + ); + } // main's own run of a push. Not the release's call of these checks, which sees the push that // published it as its event too: `github.workflow` there is the caller's, Publish release. const mainPush = @@ -1514,11 +1589,27 @@ if (import.meta.main) { ); } } catch (error) { - // Unable to decide is never a reason to skip: everything runs. - decision = everything( - rulesOf(workflow), - `Could not decide, so everything runs: ${error instanceof Error ? error.message : String(error)}`, - ); + const why = `Could not decide, so everything runs: ${error instanceof Error ? error.message : String(error)}`; + if ( + workflow === "ci" && + ["pull_request", "merge_group"].includes(eventName) + ) { + // Historical API evidence may fail while the event's local Git diff remains readable. + // If that diff fails too, fail changes rather than claim fixed lists cover unknown files. + if (!fallbackChanges) throw error; + const local = liveDeps( + workflow, + repository, + Number(process.env.GITHUB_RUN_ID ?? 0), + [repository], + ); + const { base, head } = fallbackChanges; + decision = fullDecision(workflow, why, local, () => + local.diff(base, head), + ); + } else { + decision = everything(rulesOf(workflow), why); + } } for (const [output, value] of Object.entries(decision.run)) { writeOutput(output, String(value)); diff --git a/scripts/workflow-concurrency.test.ts b/scripts/workflow-concurrency.test.ts index 839707f377..5ae8a243db 100644 --- a/scripts/workflow-concurrency.test.ts +++ b/scripts/workflow-concurrency.test.ts @@ -1,6 +1,6 @@ /** * A pull request's newer push cancels the run of the push before it, in every workflow a pull - * request starts, and nothing else is ever cancelled. + * request starts. A label can also start a complete replacement CI run. * * CI waits on the 16-core runners. A pull request pushed again while its run is in progress leaves * that run spending minutes on a commit nobody will merge, so each workflow's `concurrency` cancels @@ -31,7 +31,7 @@ type Workflow = { concurrency?: | string | { group?: string; "cancel-in-progress"?: boolean | string }; - jobs?: Record; + jobs?: Record; }; const files = readdirSync(directory) @@ -276,7 +276,7 @@ describe("main, a release branch, a tag, a schedule and a manual run are never c }); }); -describe("a pull request labelled while its run is in progress keeps that run", () => { +describe("a label preserves the active run or starts its complete CI replacement", () => { const labelled = pullRequestWorkflows.filter((file) => triggers(file).pull_request?.types?.includes("labeled"), ); @@ -285,7 +285,19 @@ describe("a pull request labelled while its run is in progress keeps that run", action: "labeled", label: "full-ci", }); - expect(concurrency(file, label)?.cancel).toBe(false); + if (file === "ci.yml") { + // CI runs its normal decision/check graph for every label, including the full-ci override. + // Replacing the active run is safe because the new run supplies every required obligation. + expect(triggers(file).pull_request?.types).toContain("labeled"); + expect(workflow(file).jobs?.changes?.if).toBeUndefined(); + expect(workflow(file).jobs?.verify?.if).toBe("always()"); + expect(concurrency(file, label)?.group).toBe( + concurrency(file, pullRequest(file, 101, "same-push"))?.group, + ); + expect(concurrency(file, label)?.cancel).toBe(true); + } else { + expect(concurrency(file, label)?.cancel).toBe(false); + } }); }); From 499ac14e0eb1d74258642945cd562b62688f1a51 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:52:30 -0800 Subject: [PATCH 05/21] CI: fail on dependency-search errors and isolate browser engines --- .../bots-panel-start-conversation.test.tsx | 17 ++-- app/tests/browser-engines.test.ts | 80 +++++++++++++++++++ app/tests/browser-engines.ts | 25 ++++++ app/tests/roster-working.test.tsx | 19 ++--- app/tests/section-strip-routines.test.tsx | 17 ++-- app/tests/sidebar-zoom-drag.test.tsx | 17 ++-- scripts/ci-changes.test.ts | 56 +++++++++++++ scripts/ci-changes.ts | 6 +- 8 files changed, 199 insertions(+), 38 deletions(-) create mode 100644 app/tests/browser-engines.test.ts create mode 100644 app/tests/browser-engines.ts diff --git a/app/tests/bots-panel-start-conversation.test.tsx b/app/tests/bots-panel-start-conversation.test.tsx index 1189a22937..9407f68361 100644 --- a/app/tests/bots-panel-start-conversation.test.tsx +++ b/app/tests/bots-panel-start-conversation.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, Locator, Page } from "playwright-core"; +import type { Browser, Locator, 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"; @@ -24,8 +25,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"; @@ -195,11 +196,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..a68423fef3 --- /dev/null +++ b/app/tests/browser-engines.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, test } from "bun:test"; +import { launchBrowserEngines } 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); + }); +}); diff --git a/app/tests/browser-engines.ts b/app/tests/browser-engines.ts new file mode 100644 index 0000000000..95cfa526b4 --- /dev/null +++ b/app/tests/browser-engines.ts @@ -0,0 +1,25 @@ +type BrowserFactory = { + launch(options?: { channel?: string }): Promise; +}; + +/** 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 { + const selected = new Set( + (selection?.trim() || "chromium").split(",").map((engine) => engine.trim()), + ); + for (const engine of selected) { + if (engine !== "chromium" && engine !== "webkit") { + throw new Error(`Unsupported browser engine: ${engine}`); + } + // 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/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/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/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 82a8b1532d..09dd0c8db2 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -148,6 +148,7 @@ function actionsDecision(options: { commits?: Record[]; base?: string; expectFailure?: boolean; + grepExit?: number; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -221,6 +222,26 @@ if (args[0] === "run" && args[1] === "download") { `, ); chmodSync(gh, 0o755); + if (options.grepExit !== undefined) { + const realGit = Bun.which("git"); + if (!realGit) throw new Error("git is not installed"); + const wrappedGit = join(directory, "git"); + writeFileSync( + wrappedGit, + `#!${process.execPath} +const args = process.argv.slice(2); +if (args[0] === "grep") { + if (${options.grepExit} !== 1) console.error("fatal: failed to read test file"); + process.exit(${options.grepExit}); +} +const result = Bun.spawnSync([${JSON.stringify(realGit)}, ...args]); +process.stdout.write(result.stdout); +process.stderr.write(result.stderr); +process.exit(result.exitCode); +`, + ); + chmodSync(wrappedGit, 0o755); + } const event = join(directory, "event.json"); writeFileSync( event, @@ -1119,6 +1140,41 @@ describe("CHANGELOG.md", () => { describe("a merge group", () => { const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); + test("dependency discovery accepts grep's no-match status but fails on unreadable tests", () => { + for (const grepExit of [undefined, 1, 128]) { + const result = actionsDecision({ + event: "merge_group", + commits: [ + { + "README.md": "changed docs", + "app/tests/unlisted.test.ts": + grepExit === 1 + ? "OPENBOT_APP_BROWSER" + : "README.md OPENBOT_APP_BROWSER", + }, + ], + grepExit, + expectFailure: grepExit === 128, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "README.md" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + }), + }); + if (grepExit !== 128) { + expect(result.suite).toBe("false"); + expect(result.partial).toBe(String(grepExit === undefined)); + expect(JSON.parse(result.browser_tests)).toEqual( + grepExit === undefined ? ["app/tests/unlisted.test.ts"] : [], + ); + } + } + }); + test("a source file renamed to a document cannot use the docs-only shortcut", () => { const result = actionsDecision({ event: "merge_group", diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index be2148d555..96d2e51ca2 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1114,9 +1114,9 @@ function describe(changes: Change[]): string { // --------------------------------------------------------------------------------------------- // Running it in Actions. -function exec(cmd: string[], allowFailure = false): string { +function exec(cmd: string[], allowedExitCode?: number): string { const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" }); - if (result.exitCode !== 0 && !allowFailure) { + if (result.exitCode !== 0 && result.exitCode !== allowedExitCode) { throw new Error(`${cmd.join(" ")}: ${result.stderr.toString().trim()}`); } return result.stdout.toString(); @@ -1333,7 +1333,7 @@ function liveDeps( "*.test.ts", "*.test.tsx", ], - true, + 1, ) .split("\0") .filter((file) => file && isBunTest(file)); From d8ff4b661bf17182abd25fc66fa10ef9687e537f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:53:56 -0800 Subject: [PATCH 06/21] CI: keep manual runs from erasing changed browser obligations --- scripts/ci-changes.test.ts | 33 +++++++++++++++++++++++++++++++++ scripts/ci-changes.ts | 6 ++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 09dd0c8db2..de12c5bfcf 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1509,6 +1509,39 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("manual and scheduled fixed-list runs cannot discharge a PR's unlisted browser edit", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + for (const event of ["workflow_dispatch", "schedule"]) { + const result = actionsDecision({ + event: "pull_request", + commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event, + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[0]}&per_page=100`]: + { workflow_runs: [] }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: API_BASELINE_JOBS }, + }), + }); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + expect(result.partial).toBe("true"); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + expect(result.build).toBe("false"); + } + }); + test("a docs push retains failed partial browser work until the latest partial attempt passes", () => { const app = "app/tests/access-requests-layout.test.tsx"; const desktop = "desktop/src/unlisted.browser.test.ts"; diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 96d2e51ca2..42ff62ad2f 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1269,8 +1269,10 @@ function liveDeps( )[0]; const browserCovered = workflow !== "ci" || - partial?.conclusion === "success" || - partial?.conclusion === "skipped"; + // Manual/scheduled runs do not discover a feature branch's changed browser files. + (["pull_request", "push", "merge_group"].includes(run.event) && + (partial?.conclusion === "success" || + partial?.conclusion === "skipped")); for (const job of jobs) if ( job.conclusion === "success" && From f5207aafed010ac0a696861bb64ddb244879f87f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:55:45 -0800 Subject: [PATCH 07/21] CI: limit push browser baselines to main --- scripts/ci-changes.test.ts | 15 +++++++++++---- scripts/ci-changes.ts | 6 ++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index de12c5bfcf..3b99c75476 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1509,9 +1509,14 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { - test("manual and scheduled fixed-list runs cannot discharge a PR's unlisted browser edit", () => { + test("only supported producer events can discharge a PR's unlisted browser edit", () => { const file = "app/tests/access-requests-layout.test.tsx"; - for (const event of ["workflow_dispatch", "schedule"]) { + for (const [event, head_branch, covered] of [ + ["workflow_dispatch", "feature", false], + ["schedule", "main", false], + ["push", "feature", false], + ["push", "main", true], + ] as const) { const result = actionsDecision({ event: "pull_request", commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], @@ -1522,6 +1527,7 @@ describe("the checkout a passing run proves", () => { { id: 1, event, + head_branch, path: ".github/workflows/ci.yml", run_attempt: 1, head_repository: { full_name: "CopilotKit/OpenBot" }, @@ -1534,8 +1540,8 @@ describe("the checkout a passing run proves", () => { { jobs: API_BASELINE_JOBS }, }), }); - expect(JSON.parse(result.browser_tests)).toEqual([file]); - expect(result.partial).toBe("true"); + expect(JSON.parse(result.browser_tests)).toEqual(covered ? [] : [file]); + expect(result.partial).toBe(String(!covered)); expect(result.suite).toBe("false"); expect(result.static).toBe("false"); expect(result.build).toBe("false"); @@ -1570,6 +1576,7 @@ describe("the checkout a passing run proves", () => { const run = (id: number, event: string) => ({ id, event, + head_branch: event === "push" ? "main" : "feature", path: ".github/workflows/ci.yml", run_attempt: state === "retry" ? 2 : 1, head_repository: { full_name: "CopilotKit/OpenBot" }, diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 42ff62ad2f..71d03c8d75 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1126,6 +1126,7 @@ type ApiRun = { id: number; path: string; event: string; + head_branch: string | null; run_attempt: number; head_repository?: { full_name?: string } | null; }; @@ -1269,8 +1270,9 @@ function liveDeps( )[0]; const browserCovered = workflow !== "ci" || - // Manual/scheduled runs do not discover a feature branch's changed browser files. - (["pull_request", "push", "merge_group"].includes(run.event) && + // Only supported producers discover PR changes or test the protected main branch. + ((["pull_request", "merge_group"].includes(run.event) || + (run.event === "push" && run.head_branch === "main")) && (partial?.conclusion === "success" || partial?.conclusion === "skipped")); for (const job of jobs) From 7ca893f12d6a3ea210f54e976c7363bc6f90a7fb Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:08:20 -0800 Subject: [PATCH 08/21] CI: keep current unlisted browser files owed across reused trees --- scripts/ci-changes.test.ts | 146 ++++++++++++++++++++++++++++++++++--- scripts/ci-changes.ts | 85 ++++++++++++++++++++- 2 files changed, 218 insertions(+), 13 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 3b99c75476..6d5cdc2384 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -145,8 +145,9 @@ function actionsDecision(options: { responses: (sha: string, commits: string[]) => Record; proof?: boolean | string; proofs?: (commits: string[]) => Record; - commits?: Record[]; + commits?: Record[]; base?: string; + baseIndex?: number; expectFailure?: boolean; grepExit?: number; }) { @@ -172,6 +173,10 @@ function actionsDecision(options: { const commits = [git("rev-parse", "HEAD")]; for (const files of options.commits ?? []) { for (const [file, content] of Object.entries(files)) { + if (content === null) { + rmSync(join(directory, file), { force: true }); + continue; + } mkdirSync(dirname(join(directory, file)), { recursive: true }); writeFileSync(join(directory, file), content); } @@ -250,10 +255,12 @@ process.exit(result.exitCode); pull_request: { labels: [], head: { ref: "fix", sha, repo: { full_name: repository } }, - base: { sha: options.base ?? commits[0] }, + base: { sha: options.base ?? commits[options.baseIndex ?? 0] }, }, merge_group: { - base_sha: options.commits?.length ? commits[0] : "b".repeat(40), + base_sha: options.commits?.length + ? commits[options.baseIndex ?? 0] + : "b".repeat(40), head_sha: sha, head_ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha}`, }, @@ -426,6 +433,58 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("only literal unfiltered full-job arrays prove current browser-file coverage", () => { + const file = "app/tests/selected.browser.test.ts"; + const array = `files=(\n ${file}\n)\nbun test --parallel "\${files[@]}"`; + for (const [run, covered] of [ + [array, true], + [ + array + .split("\n") + .map((line) => `# ${line}`) + .join("\n"), + false, + ], + [array.replace("bun test", 'bun test -t "one case"'), false], + [array.replace("bun test", "bun test --test-name-pattern=one"), false], + [array.replace("--parallel", "--parallel --shard=1/2"), false], + [array.replace("--parallel", "--parallel --unknown"), false], + [array.replace(file, "$FILE"), false], + [`# ${file}\nbun test app/tests/another.browser.test.ts`, false], + ] as const) { + const base = deps({ passed: { c2: ALL_CI }, changes: {} }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? [{ path: file, deleted: false }] + : base.diff(from, to), + read: (path) => + path === ".github/workflows/ci.yml" + ? JSON.stringify({ + jobs: { "app-browser-webkit": { steps: [{ run }] } }, + }) + : "process.env.OPENBOT_APP_BROWSER", + }); + expect(result.browserTests).toEqual(covered ? [] : [file]); + } + for (const manifest of [undefined, "jobs: ["]) { + const base = deps({ passed: { c2: ALL_CI }, changes: {} }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? [{ path: file, deleted: false }] + : base.diff(from, to), + read: (path) => + path === ".github/workflows/ci.yml" + ? manifest + : "process.env.OPENBOT_APP_BROWSER", + }); + expect(result.browserTests).toEqual([file]); + } + }); + test("an outstanding WebKit test survives a docs-only push after Chromium passed", () => { const file = "app/tests/composer-dictation-language.test.tsx"; for (const recovered of [false, true]) { @@ -443,6 +502,9 @@ describe("a pull request push", () => { files: { [file]: "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, }, }); const result = decide("ci", PR, { @@ -568,7 +630,7 @@ describe("a pull request push", () => { { ...base, diff: (from, to) => { - expect(from).toBe("c2"); + expect(["c2", PR.base]).toContain(from); return to === "merge" ? [{ path: "app/src/main.tsx", deleted: false }] : []; @@ -1509,8 +1571,62 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { - test("only supported producer events can discharge a PR's unlisted browser edit", () => { + test("restoring an unlisted browser file remains owed even when its old main tree passed", () => { const file = "app/tests/access-requests-layout.test.tsx"; + const content = "process.env.OPENBOT_APP_BROWSER"; + for (const event of ["pull_request", "merge_group"] as const) { + const result = actionsDecision({ + event, + commits: [ + { + [file]: content, + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + { [file]: null }, + { [file]: content }, + ], + baseIndex: 2, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { workflow_runs: [] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[2]}&per_page=100`]: + { workflow_runs: [] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[1]}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event: "push", + head_branch: "main", + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: API_BASELINE_JOBS }, + [`repos/CopilotKit/OpenBot/compare/${commits[2]}...${sha}`]: { + files: [{ filename: file }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + }), + }); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + expect(result.partial).toBe("true"); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + expect(result.app_browser).toBe("false"); + } + }); + + test("only supported producer events provide reusable fixed-list browser checks", () => { + const file = "app/tests/composer-dictation-language.test.tsx"; for (const [event, head_branch, covered] of [ ["workflow_dispatch", "feature", false], ["schedule", "main", false], @@ -1519,7 +1635,14 @@ describe("the checkout a passing run proves", () => { ] as const) { const result = actionsDecision({ event: "pull_request", - commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + commits: [ + { + [file]: "process.env.OPENBOT_APP_BROWSER", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + ], responses: (sha, commits) => ({ [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: { @@ -1548,7 +1671,7 @@ describe("the checkout a passing run proves", () => { } }); - test("a docs push retains failed partial browser work until the latest partial attempt passes", () => { + test("current unlisted work remains owed while partial results govern fixed-job reuse", () => { const app = "app/tests/access-requests-layout.test.tsx"; const desktop = "desktop/src/unlisted.browser.test.ts"; for (const state of [ @@ -1625,11 +1748,10 @@ describe("the checkout a passing run proves", () => { }; }, }); - expect(JSON.parse(result.browser_tests)).toEqual(recovered ? [] : [app]); - expect(JSON.parse(result.desktop_browser_tests)).toEqual( - recovered ? [] : [desktop], - ); - expect(result.partial).toBe(String(!recovered)); + expect(JSON.parse(result.browser_tests)).toEqual([app]); + expect(JSON.parse(result.desktop_browser_tests)).toEqual([desktop]); + expect(result.partial).toBe("true"); + expect(result.app_browser).toBe(String(!recovered)); expect(result.suite).toBe("false"); expect(result.static).toBe("false"); expect(result.build).toBe("false"); diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 71d03c8d75..30358c22ad 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -696,6 +696,7 @@ function decideSuite( browser: boolean, fullJob = false, forceWebKit = false, + covered?: Set, ) => { if (!changes) return; const named = changes @@ -712,7 +713,11 @@ function decideSuite( ...deps.mentions(named), ]; for (const file of files) { - if (isBunTest(file) && isBrowserTest(file, deps) === browser) { + if ( + isBunTest(file) && + isBrowserTest(file, deps) === browser && + !covered?.has(file) + ) { candidates.add(file); if (forceWebKit && !file.startsWith("desktop/")) webkit.add(file); } @@ -734,6 +739,10 @@ function decideSuite( } add(changes, true, run[output], output === "app_browser_webkit"); } + // Passing fixed lists prove nothing about files outside them, even when an older passing tree + // is restored exactly. Keep those files owed by this PR/group's own diff until they join a list. + current ??= currentChanges?.().filter((change) => !isIgnored(change.path)); + add(current, true, true, true, fullBrowserFiles(deps)); for (const file of [...candidates].sort()) { if (!isBrowserTest(file, deps)) { @@ -766,6 +775,80 @@ function decideSuite( } } +/** Only literal full arrays in the current browser jobs prove file coverage. Unknown is no proof. */ +function fullBrowserFiles(deps: Pick): Set { + const files = new Set(); + try { + const workflow = Bun.YAML.parse( + deps.read(".github/workflows/ci.yml") ?? "", + ) as { + jobs?: Record; + } | null; + for (const id of [ + "app-browser", + "app-browser-webkit", + "app-browser-desktop", + ]) { + for (const step of workflow?.jobs?.[id]?.steps ?? []) { + const run = step.run; + if ( + typeof run !== "string" || + step.if !== undefined || + run.includes("<<") || + /^(?:[ \t]*)(?:if|case|for|while|until)\b/m.test(run) + ) + continue; + const commands = run + .split("\n") + .filter((line) => /^[ \t]*bun[ \t]+test\b/.test(line)); + if ( + !commands.some((command) => { + const words = command.trim().split(/\s+/); + return ( + words[0] === "bun" && + words[1] === "test" && + words.at(-1) === `"\${files[@]}"` && + words + .slice(2, -1) + .every( + (flag) => + /^--parallel(?:=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*"))?$/.test( + flag, + ) || + /^--timeout=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*")$/.test(flag), + ) + ); + }) + ) + continue; + if ((run.match(/^[ \t]*files(?:\+|\[[^\]]+\])?=/gm) ?? []).length !== 1) + continue; + const body = run.match( + /^[ \t]*files=\([ \t]*\r?\n([\s\S]*?)^[ \t]*\)[ \t]*\r?$/m, + )?.[1]; + if (!body) continue; + const paths = body + .split("\n") + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith("#")); + if ( + !paths.every( + (path) => + /^(?:[\w.-]+\/)*[\w.-]+\.test\.tsx?$/.test(path) && + !path.split("/").includes(".."), + ) + ) + continue; + for (const path of paths) files.add(path); + } + } + return files; + } catch { + // An unreadable or unrecognised manifest must leave every changed browser file owed. + return new Set(); + } +} + /** A test that drives a real browser, which `bun test` alone skips. */ function isBrowserTest(file: string, deps: Pick): boolean { return ( From ec549ae13e61d1ab04c8085236079c48674ea28f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:15:52 -0800 Subject: [PATCH 09/21] Tests: disable commit signing in CI decision fixtures --- scripts/ci-changes.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 6d5cdc2384..450fdfa735 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -159,6 +159,7 @@ function actionsDecision(options: { return result.stdout.toString().trim(); }; git("init", "--quiet"); + git("config", "--local", "commit.gpgsign", "false"); git( "-c", "user.name=CI", From d3dd79aa6d2609881169693a27d1a382a0d9d0d0 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:17:03 -0800 Subject: [PATCH 10/21] Tests: override inherited signing for fixture Git commands --- scripts/ci-changes.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 450fdfa735..f2cf16c3c1 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -154,12 +154,14 @@ function actionsDecision(options: { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { const git = (...args: string[]) => { - const result = Bun.spawnSync(["git", ...args], { cwd: directory }); + const result = Bun.spawnSync( + ["git", "-c", "commit.gpgsign=false", ...args], + { cwd: directory }, + ); if (result.exitCode !== 0) throw new Error(result.stderr.toString()); return result.stdout.toString().trim(); }; git("init", "--quiet"); - git("config", "--local", "commit.gpgsign", "false"); git( "-c", "user.name=CI", From 766dc48cf1816420ec27be38e509bb0e25052a41 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:44:05 -0800 Subject: [PATCH 11/21] CI: bound and interleave historical proof lookups --- scripts/ci-changes.test.ts | 145 ++++++++++++++++++++++- scripts/ci-changes.ts | 230 +++++++++++++++++++++++-------------- 2 files changed, 285 insertions(+), 90 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index f2cf16c3c1..0d2336fb52 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -150,6 +150,7 @@ function actionsDecision(options: { baseIndex?: number; expectFailure?: boolean; grepExit?: number; + historyBudgetMs?: number; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -206,6 +207,10 @@ function actionsDecision(options: { proof: options.proof, proofs: options.proofs?.(commits), sha, + historyCalls: + options.historyBudgetMs === undefined + ? undefined + : join(directory, "history-called"), }), ); const gh = join(directory, "gh"); @@ -223,6 +228,7 @@ if (args[0] === "run" && args[1] === "download") { writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), proof); } else { const endpoint = args.find((arg) => arg.startsWith("repos/")); + if (fixture.historyCalls && endpoint?.includes("/actions/runs")) writeFileSync(fixture.historyCalls, "called"); if (!(endpoint in fixture.responses)) process.exit(1); const response = fixture.responses[endpoint]; console.log(JSON.stringify(args.includes("--slurp") ? (Array.isArray(response) ? response : [response]) : (Array.isArray(response) ? response[0] : response))); @@ -288,6 +294,7 @@ process.exit(result.exitCode); WORKFLOW_NAME: "CI", GITHUB_OUTPUT: output, GITHUB_STEP_SUMMARY: "", + CI_HISTORY_BUDGET_MS: String(options.historyBudgetMs ?? 45_000), }, }, ); @@ -297,6 +304,8 @@ process.exit(result.exitCode); return {}; } expect(result.exitCode).toBe(0); + if (options.historyBudgetMs === 0) + expect(existsSync(join(directory, "history-called"))).toBe(false); return Object.fromEntries( [ ...readFileSync(output, "utf8").matchAll( @@ -436,6 +445,39 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("scheduled cross-browser jobs cover listed files without duplicate partial work", () => { + const listed = "app/tests/composer-dictation-language.test.tsx"; + const unlisted = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/setupLayout.browser.test.ts"; + for (const extra of [false, true]) { + const files = [listed, ...(extra ? [unlisted, desktop] : [])]; + const base = deps({ + passed: { c2: ALL_CI }, + changes: { c2: ["app/src/main.tsx", ...files] }, + files: { + [listed]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + [unlisted]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? files.map((path) => ({ path, deleted: false })) + : base.diff(from, to), + }); + expect(result.run.app_browser_webkit).toBe(true); + expect(result.browserTests).toEqual(extra ? [unlisted] : []); + expect(result.webkitTests).toEqual(extra ? [unlisted] : []); + expect(result.desktopBrowserTests).toEqual(extra ? [desktop] : []); + expect(result.run.partial).toBe(extra); + } + }); test("only literal unfiltered full-job arrays prove current browser-file coverage", () => { const file = "app/tests/selected.browser.test.ts"; const array = `files=(\n ${file}\n)\nbun test --parallel "\${files[@]}"`; @@ -1420,6 +1462,50 @@ describe("a merge group", () => { ?.checks as string[]; const GROUP: MergeGroup = { head: "g", pr: { labels: [], head: "h" } }; + test("an exact PR proof is found before obsolete main-history lookups", () => { + const base = groupDeps({ passed: {}, changes: {} }); + const visited: string[] = []; + const result = decideMergeGroup( + "ci", + ["app/src/main.tsx"], + { + ...base, + passed: (sha) => { + visited.push(sha); + if (sha === "b" || sha === "b1") + throw new Error("obsolete main history must not be queried"); + return new Set(sha === "h" ? ALL_CI : []); + }, + diff: (from) => + from === "h" ? [] : [{ path: "app/src/main.tsx", deleted: false }], + }, + GROUP, + ); + expect(visited).toEqual(["g", "h"]); + expect(result.run.suite).toBe(false); + expect(result.run.app_browser_webkit).toBe(false); + }); + + test("an empty tree diff wins over an earlier equal-input test-only diff", () => { + const file = "app/tests/composer-dictation-language.test.tsx"; + const base = groupDeps({ + passed: { g: ALL_CI, h: ALL_CI }, + changes: { g: [file], h: [] }, + }); + const result = decideMergeGroup( + "ci", + [file], + { + ...base, + read: () => + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + }, + GROUP, + ); + expect(result.browserTests).toEqual([]); + expect(result.run.partial).toBe(false); + }); + test("a merge group without passing baselines retains changed browser files from its event base", () => { const file = "app/tests/access-requests-layout.test.tsx"; const base = groupDeps({ passed: {}, changes: { "event-base": [file] } }); @@ -1574,6 +1660,60 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("zero history budget runs unresolved checks and keeps current unlisted browser files", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + const result = actionsDecision({ + event: "pull_request", + historyBudgetMs: 0, + commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event: "push", + head_branch: "main", + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: API_BASELINE_JOBS }, + }), + }); + expect(result.static).toBe("true"); + expect(result.suite).toBe("true"); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + }); + + test("a cached static proof survives unreadable older history for unresolved checks", () => { + const result = actionsDecision({ + event: "pull_request", + commits: [{ "README.md": "docs" }], + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event: "push", + head_branch: "main", + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: [{ name: "format, lint, types", conclusion: "success" }] }, + }), + }); + expect(result.static).toBe("false"); + expect(result.suite).toBe("true"); + }); test("restoring an unlisted browser file remains owed even when its old main tree passed", () => { const file = "app/tests/access-requests-layout.test.tsx"; const content = "process.env.OPENBOT_APP_BROWSER"; @@ -1666,8 +1806,9 @@ describe("the checkout a passing run proves", () => { { jobs: API_BASELINE_JOBS }, }), }); - expect(JSON.parse(result.browser_tests)).toEqual(covered ? [] : [file]); - expect(result.partial).toBe(String(!covered)); + expect(JSON.parse(result.browser_tests)).toEqual([]); + expect(result.app_browser_webkit).toBe(String(!covered)); + expect(result.partial).toBe("false"); expect(result.suite).toBe("false"); expect(result.static).toBe("false"); expect(result.build).toBe("false"); diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 30358c22ad..010ec3eaf9 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -41,7 +41,9 @@ * bun scripts/ci-changes.ts ci|desktop * * Env: GITHUB_EVENT_PATH, GITHUB_EVENT_NAME, GITHUB_REF, GITHUB_SHA, GITHUB_REPOSITORY, - * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). Writes one + * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). + * CI_HISTORY_BUDGET_MS can shorten the 45000 ms historical-proof deadline (0..45000); each remote + * history call is limited to the remaining time or 5000 ms, whichever is less. Writes one * output per job (`true` to run it), the changed tests as JSON arrays, and `queue_run` (the merge * queue's run that stands in for this one, or empty) to $GITHUB_OUTPUT, and what it decided and why * to $GITHUB_STEP_SUMMARY. @@ -544,19 +546,31 @@ function decideFrom( } return names; }; - /** Along each history, the newest commit where every one of these checks passed. */ - const baselinesOf = (checks: string[]) => - histories.flatMap((ancestors) => { - for (const sha of ancestors) { + /** Visit each history at the same depth before looking farther back on either one. */ + const baselinesOf = (checks: string[]) => { + const baselines: string[] = []; + const found = new Set(); + const depth = Math.max(0, ...histories.map((history) => history.length)); + for (let index = 0; index < depth; index++) { + for (const [lane, ancestors] of histories.entries()) { + if (found.has(lane)) continue; + const sha = ancestors[index]; + if (!sha) continue; const trees = deps.testedTrees ? deps.testedTrees(sha, checks) : checks.every((check) => passed(sha).has(check)) ? [sha] : []; - if (trees.length > 0) return trees; + if (trees.length > 0) found.add(lane); + for (const tree of trees) { + baselines.push(tree); + if (since(tree).length === 0) return baselines; + } } - return []; - }); + if (found.size === histories.length) break; + } + return baselines; + }; const changesSince = new Map(); const since = (sha: string) => { let changes = changesSince.get(sha); @@ -605,8 +619,11 @@ function decideFrom( changes.filter( (change) => !manualOnly(change.path) && rule.reads(change.path), ).length; - return usable.reduce((best, changes) => - readBy(changes) < readBy(best) ? changes : best, + return ( + usable.find((changes) => changes.length === 0) ?? + usable.reduce((best, changes) => + readBy(changes) < readBy(best) ? changes : best, + ) ); }; @@ -744,7 +761,16 @@ function decideSuite( current ??= currentChanges?.().filter((change) => !isIgnored(change.path)); add(current, true, true, true, fullBrowserFiles(deps)); + const coveredByCrossBrowser = run.app_browser_webkit + ? fullBrowserFiles(deps, ["app-browser-webkit"]) + : new Set(); for (const file of [...candidates].sort()) { + if ( + !file.startsWith("desktop/") && + coveredByCrossBrowser.has(file) && + isBrowserTest(file, deps) + ) + continue; if (!isBrowserTest(file, deps)) { decision.tests.push(file); } else if (file.startsWith("desktop/")) { @@ -776,7 +802,10 @@ function decideSuite( } /** Only literal full arrays in the current browser jobs prove file coverage. Unknown is no proof. */ -function fullBrowserFiles(deps: Pick): Set { +function fullBrowserFiles( + deps: Pick, + jobs = ["app-browser", "app-browser-webkit", "app-browser-desktop"], +): Set { const files = new Set(); try { const workflow = Bun.YAML.parse( @@ -784,11 +813,7 @@ function fullBrowserFiles(deps: Pick): Set { ) as { jobs?: Record; } | null; - for (const id of [ - "app-browser", - "app-browser-webkit", - "app-browser-desktop", - ]) { + for (const id of jobs) { for (const step of workflow?.jobs?.[id]?.steps ?? []) { const run = step.run; if ( @@ -1197,8 +1222,16 @@ function describe(changes: Change[]): string { // --------------------------------------------------------------------------------------------- // Running it in Actions. -function exec(cmd: string[], allowedExitCode?: number): string { - const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" }); +function exec( + cmd: string[], + allowedExitCode?: number, + timeout?: number, +): string { + const result = Bun.spawnSync(cmd, { + stdout: "pipe", + stderr: "pipe", + timeout, + }); if (result.exitCode !== 0 && result.exitCode !== allowedExitCode) { throw new Error(`${cmd.join(" ")}: ${result.stderr.toString().trim()}`); } @@ -1221,9 +1254,13 @@ type ApiJob = { }; /** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ -function jobsOf(repository: string, run: Pick): ApiJob[] { +function jobsOf( + repository: string, + run: Pick, + command: (cmd: string[]) => string = exec, +): ApiJob[] { const pages = JSON.parse( - exec([ + command([ "gh", "api", "--paginate", @@ -1260,6 +1297,19 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); + // Test overrides can shorten this deadline, never extend it beyond the production bound. + const requestedBudget = process.env.CI_HISTORY_BUDGET_MS; + const budgetMs = + requestedBudget !== undefined && /^\d+$/.test(requestedBudget) + ? Math.min(45_000, Number(requestedBudget)) + : 45_000; + const deadline = performance.now() + budgetMs; + const remaining = () => Math.max(0, Math.floor(deadline - performance.now())); + const historyCommand = (cmd: string[]) => { + const timeout = Math.min(5_000, remaining()); + if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); + return exec(cmd, undefined, timeout); + }; const browserChecks = new Set( CI_RULES.filter((rule) => ["app_browser", "app_browser_webkit"].includes(rule.output), @@ -1270,43 +1320,47 @@ function liveDeps( const cached = records.get(sha); if (cached) return cached; const trees = new Map>(); - const runs = ( - JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, - ]), - ).workflow_runs as ApiRun[] - ).filter( - (run) => - run.path === WORKFLOW_PATH[workflow] && - run.id !== currentRun && - trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), - ); + records.set(sha, trees); + if (remaining() <= 0) return trees; + let runs: ApiRun[]; + try { + runs = ( + JSON.parse( + historyCommand([ + "gh", + "api", + `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, + ]), + ).workflow_runs as ApiRun[] + ).filter( + (run) => + run.path === WORKFLOW_PATH[workflow] && + run.id !== currentRun && + trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), + ); + } catch { + return trees; + } for (const run of runs) { + if (remaining() <= 0) break; let tree = testedCheckout(workflow, sha, run.event); if (workflow === "ci" && run.event === "pull_request") { // Actions attributes this run to the PR head, but checkout tested its temporary merge. // Runs before this proof existed, expired artifacts and unreachable trees never stand in. const directory = mkdtempSync(join(tmpdir(), "openbot-ci-tree-")); try { - const downloaded = Bun.spawnSync( - [ - "gh", - "run", - "download", - String(run.id), - "--repo", - repository, - "--name", - `ci-tested-tree-${run.id}`, - "--dir", - directory, - ], - { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, - ); - if (downloaded.exitCode !== 0) continue; + historyCommand([ + "gh", + "run", + "download", + String(run.id), + "--repo", + repository, + "--name", + `ci-tested-tree-${run.id}`, + "--dir", + directory, + ]); tree = testedCheckout( workflow, sha, @@ -1320,18 +1374,15 @@ function liveDeps( stderr: "pipe", }).exitCode === 0; if (!present()) { - const fetched = Bun.spawnSync( - [ - "git", - "fetch", - "--no-tags", - "--filter=blob:none", - "origin", - tree, - ], - { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, - ); - if (fetched.exitCode !== 0 || !present()) continue; + historyCommand([ + "git", + "fetch", + "--no-tags", + "--filter=blob:none", + "origin", + tree, + ]); + if (!present()) continue; } } catch { continue; @@ -1340,33 +1391,36 @@ function liveDeps( } } if (!tree) continue; - const names = trees.get(tree) ?? new Set(); - const jobs = jobsOf(repository, run); - // A fixed browser list cannot discharge a failed unlisted-file obligation. Failed-only - // reruns retain older jobs, so only the latest partial result establishes that coverage. - const partial = jobs - .filter((job) => job.name === "tests (changed files)") - .sort( - (a, b) => - (b.run_attempt ?? 0) - (a.run_attempt ?? 0) || - (b.id ?? 0) - (a.id ?? 0), - )[0]; - const browserCovered = - workflow !== "ci" || - // Only supported producers discover PR changes or test the protected main branch. - ((["pull_request", "merge_group"].includes(run.event) || - (run.event === "push" && run.head_branch === "main")) && - (partial?.conclusion === "success" || - partial?.conclusion === "skipped")); - for (const job of jobs) - if ( - job.conclusion === "success" && - (browserCovered || !browserChecks.has(job.name)) - ) - names.add(job.name); - trees.set(tree, names); + try { + const names = trees.get(tree) ?? new Set(); + const jobs = jobsOf(repository, run, historyCommand); + // A fixed browser list cannot discharge a failed unlisted-file obligation. Failed-only + // reruns retain older jobs, so only the latest partial result establishes that coverage. + const partial = jobs + .filter((job) => job.name === "tests (changed files)") + .sort( + (a, b) => + (b.run_attempt ?? 0) - (a.run_attempt ?? 0) || + (b.id ?? 0) - (a.id ?? 0), + )[0]; + const browserCovered = + workflow !== "ci" || + // Only supported producers discover PR changes or test the protected main branch. + ((["pull_request", "merge_group"].includes(run.event) || + (run.event === "push" && run.head_branch === "main")) && + (partial?.conclusion === "success" || + partial?.conclusion === "skipped")); + for (const job of jobs) + if ( + job.conclusion === "success" && + (browserCovered || !browserChecks.has(job.name)) + ) + names.add(job.name); + trees.set(tree, names); + } catch { + // An unreadable run is no proof; earlier completed/cached proofs remain usable. + } } - records.set(sha, trees); return trees; }; return { From d3b887c15f5c3d6847d543955e040f1b8a19a148 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:54:24 -0800 Subject: [PATCH 12/21] CI: reuse current main history and classify browser tests by root --- scripts/ci-changes.test.ts | 125 ++++++++++++++++++++++++++++++++++++- scripts/ci-changes.ts | 41 +++++++----- 2 files changed, 149 insertions(+), 17 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 0d2336fb52..9ba5fe6b07 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -22,6 +22,7 @@ import { decideMainPush, decideMergeGroup, isBunTest, + isBrowserTest, isCode, isDocs, isIgnored, @@ -133,8 +134,7 @@ const readTracked = (path: string) => { /** A test that drives a real browser, as ci-changes.ts tells one. */ const isBrowserFile = (file: string) => - file.endsWith(".browser.test.ts") || - (readTracked(file)?.includes("OPENBOT_APP_BROWSER") ?? false); + isBrowserTest(file, { read: readTracked }); /** This checkout, as the merge group's `changes` job reads it. */ const REAL = { mentions: realMentions, read: readTracked }; @@ -445,6 +445,105 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("CI compares checkout/main and PR history without replaying upstream-only browser edits", () => { + const own = "app/tests/composer-dictation-language.test.tsx"; + const upstream = "app/tests/upstream-only.browser.test.ts"; + const base = deps({ + passed: {}, + changes: {}, + files: { + [own]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + }); + const histories = { + checkout: ["checkout", "main", "old"], + head: ["head", "old"], + }; + const result = decide( + "ci", + { ...PR, head: "head", checkout: "checkout", base: "main" }, + { + ...base, + ancestors: (head) => histories[head as keyof typeof histories], + passed: (sha) => + new Set(["main", "head", "old"].includes(sha) ? ALL_CI : []), + diff: (from, to) => { + expect(to).toBe("checkout"); + return ( + from === "main" + ? [own] + : from === "head" + ? [upstream] + : [own, upstream] + ).map((path) => ({ path, deleted: false })); + }, + }, + ); + expect(result.browserTests).toEqual([own]); + expect(result.webkitTests).toEqual([own]); + expect(result.run.suite).toBe(false); + }); + + test("script fixture markers stay ordinary suite tests rather than browser obligations", () => { + const scripts = [ + "scripts/ci-changes.test.ts", + "scripts/ci-run-tests.test.ts", + ]; + for (const source of [false, true]) { + const paths = [...scripts, ...(source ? ["server/src/main.ts"] : [])]; + const base = deps({ + passed: { c2: ALL_CI }, + changes: { c2: paths }, + files: Object.fromEntries( + scripts.map((file) => [ + file, + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ]), + ), + }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? paths.map((path) => ({ path, deleted: false })) + : base.diff(from, to), + }); + expect(result.tests).toEqual(source ? [] : scripts); + expect(result.browserTests).toEqual([]); + expect(result.webkitTests).toEqual([]); + expect(result.run.partial).toBe(!source); + expect(result.run.app_browser_webkit).toBe(false); + } + }); + + test("frontend/root test markers and explicit browser filenames still select browsers", () => { + const files = [ + "app/tests/view.test.tsx", + "desktop/src/view.test.tsx", + "extension/tests/view.test.ts", + "tests/view.test.ts", + "scripts/opt-in.browser.test.ts", + ]; + const base = deps({ + passed: { c2: ALL_CI }, + changes: { c2: files }, + files: Object.fromEntries( + files + .filter((file) => !file.startsWith("scripts/")) + .map((file) => [file, "process.env.OPENBOT_APP_BROWSER"]), + ), + }); + const result = decide("ci", PR, base); + expect(result.browserTests).toEqual( + files.filter((file) => !file.startsWith("desktop/")).sort(), + ); + expect(result.desktopBrowserTests).toEqual(["desktop/src/view.test.tsx"]); + expect(result.tests).toEqual([]); + }); test("scheduled cross-browser jobs cover listed files without duplicate partial work", () => { const listed = "app/tests/composer-dictation-language.test.tsx"; const unlisted = "app/tests/access-requests-layout.test.tsx"; @@ -2349,6 +2448,28 @@ describe("a release PR", () => { describe("the Desktop workflow", () => { const ALL_DESKTOP = DESKTOP_RULES.flatMap((rule) => rule.checks); + test("Desktop keeps only raw PR-head history and compares the raw head", () => { + const base = deps({ passed: {}, changes: {} }); + const result = decide( + "desktop", + { ...PR, head: "desktop-head", checkout: "ci-merge" }, + { + ...base, + ancestors: (head) => { + expect(head).toBe("desktop-head"); + return [head]; + }, + passed: () => new Set(ALL_DESKTOP), + diff: (from, to) => { + expect(from).toBe("desktop-head"); + expect(to).toBe("desktop-head"); + return []; + }, + }, + ); + expect(running(result)).toEqual([]); + }); + test("a Desktop test-only edit gets a frozen install and Desktop types in static CI", () => { for (const source of [false, true]) { const decision = decide( diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 010ec3eaf9..c4922ffa59 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -513,19 +513,19 @@ export function decide( // A release PR that changes more than the release files is checked like any other PR. } - return decideFrom( - workflow, - pr.checkout ?? pr.head, - [deps.ancestors(pr.head)], - deps, - () => deps.diff(pr.base, pr.checkout ?? pr.head), + const checkout = workflow === "ci" ? (pr.checkout ?? pr.head) : pr.head; + const histories = [deps.ancestors(checkout)]; + if (workflow === "ci" && checkout !== pr.head) + histories.push(deps.ancestors(pr.head)); + return decideFrom(workflow, checkout, histories, deps, () => + deps.diff(pr.base, checkout), ); } /** * Decides every job for the tree at `head`, from the commits where each job last passed. `histories` - * are lists of commits newest first, each a line of first parents: for a pull request its own, for a - * merge group main's and the pull request's. A job is skipped when, along any one of them, nothing it + * are lists of commits newest first, each a line of first parents: CI uses the checkout/main and PR + * lines, Desktop the PR head alone. A job is skipped when, along any one of them, nothing it * reads changed between the newest commit where it passed and `head`: its inputs are then the very * files a passing run already checked. */ @@ -548,7 +548,7 @@ function decideFrom( }; /** Visit each history at the same depth before looking farther back on either one. */ const baselinesOf = (checks: string[]) => { - const baselines: string[] = []; + const baselines: string[][] = histories.map(() => []); const found = new Set(); const depth = Math.max(0, ...histories.map((history) => history.length)); for (let index = 0; index < depth; index++) { @@ -563,13 +563,14 @@ function decideFrom( : []; if (trees.length > 0) found.add(lane); for (const tree of trees) { - baselines.push(tree); - if (since(tree).length === 0) return baselines; + baselines[lane].push(tree); + if (since(tree).length === 0) return baselines.flat(); } } if (found.size === histories.length) break; } - return baselines; + // Equal-input ties prefer the checkout/main lane, independent of interleaved discovery order. + return baselines.flat(); }; const changesSince = new Map(); const since = (sha: string) => { @@ -658,6 +659,7 @@ function decideFrom( (change) => !change.deleted && isBunTest(change.path) && + isBrowserTest(change.path, deps) && (deps.read(change.path)?.includes("OPENBOT_APP_ENGINES") ?? false), ); if (webkitTest) { @@ -874,11 +876,20 @@ function fullBrowserFiles( } } -/** A test that drives a real browser, which `bun test` alone skips. */ -function isBrowserTest(file: string, deps: Pick): boolean { +const browserMarkerRoot = matcher( + "app/tests/**", + "desktop/src/**", + "desktop/tests/**", + "extension/tests/**", + "tests/**", +); + +/** Frontend/root tests may opt in by marker; explicit browser filenames opt in anywhere. */ +export function isBrowserTest(file: string, deps: Pick): boolean { return ( file.endsWith(".browser.test.ts") || - (deps.read(file)?.includes("OPENBOT_APP_BROWSER") ?? false) + (browserMarkerRoot(file) && + (deps.read(file)?.includes("OPENBOT_APP_BROWSER") ?? false)) ); } From 029bc762bb0ce201fba16e3cf20bfd6eb83996f3 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:11:30 -0800 Subject: [PATCH 13/21] CI: build app assets for partial print browser tests --- .github/workflows/ci.yml | 4 +++ scripts/ci-run-tests.test.ts | 48 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c664bfb60..49d111acc1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -974,6 +974,10 @@ jobs: - name: Install WebKit 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/scripts/ci-run-tests.test.ts b/scripts/ci-run-tests.test.ts index aac9487dc1..31fd84f24d 100644 --- a/scripts/ci-run-tests.test.ts +++ b/scripts/ci-run-tests.test.ts @@ -15,6 +15,54 @@ import { data, Evaluator, Lexer, Parser } from "@actions/expressions"; const ROOT = join(import.meta.dir, ".."); const SETUP_TEST = "desktop/src/setupLayout.browser.test.ts"; +test("the partial job builds the shipped app only for the print-page browser test, before testing", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: Record; + }; + const steps = workflow.jobs["changed-tests"].steps; + const build = steps.findIndex( + (step) => step.run === "bun run --cwd app build", + ); + const install = steps.findIndex( + (step) => step.run === "bun install --frozen-lockfile", + ); + const tests = steps.findIndex( + (step) => step.run === "bun scripts/ci-run-tests.ts", + ); + expect(build).toBeGreaterThan(install); + expect(build).toBeLessThan(tests); + const condition = steps[build]?.if; + expect(condition).toBeDefined(); + const tree = new Parser( + new Lexer(condition ?? "").lex().tokens, + ["needs"], + [], + ).parse(); + const print = "app/tests/artifact-print-browser.test.ts"; + for (const [files, expected] of [ + [[], false], + [["app/tests/composer-dictation-language.test.tsx"], false], + [[print], true], + [["app/tests/composer-dictation-language.test.tsx", print], true], + [[`${print}.other.test.ts`], false], + [[SETUP_TEST], false], + ] as const) { + const context = JSON.parse( + JSON.stringify({ + needs: { + changes: { outputs: { browser_tests: JSON.stringify(files) } }, + }, + }), + data.reviver, + ) as data.Dictionary; + expect(new Evaluator(tree, context).evaluate()).toEqual( + new data.BooleanData(expected), + ); + } +}); + function runDesktopTests(files: string[], failWebKit = false) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-run-tests-")); try { From 82028b64961abea884b11df4a30333e7b269bc10 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:17:01 -0800 Subject: [PATCH 14/21] CI: bound the entire queued pull request lookup --- scripts/ci-changes.test.ts | 164 ++++++++++++++++++++++++++++++++++++- scripts/ci-changes.ts | 68 ++++++++------- 2 files changed, 201 insertions(+), 31 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 4b97a68811..6268522e94 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -152,6 +152,12 @@ function actionsDecision(options: { grepExit?: number; historyBudgetMs?: number; probeDelayMs?: number; + queue?: { + delays?: Partial>; + fetchFails?: boolean; + calls: string[]; + reason: string; + }; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -208,6 +214,8 @@ function actionsDecision(options: { proof: options.proof, proofs: options.proofs?.(commits), sha, + queue: options.queue, + queueCalls: join(directory, "queue-calls.jsonl"), historyCalls: options.historyBudgetMs === undefined ? undefined @@ -218,7 +226,7 @@ function actionsDecision(options: { writeFileSync( gh, `#!${process.execPath} -import { readFileSync, writeFileSync } from "node:fs"; +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; const fixture = JSON.parse(readFileSync(process.env.CI_FIXTURE, "utf8")); const args = process.argv.slice(2); @@ -229,6 +237,10 @@ if (args[0] === "run" && args[1] === "download") { writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), proof); } else { const endpoint = args.find((arg) => arg.startsWith("repos/")); + if (fixture.queue && endpoint?.includes("/pulls/")) { + appendFileSync(fixture.queueCalls, JSON.stringify("api") + "\\n"); + Bun.sleepSync(fixture.queue.delays?.api ?? 0); + } if (fixture.historyCalls && endpoint?.includes("/actions/runs")) writeFileSync(fixture.historyCalls, "called"); if (!(endpoint in fixture.responses)) process.exit(1); const response = fixture.responses[endpoint]; @@ -237,7 +249,11 @@ if (args[0] === "run" && args[1] === "download") { `, ); chmodSync(gh, 0o755); - if (options.grepExit !== undefined || options.probeDelayMs !== undefined) { + if ( + options.grepExit !== undefined || + options.probeDelayMs !== undefined || + options.queue + ) { const realGit = Bun.which("git"); if (!realGit) throw new Error("git is not installed"); const wrappedGit = join(directory, "git"); @@ -245,6 +261,13 @@ if (args[0] === "run" && args[1] === "download") { wrappedGit, `#!${process.execPath} const args = process.argv.slice(2); +const fixture = JSON.parse(require("node:fs").readFileSync(process.env.CI_FIXTURE, "utf8")); +if (fixture.queue && ["fetch", "cat-file"].includes(args[0])) { + const command = args[0] === "fetch" ? "fetch" : "presence"; + require("node:fs").appendFileSync(fixture.queueCalls, JSON.stringify(command) + "\\n"); + Bun.sleepSync(fixture.queue.delays?.[command] ?? 0); + if (command === "fetch") process.exit(fixture.queue.fetchFails ? 1 : 0); +} if (args[0] === "cat-file" && ${options.probeDelayMs !== undefined}) { require("node:fs").writeFileSync(${JSON.stringify(join(directory, "probe-called"))}, "called"); Bun.sleepSync(${options.probeDelayMs ?? 0}); @@ -309,6 +332,16 @@ process.exit(result.exitCode); return {}; } expect(result.exitCode).toBe(0); + if (options.queue) { + const calls = existsSync(join(directory, "queue-calls.jsonl")) + ? readFileSync(join(directory, "queue-calls.jsonl"), "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)) + : []; + expect(calls).toEqual(options.queue.calls); + expect(result.stdout.toString()).toContain(options.queue.reason); + } if (options.historyBudgetMs === 0) expect(existsSync(join(directory, "history-called"))).toBe(false); if (options.probeDelayMs !== undefined) @@ -1868,6 +1901,133 @@ describe("a merge group", () => { expect(running(decision)).toEqual(everyJob); }); + for (const stall of ["api", "fetch", "presence"] as const) { + test(`the real merge-group CLI drops stalled queued-PR ${stall} within its shared budget`, () => { + const started = performance.now(); + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 600, + commits: [{ "server/src/main.ts": "changed" }], + queue: { + delays: { [stall]: 1_800 }, + calls: + stall === "api" + ? ["api"] + : stall === "fetch" + ? ["api", "fetch"] + : ["api", "fetch", "presence"], + reason: + stall === "api" + ? "pull request could not be read" + : stall === "fetch" + ? "passed on main." + : "labelled full-ci", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: stall === "presence" ? [{ name: "full-ci" }] : [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(performance.now() - started).toBeLessThan(1_500); + expect(result.suite).toBe("true"); + }); + } + + test("queued API and fetch share one deadline rather than starting a timer per command", () => { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 600, + commits: [{ "server/src/main.ts": "changed" }], + queue: { + delays: { api: 350, fetch: 350 }, + calls: ["api", "fetch"], + reason: "passed on main.", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("a readable same-repository queued head still supplies PR history", () => { + const result = actionsDecision({ + event: "merge_group", + commits: [{ "server/src/main.ts": "changed" }], + queue: { + calls: ["api", "fetch", "presence"], + reason: "passed on main or on the pull request", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("zero queued-PR budget avoids even its API call and falls back safely", () => { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 0, + commits: [{ "server/src/main.ts": "changed" }], + queue: { calls: [], reason: "pull request could not be read" }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("queued-PR lookup retains labels after fetch failure and never fetches a fork", () => { + for (const fork of [false, true]) { + const result = actionsDecision({ + event: "merge_group", + commits: [{ "README.md": "docs" }], + queue: { + fetchFails: true, + calls: fork ? ["api"] : ["api", "fetch"], + reason: "labelled full-ci", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "README.md" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [{ name: "full-ci" }], + head: { + sha, + repo: { full_name: fork ? "Other/Fork" : "CopilotKit/OpenBot" }, + }, + }, + }), + }); + expect(result.suite).toBe("true"); + } + }); + test("reads the queued pull request from the group's ref", () => { const sha = "bff854d1ab9cc25580bd3efa3308a7f954069c5c"; expect( diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 6be6eaea89..75c4222dc9 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -43,7 +43,8 @@ * Env: GITHUB_EVENT_PATH, GITHUB_EVENT_NAME, GITHUB_REF, GITHUB_SHA, GITHUB_REPOSITORY, * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). * CI_HISTORY_BUDGET_MS can shorten the 45000 ms historical-proof deadline (0..45000); each remote - * history call is limited to the remaining time or 5000 ms, whichever is less. Writes one + * history call is limited to the remaining time or 5000 ms, whichever is less. The optional queued + * PR lookup shares a separate 5000 ms deadline, shortened by the same override (0 skips it). Writes one * output per job (`true` to run it), the changed tests as JSON arrays, and `queue_run` (the merge * queue's run that stands in for this one, or empty) to $GITHUB_OUTPUT, and what it decided and why * to $GITHUB_STEP_SUMMARY. @@ -1339,6 +1340,25 @@ export function testedCheckout( return undefined; } +/** One monotonic deadline for optional remote proof commands, with a shorter test override. */ +function historyCommands(maximumMs: number) { + const requested = process.env.CI_HISTORY_BUDGET_MS; + const budgetMs = + requested !== undefined && /^\d+$/.test(requested) + ? Math.min(maximumMs, Number(requested)) + : maximumMs; + const deadline = performance.now() + budgetMs; + const remaining = () => Math.max(0, Math.floor(deadline - performance.now())); + return { + remaining, + run: (cmd: string[]) => { + const timeout = Math.min(5_000, remaining()); + if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); + return exec(cmd, undefined, timeout); + }, + }; +} + function liveDeps( workflow: Workflow, repository: string, @@ -1346,19 +1366,7 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); - // Test overrides can shorten this deadline, never extend it beyond the production bound. - const requestedBudget = process.env.CI_HISTORY_BUDGET_MS; - const budgetMs = - requestedBudget !== undefined && /^\d+$/.test(requestedBudget) - ? Math.min(45_000, Number(requestedBudget)) - : 45_000; - const deadline = performance.now() + budgetMs; - const remaining = () => Math.max(0, Math.floor(deadline - performance.now())); - const historyCommand = (cmd: string[]) => { - const timeout = Math.min(5_000, remaining()); - if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); - return exec(cmd, undefined, timeout); - }; + const { remaining, run: historyCommand } = historyCommands(45_000); const browserChecks = new Set( CI_RULES.filter((rule) => ["app_browser", "app_browser_webkit"].includes(rule.output), @@ -1596,9 +1604,10 @@ function queuedPull( ): MergeGroup["pr"] | undefined { const number = queuedPullRequest(headRef); if (number === undefined) return undefined; + const { run } = historyCommands(5_000); try { const pull = JSON.parse( - exec(["gh", "api", `repos/${repository}/pulls/${number}`]), + run(["gh", "api", `repos/${repository}/pulls/${number}`]), ) as { labels?: { name: string }[]; head: { sha: string; repo?: { full_name?: string } | null }; @@ -1607,20 +1616,21 @@ function queuedPull( const ours = pull.head.repo?.full_name?.toLowerCase() === repository.toLowerCase(); if (!ours || !/^[0-9a-f]{40}$/.test(pull.head.sha)) return { labels }; - // Its commits and trees, as the pull request's own `changes` job fetches them. - const fetched = Bun.spawnSync([ - "git", - "fetch", - "--no-tags", - "--filter=blob:none", - "origin", - `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`, - ]); - const has = - fetched.exitCode === 0 && - Bun.spawnSync(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]) - .exitCode === 0; - return has ? { labels, head: pull.head.sha } : { labels }; + // Its commits and trees share the API call's deadline; failed lookups retain readable labels. + try { + run([ + "git", + "fetch", + "--no-tags", + "--filter=blob:none", + "origin", + `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`, + ]); + run(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]); + return { labels, head: pull.head.sha }; + } catch { + return { labels }; + } } catch { return undefined; } From 8e320be7e59dc8eedfbf0c52e4e1a0d9dabdae54 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:20:18 -0800 Subject: [PATCH 15/21] CI: require readable queue labels before skipping docs checks --- scripts/ci-changes.test.ts | 56 ++++++++++++++++++++++++++++++++++++-- scripts/ci-changes.ts | 10 +++---- 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 6268522e94..e3f96fbfcd 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1593,8 +1593,54 @@ describe("a merge group", () => { expect(result.suite).toBe("false"); }); + test("docs require readable queued-PR metadata before they can skip full checks", () => { + const minimal = { mentions: () => [], read: () => "" }; + for (const group of [ + undefined, + { head: "merge" }, + { head: "merge", pr: { labels: ["full-ci"] } }, + ]) { + const result = decideMergeGroup("ci", ["README.md"], minimal, group); + expect(result.ignoredOnly).toBe(false); + expect(running(result)).toEqual(everyJob); + } + const readable = decideMergeGroup("ci", ["README.md"], minimal, { + head: "merge", + pr: { labels: [] }, + }); + expect(readable.ignoredOnly).toBe(true); + expect(running(readable)).toEqual([]); + }); + + test("the real docs-only merge-group CLI runs full checks when its full-ci label cannot be read", () => { + for (const budget of [0, 600]) { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: budget, + commits: [{ "README.md": "docs" }], + queue: { + delays: { api: 1_800 }, + calls: budget === 0 ? [] : ["api"], + reason: "pull request could not be read", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "README.md" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [{ name: "full-ci" }], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.ignored_only).toBe("false"); + expect(result.suite).toBe("true"); + expect(result.build).toBe("true"); + } + }); + test("that changes only CHANGELOG.md runs nothing, not even the tests that name it", () => { - const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL); + const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL, GROUP); expect(running(decision)).toEqual([]); expect(decision.ignoredOnly).toBe(true); expect(decision.reasons[0]).toContain("CHANGELOG.md"); @@ -1605,6 +1651,7 @@ describe("a merge group", () => { "ci", [...UNREAD_DOCS, "CHANGELOG.md"], REAL, + GROUP, ); expect(running(decision)).toEqual( decision.tests.length > 0 ? ["partial"] : [], @@ -1618,7 +1665,12 @@ describe("a merge group", () => { }); test("a doc a test reads runs that test, and no job", () => { - const decision = decideMergeGroup("ci", ["docs/agent-frameworks.md"], REAL); + const decision = decideMergeGroup( + "ci", + ["docs/agent-frameworks.md"], + REAL, + GROUP, + ); expect(running(decision)).toEqual(["partial"]); expect(decision.tests).toContain( "tests/agent-frameworks-receivers.test.ts", diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 75c4222dc9..36547ce981 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1170,6 +1170,11 @@ export function decideMergeGroup( ...fullDecision(workflow, why, deps, currentChanges), ignoredOnly: false, }); + if (!group?.pr) { + return full( + "A merge group whose pull request could not be read: everything runs.", + ); + } // The explicit override applies even when every changed file is a document. if (group?.pr?.labels.includes("full-ci")) { return full( @@ -1227,11 +1232,6 @@ export function decideMergeGroup( if (!group || !ancestors || !passed || !diff || !releaseViolations) { return full("A merge group: everything runs."); } - if (!group.pr) { - return full( - "A merge group whose pull request could not be read: everything runs.", - ); - } if (group.pr.labels.includes("full-ci")) { return full( "A merge group of a pull request labelled full-ci: everything runs.", From 8b7f93ff2b368512f08669e5313e95dc3659587f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:33:12 -0800 Subject: [PATCH 16/21] Tests: await company sign-in socket before holding out the page --- app/tests/company-sign-in.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/tests/company-sign-in.test.tsx b/app/tests/company-sign-in.test.tsx index c51c97d5de..ce2e9710ad 100644 --- a/app/tests/company-sign-in.test.tsx +++ b/app/tests/company-sign-in.test.tsx @@ -424,6 +424,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. From e5d6d368f5cb8dd3875a657e1b073bf7b47afae1 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 14:01:59 -0800 Subject: [PATCH 17/21] CI: no browser test runs twice, and only full-ci replaces a run - Only the full-ci label cancels and replaces a pull request's CI run. Any other label waits for the run in progress, then finds its checks passed on the same commit and skips them. A label run cannot skip everything up front: a skipped verify counts as passing. - 14 files in the cross-browser list ignored the engine selection and ran in full in both the Chromium and the WebKit leg, artifacts-screens (about 11 minutes) among them. They now run where Chromium is selected (ownBrowsersAsked), once. sidebar-window-buttons launches through launchBrowserEngines. A test holds every listed file to the selection. - A full browser job that runs covers the changed files in its list, so they no longer run a second time in tests (changed files). The desktop setup window's step names its file in a list the planner can read. - The queued pull request's head is fetched on a deadline of its own, and a merge group that has to go without its history says why. - The budget test builds matrix legs as GitHub does: include and exclude are lists of legs, not axes. - Comments and docs/releasing.md name the engine and shard checks. --- .github/workflows/ci.yml | 27 +++++-- app/tests/artifact-bridge-browser.test.ts | 4 +- app/tests/artifact-collab-browser.test.tsx | 4 +- .../artifact-error-notice-layout.test.tsx | 4 +- app/tests/artifact-events-socket.test.ts | 4 +- app/tests/artifact-kinds-browser.test.tsx | 4 +- app/tests/artifacts-kit.test.ts | 4 +- app/tests/artifacts-screens.test.tsx | 4 +- app/tests/board-row-layout.test.tsx | 4 +- app/tests/browser-engines.test.ts | 49 +++++++++++- app/tests/browser-engines.ts | 38 +++++++-- app/tests/plan-notices-layout.test.tsx | 4 +- app/tests/renderer-crash.test.ts | 4 +- app/tests/select-scrolls-layout.test.tsx | 4 +- app/tests/sidebar-current-row.test.tsx | 4 +- app/tests/sidebar-window-buttons.test.tsx | 17 ++-- app/tests/trusted-types-build.test.ts | 4 +- app/tests/workspace-snapshots-layout.test.tsx | 4 +- docs/releasing.md | 2 +- scripts/ci-budgets.test.ts | 79 ++++++++++++++++--- scripts/ci-changes.test.ts | 49 ++++++++++-- scripts/ci-changes.ts | 65 ++++++++++++--- scripts/release-publish-order.test.ts | 3 +- scripts/workflow-concurrency.test.ts | 12 ++- 24 files changed, 326 insertions(+), 71 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49d111acc1..344710af26 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,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. # -# A pull request's newer push or label starts a replacement run. 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). +# 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 @@ -607,8 +610,12 @@ jobs: # link, the page, a reload, and the bare address an older tab kept. 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 @@ -631,7 +638,8 @@ jobs: name: app (real browser, ${{ matrix.engine }}) (shard ${{ matrix.shard }} of 3) needs: changes strategy: - # Each engine/shard keeps its own runner and result; failures leave the other legs running. + # 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] @@ -813,13 +821,18 @@ 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.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 "${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: | 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 e34987b75c..385eb5a02d 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"; /** @@ -30,7 +31,8 @@ import { still } from "./page-still"; * * 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 eb8d230f5e..9a64e91bef 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, test } 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"; /** @@ -18,7 +19,8 @@ import { marksPlugin } from "./marks-plugin"; * * 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 4f66e689b0..c9e1cb77a6 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"; /** * The artifacts kit: what a Bot's page is compiled against (app/scripts/build-artifacts-kit.ts). @@ -34,7 +35,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.test.tsx b/app/tests/artifacts-screens.test.tsx index 75ca747e3d..487e5e9451 100644 --- a/app/tests/artifacts-screens.test.tsx +++ b/app/tests/artifacts-screens.test.tsx @@ -20,6 +20,7 @@ import { THUMBNAIL_DARK_SHA, THUMBNAIL_LIGHT_SHA, } from "./artifacts-api"; +import { ownBrowsersAsked } from "./browser-engines"; import { marksPlugin } from "./marks-plugin"; import { still } from "./page-still"; @@ -43,7 +44,8 @@ import { still } from "./page-still"; * --.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. */ -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/board-row-layout.test.tsx b/app/tests/board-row-layout.test.tsx index bc691e4efd..10b75bfe13 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"; /** * A Needs you board row keeps its words readable at every width the board is drawn at. @@ -20,7 +21,8 @@ import { compile } from "tailwindcss"; * 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/browser-engines.test.ts b/app/tests/browser-engines.test.ts index a68423fef3..f105354fd8 100644 --- a/app/tests/browser-engines.test.ts +++ b/app/tests/browser-engines.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from "bun:test"; -import { launchBrowserEngines } from "./browser-engines"; +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 [ @@ -78,3 +80,48 @@ describe("browser engine selection", () => { 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 index 95cfa526b4..d34ae22b62 100644 --- a/app/tests/browser-engines.ts +++ b/app/tests/browser-engines.ts @@ -2,19 +2,43 @@ 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 { - const selected = new Set( - (selection?.trim() || "chromium").split(",").map((engine) => engine.trim()), - ); - for (const engine of selected) { - if (engine !== "chromium" && engine !== "webkit") { - throw new Error(`Unsupported browser engine: ${engine}`); - } + for (const engine of selectedEngines(selection)) { // CI installs full Chromium without the headless shell. const browser = engine === "chromium" diff --git a/app/tests/plan-notices-layout.test.tsx b/app/tests/plan-notices-layout.test.tsx index cb1a399fee..c4f30827f1 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"; /** @@ -17,7 +18,8 @@ import { still } from "./page-still"; * 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 61e7c0b57b..10902c10d1 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(); describe.skipIf(!asked)("a renderer crash in a real-browser test", () => { test("is run again, up to twice; any other failure is not", async () => { diff --git a/app/tests/select-scrolls-layout.test.tsx b/app/tests/select-scrolls-layout.test.tsx index 0c5c780111..651e6b217f 100644 --- a/app/tests/select-scrolls-layout.test.tsx +++ b/app/tests/select-scrolls-layout.test.tsx @@ -10,6 +10,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 { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; /** @@ -31,7 +32,8 @@ import { still } from "./page-still"; * * With OPENBOT_APP_SHOTS= each open select is saved as select-scrolls-arrow-.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(); // 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; diff --git a/app/tests/sidebar-current-row.test.tsx b/app/tests/sidebar-current-row.test.tsx index e0e94cdda7..fd20757b87 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"; /** @@ -29,7 +30,8 @@ import { still } from "./page-still"; * * 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 bef8dd2c79..7333c38475 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, test } 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"; @@ -30,8 +31,8 @@ import { still } from "./page-still"; * * 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"; @@ -372,11 +373,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 a2ede4dadb..074d5e8772 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"; /** * THE BUILT APP LOADS WITH NO TRUSTED TYPES VIOLATION, AND DRAWS MERMAID UNDER THEM. @@ -37,7 +38,8 @@ import { * 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 6d0348c906..5440e61261 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"; /** @@ -16,7 +17,8 @@ import { still } from "./page-still"; * * 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/docs/releasing.md b/docs/releasing.md index 83271dfdb5..1d0de93fe1 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1126,7 +1126,7 @@ A job added to `ci.yml` is covered by it without anybody updating a list. | `format, lint, types` | the ordinary things, across every workspace, and a desktop version that has left the release version | | `API spec` | a bundled spec that is not what its sources bundle to, a broken API convention, a generated client that is not the committed one, or, on a pull request, a breaking change to the API or the live channels | | `native types` | a type error in the `mobile` app, which installs from its own npm lockfile | -| `app (real browser)`, `app (real browser, WebKit)`, `app (real browser, desktop setup window)` | the app and desktop setup window behavior only a real Chromium shows, such as layout, and following the system's light or dark, and dictation's languages in WebKit, the engine the Mac window draws with | +| `app (real browser)`, `app (real browser, Chromium) (shard N of 3)`, `app (real browser, WebKit) (shard N of 3)`, `app (real browser, desktop setup window)` | the app and desktop setup window behavior only a real browser shows, such as layout, and following the system's light or dark, in Chromium and in WebKit, the engine the Mac window draws with: the cross-browser list runs in three shards for each engine, and all six must pass | | `tests` | a decision made wrongly, in isolation | | `python harness (agent-crewai)` and one per harness | a provider-boundary regression in that Python Bot harness | | `compose config` | a Compose file an older Compose cannot read | diff --git a/scripts/ci-budgets.test.ts b/scripts/ci-budgets.test.ts index 11a5c8732d..82def9dbff 100644 --- a/scripts/ci-budgets.test.ts +++ b/scripts/ci-budgets.test.ts @@ -51,6 +51,47 @@ const watch = Bun.YAML.parse( readFileSync(join(WORKFLOWS, "ci-watch.yml"), "utf8"), ) as { on: { workflow_run: { workflows: string[] } } }; +type Leg = Record; + +/** + * A matrix's legs as GitHub builds them: every combination of its arrays, less the `exclude` + * entries, then each `include` entry added to every leg whose values it keeps, or as a leg of its + * own when it keeps none. `include` and `exclude` are lists of legs, not axes. + */ +function legs(matrix: Record | undefined): Leg[] { + const axes = Object.entries(matrix ?? {}).filter( + (entry): entry is [string, unknown[]] => + entry[0] !== "include" && + entry[0] !== "exclude" && + Array.isArray(entry[1]), + ); + const keys = new Set(axes.map(([key]) => key)); + let built: Leg[] = + axes.length === 0 + ? [] + : axes.reduce( + (legsSoFar, [key, values]) => + legsSoFar.flatMap((leg) => + values.map((value) => ({ ...leg, [key]: value })), + ), + [{}], + ); + const matches = (leg: Leg, entry: Leg) => + Object.entries(entry).every(([key, value]) => leg[key] === value); + const excluded = (matrix?.exclude ?? []) as Leg[]; + built = built.filter((leg) => !excluded.some((entry) => matches(leg, entry))); + for (const entry of (matrix?.include ?? []) as Leg[]) { + const kept = built.filter((leg) => + Object.entries(entry).every( + ([key, value]) => !keys.has(key) || leg[key] === value, + ), + ); + if (kept.length > 0) for (const leg of kept) Object.assign(leg, entry); + else built.push({ ...entry }); + } + return built.length > 0 ? built : [{}]; +} + /** * The budget names a job reports under: its matrix expanded where the name uses it, and where a * part of the name is known only once the run starts, the wildcard every leg shares. @@ -58,19 +99,15 @@ const watch = Bun.YAML.parse( function names(id: string, job: Job): string[] { const name = job.name ?? id; if (!name.includes(EXPRESSION)) return [name]; - let expanded = [name]; - let total = 1; - for (const [key, values] of Object.entries(job.strategy?.matrix ?? {})) { - if (!Array.isArray(values)) continue; - total *= values.length; - expanded = expanded.flatMap((value) => - values.map((choice) => - value.replaceAll(`${EXPRESSION} matrix.${key} }}`, String(choice)), - ), - ); - } - expanded = expanded.map((value) => - value.replaceAll(`${EXPRESSION} strategy.job-total }}`, String(total)), + const all = legs(job.strategy?.matrix as Record); + const expanded = all.map((leg) => + Object.entries(leg) + .reduce( + (value, [key, choice]) => + value.replaceAll(`${EXPRESSION} matrix.${key} }}`, String(choice)), + name, + ) + .replaceAll(`${EXPRESSION} strategy.job-total }}`, String(all.length)), ); return [ ...new Set( @@ -79,6 +116,22 @@ function names(id: string, job: Job): string[] { ]; } +describe("a job's matrix legs", () => { + test("include and exclude are lists of legs, not axes", () => { + expect(legs({ shard: [1, 2] })).toEqual([{ shard: 1 }, { shard: 2 }]); + expect( + legs({ os: ["a", "b"], shard: [1, 2], exclude: [{ os: "b", shard: 2 }] }), + ).toHaveLength(3); + // An entry keeping a leg's values extends it; one keeping none is a leg of its own. + expect( + legs({ + shard: [1, 2], + include: [{ shard: 1, big: true }, { shard: 3 }], + }), + ).toEqual([{ shard: 1, big: true }, { shard: 2 }, { shard: 3 }]); + }); +}); + describe("every job has a time limit", () => { for (const file of files) { test(file, () => { diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index e3f96fbfcd..cb5aaef190 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -4,8 +4,8 @@ import { existsSync, mkdirSync, mkdtempSync, - readFileSync, readdirSync, + readFileSync, rmSync, writeFileSync, } from "node:fs"; @@ -21,8 +21,8 @@ import { decideDesktopMainPush, decideMainPush, decideMergeGroup, - isBunTest, isBrowserTest, + isBunTest, isCode, isDocs, isIgnored, @@ -613,7 +613,9 @@ describe("a pull request push", () => { expect(result.run.app_browser_webkit).toBe(true); expect(result.browserTests).toEqual(extra ? [unlisted] : []); expect(result.webkitTests).toEqual(extra ? [unlisted] : []); - expect(result.desktopBrowserTests).toEqual(extra ? [desktop] : []); + // The app changed, so the desktop setup window's job runs its whole file: no second run. + expect(result.run.app_browser).toBe(true); + expect(result.desktopBrowserTests).toEqual([]); expect(result.run.partial).toBe(extra); } }); @@ -1926,6 +1928,19 @@ describe("a merge group", () => { // Without the pull request's run, the WebKit list reads the app change since main's run. expect(decision.run.app_browser_webkit).toBe(true); expect(decision.run.python_harness).toBe(false); + // The summary says why, so a slow fetch is never a silent rerun of what the pull request passed. + const slow = decideMergeGroup( + "ci", + ["app/src/lib/marks.ts"], + groupDeps(APP_PR_HARNESS_MAIN), + { + head: "g", + pr: { labels: [], noHead: "its head could not be fetched: timed out" }, + }, + ); + expect(slow.reasons[0]).toContain( + "The pull request's own runs are not used: its head could not be fetched: timed out.", + ); }); test("runs everything for a pull request labelled full-ci, or one that could not be read", () => { @@ -1990,15 +2005,39 @@ describe("a merge group", () => { }); } - test("queued API and fetch share one deadline rather than starting a timer per command", () => { + test("the queued head's fetch has its own deadline, not what the API call left", () => { const result = actionsDecision({ event: "merge_group", historyBudgetMs: 600, commits: [{ "server/src/main.ts": "changed" }], queue: { delays: { api: 350, fetch: 350 }, + calls: ["api", "fetch", "presence"], + reason: "passed on main or on the pull request", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("a fetch that runs out of its own deadline falls back to main and says so", () => { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 600, + commits: [{ "server/src/main.ts": "changed" }], + queue: { + delays: { fetch: 900 }, calls: ["api", "fetch"], - reason: "passed on main.", + reason: + "The pull request's own runs are not used: its head could not be fetched", }, responses: (sha, commits) => ({ [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 36547ce981..6339a61d4b 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -44,7 +44,9 @@ * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). * CI_HISTORY_BUDGET_MS can shorten the 45000 ms historical-proof deadline (0..45000); each remote * history call is limited to the remaining time or 5000 ms, whichever is less. The optional queued - * PR lookup shares a separate 5000 ms deadline, shortened by the same override (0 skips it). Writes one + * PR lookup's API call has a separate 5000 ms deadline and the fetch of its head 15000 ms, both + * shortened by the same override (0 skips them); a fetch that fails or runs out is named in the + * summary. Writes one * output per job (`true` to run it), the changed tests as JSON arrays, and `queue_run` (the merge * queue's run that stands in for this one, or empty) to $GITHUB_OUTPUT, and what it decided and why * to $GITHUB_STEP_SUMMARY. @@ -755,6 +757,16 @@ function decideSuite( }; if (!run.suite) add(suiteChanges, false); let current: Change[] | undefined; + // A job that runs its full list covers the changed files in that list, whichever rule's changes + // name them: running them again in `tests (changed files)` repeats work (the desktop setup + // window's file alone is 12 minutes). + const runningJobs = Object.entries(BROWSER_JOBS) + .filter(([output]) => run[output]) + .flatMap(([, jobs]) => jobs); + const coveredByRunning = + runningJobs.length > 0 + ? fullBrowserFiles(deps, runningJobs) + : new Set(); for (const output of ["app_browser", "app_browser_webkit"]) { // Without a historical pass, full jobs still cannot cover edited files outside their lists. // Only then fall back to this PR/group's diff; an old PR edit may already have passed later. @@ -767,7 +779,13 @@ function decideSuite( ); changes = current; } - add(changes, true, run[output], output === "app_browser_webkit"); + add( + changes, + true, + run[output], + output === "app_browser_webkit", + coveredByRunning, + ); } // Passing fixed lists prove nothing about files outside them, even when an older passing tree // is restored exactly. Keep those files owed by this PR/group's own diff until they join a list. @@ -814,6 +832,12 @@ function decideSuite( } } +/** The real-browser jobs each browser rule's output runs, by job id in ci.yml. */ +const BROWSER_JOBS: Record = { + app_browser: ["app-browser", "app-browser-desktop"], + app_browser_webkit: ["app-browser-webkit"], +}; + /** Only literal full arrays in the current browser jobs prove file coverage. Unknown is no proof. */ function fullBrowserFiles( deps: Pick, @@ -905,7 +929,10 @@ function fullBrowserFiles( ) ) continue; - for (const path of paths) files.add(path); + // The desktop setup window's job runs from desktop/ (docker's --workdir), so its paths are + // desktop's; the decision names files from the repository root. + const root = id === "app-browser-desktop" ? "desktop/" : ""; + for (const path of paths) files.add(`${root}${path}`); } } return files; @@ -1124,6 +1151,8 @@ export type MergeGroup = { labels: string[]; /** Its head commit when that commit's history was fetched, from this repository only. */ head?: string; + /** Why there is no head, said in the run's summary: a fork, or a fetch that failed or ran out. */ + noHead?: string; }; }; @@ -1257,7 +1286,7 @@ export function decideMergeGroup( decision.reasons.unshift( group.pr?.head ? "A merge group: each job runs unless nothing it reads changed since it passed on main or on the pull request." - : "A merge group: each job runs unless nothing it reads changed since it passed on main.", + : `A merge group: each job runs unless nothing it reads changed since it passed on main. The pull request's own runs are not used${group.pr?.noHead ? `: ${group.pr.noHead}` : ""}.`, ); return { ...decision, ignoredOnly: false }; } @@ -1340,8 +1369,11 @@ export function testedCheckout( return undefined; } -/** One monotonic deadline for optional remote proof commands, with a shorter test override. */ -function historyCommands(maximumMs: number) { +/** + * One monotonic deadline for optional remote proof commands, with a shorter test override. Each + * command gets the remaining time or `perCommandMs`, whichever is less. + */ +function historyCommands(maximumMs: number, perCommandMs = 5_000) { const requested = process.env.CI_HISTORY_BUDGET_MS; const budgetMs = requested !== undefined && /^\d+$/.test(requested) @@ -1352,7 +1384,7 @@ function historyCommands(maximumMs: number) { return { remaining, run: (cmd: string[]) => { - const timeout = Math.min(5_000, remaining()); + const timeout = Math.min(perCommandMs, remaining()); if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); return exec(cmd, undefined, timeout); }, @@ -1615,10 +1647,14 @@ function queuedPull( const labels = (pull.labels ?? []).map((label) => label.name); const ours = pull.head.repo?.full_name?.toLowerCase() === repository.toLowerCase(); - if (!ours || !/^[0-9a-f]{40}$/.test(pull.head.sha)) return { labels }; - // Its commits and trees share the API call's deadline; failed lookups retain readable labels. + if (!ours || !/^[0-9a-f]{40}$/.test(pull.head.sha)) + return { labels, noHead: "it comes from another repository" }; + // Its commits and trees, on a deadline of their own: a fetch slower than the API call's five + // seconds used to drop the pull request's history without a word, and every job it had passed + // ran again in the queue. Failed lookups keep the labels already read. + const { run: fetchCommand } = historyCommands(15_000, 15_000); try { - run([ + fetchCommand([ "git", "fetch", "--no-tags", @@ -1626,10 +1662,13 @@ function queuedPull( "origin", `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`, ]); - run(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]); + fetchCommand(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]); return { labels, head: pull.head.sha }; - } catch { - return { labels }; + } catch (error) { + return { + labels, + noHead: `its head could not be fetched: ${error instanceof Error ? error.message : String(error)}`, + }; } } catch { return undefined; diff --git a/scripts/release-publish-order.test.ts b/scripts/release-publish-order.test.ts index 81ac3c3bf0..50d7e9febf 100644 --- a/scripts/release-publish-order.test.ts +++ b/scripts/release-publish-order.test.ts @@ -238,8 +238,9 @@ test("CI keeps a run for every commit on main, and the release's own checks out `${fork} && format('ci-{0}-forks', github.workflow) || ` + "format('ci-{0}-{1}', github.workflow, github.ref == 'refs/heads/main' && github.sha || github.ref)", ), + // A label other than full-ci waits for the run in progress instead of cancelling it. "cancel-in-progress": expression( - "github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository", + "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')", ), }); }); diff --git a/scripts/workflow-concurrency.test.ts b/scripts/workflow-concurrency.test.ts index 5ae8a243db..ccf1e4e0c7 100644 --- a/scripts/workflow-concurrency.test.ts +++ b/scripts/workflow-concurrency.test.ts @@ -276,7 +276,7 @@ describe("main, a release branch, a tag, a schedule and a manual run are never c }); }); -describe("a label preserves the active run or starts its complete CI replacement", () => { +describe("only full-ci starts a CI replacement; any other label preserves the active run", () => { const labelled = pullRequestWorkflows.filter((file) => triggers(file).pull_request?.types?.includes("labeled"), ); @@ -295,6 +295,16 @@ describe("a label preserves the active run or starts its complete CI replacement concurrency(file, pullRequest(file, 101, "same-push"))?.group, ); expect(concurrency(file, label)?.cancel).toBe(true); + // Any other label (a reviewer's `windows-signing`, a release PR's `release`) waits for the + // run in progress in the same group instead of cancelling it, then finds its checks passed. + const other = pullRequest(file, 101, "same-push", { + action: "labeled", + label: "windows-signing", + }); + expect(concurrency(file, other)?.group).toBe( + concurrency(file, pullRequest(file, 101, "same-push"))?.group, + ); + expect(concurrency(file, other)?.cancel).toBe(false); } else { expect(concurrency(file, label)?.cancel).toBe(false); } From ab2333787bea2e73707c536ac0f63a4d7baad7c2 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 19:54:00 -0800 Subject: [PATCH 18/21] Tests: deal the artifact screens' layout cases over four files artifacts-screens.test.tsx took about 11 minutes in Chromium, nine of them its layout cases, and as one file it set the length of its shard and so of every run. What its describes share moves to artifacts-screens.harness.ts; the flows stay in the file, and the layout cases (each screen in light and dark, wide, narrow and on a phone) are dealt every fourth over artifacts-screens-layout-1..4.test.tsx, so the browser jobs run them side by side. The same 190 tests run; a suite test fails if a layout file goes missing or deals the wrong part. --- app/tests/artifacts-screens-layout-1.test.tsx | 25 + app/tests/artifacts-screens-layout-2.test.tsx | 25 + app/tests/artifacts-screens-layout-3.test.tsx | 25 + app/tests/artifacts-screens-layout-4.test.tsx | 25 + app/tests/artifacts-screens.harness.ts | 768 ++++++++++++++++++ app/tests/artifacts-screens.test.tsx | 761 ++--------------- 6 files changed, 921 insertions(+), 708 deletions(-) create mode 100644 app/tests/artifacts-screens-layout-1.test.tsx create mode 100644 app/tests/artifacts-screens-layout-2.test.tsx create mode 100644 app/tests/artifacts-screens-layout-3.test.tsx create mode 100644 app/tests/artifacts-screens-layout-4.test.tsx create mode 100644 app/tests/artifacts-screens.harness.ts 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 4332a65008..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,8 +13,33 @@ import { THUMBNAIL_DARK_SHA, THUMBNAIL_LIGHT_SHA, } from "./artifacts-api"; +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 { marksPlugin } from "./marks-plugin"; import { still } from "./page-still"; import { test } from "./renderer-crash"; @@ -45,416 +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). */ // 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 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 }, +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", () => { @@ -1468,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({ @@ -1757,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); - } - } -}); From 470354672ea2bf8349a9277c44d0d672c574c470 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 19:54:00 -0800 Subject: [PATCH 19/21] Tests: the desktop setup window's browser tests in three files, run side by side The window's one test file ran its 293 tests one after another for about ten minutes, the longest job of a run. What its describes share moves to setupLayout.browser.harness.ts, the move to OpenBot Cloud (about three minutes) and the approved layouts with the too-old screens (about three) move to files of their own, and the job runs the three with --parallel. The WebKit run of the key field and tab row stays on setupLayout.browser.test.ts. --- .../src/setupLayout.approved.browser.test.ts | 2643 +++++++++++ desktop/src/setupLayout.browser.harness.ts | 310 ++ desktop/src/setupLayout.browser.test.ts | 3854 +---------------- .../setupLayout.moveToCloud.browser.test.ts | 868 ++++ 4 files changed, 3882 insertions(+), 3793 deletions(-) create mode 100644 desktop/src/setupLayout.approved.browser.test.ts create mode 100644 desktop/src/setupLayout.browser.harness.ts create mode 100644 desktop/src/setupLayout.moveToCloud.browser.test.ts 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(".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); - } -}); - /** * The Content Security Policy the shell serves the bundled window with (`app.security.csp`), as * directive name to sources. Tauri adds its own scripts' hashes to `script-src` when it serves the diff --git a/desktop/src/setupLayout.moveToCloud.browser.test.ts b/desktop/src/setupLayout.moveToCloud.browser.test.ts new file mode 100644 index 0000000000..e28493e683 --- /dev/null +++ b/desktop/src/setupLayout.moveToCloud.browser.test.ts @@ -0,0 +1,868 @@ +import { describe, expect, test } from "bun:test"; +import { + asked, + browser, + calls, + cloudBuilt, + open, + type Page, + routeCalendar, + withSetupWindow, +} from "./setupLayout.browser.harness"; + +/** + * The setup window's move to OpenBot Cloud: each of its screens at the window's size, and the move + * due at a relaunch that would update OpenBot. 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.moveToCloud.browser.test.ts + */ +withSetupWindow(); + +/* + * 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. + */ +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, + ), + }; + }); + }; + 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; + }); + 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", +]; + +/** 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); + }, +); From 22c6b70747dfd074c534a5e1954718b6cfd377fe Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 19:54:00 -0800 Subject: [PATCH 20/21] CI: cut the cross-browser shards by each engine's recorded durations `bun test --shard` dealt the sorted list out in turn, so slow files piled up on one runner: on 4 December one WebKit shard took 15.6 minutes and another 9.4. Each engine's shards now read that engine's record (scripts/browser-timings/.json, seeded from the last three runs' WebKit logs) with --timings, so they take about as long as each other and each worker starts its slowest file first. Each shard writes its own durations over the record and uploads them; `bun scripts/browser-timings.ts ` merges them into a fresh record. ci-changes.ts still proves a full job covers its list with the record in its command: a record every shard of an engine reads alike only moves files between shards. One whose path differs by shard is no proof. The desktop setup window's job runs its three files with --parallel. The suite's test helper for `mentions` returns nothing for no paths, as ci-changes.ts does: git took the first pathspec for the pattern, and a comment naming a wildcard test file made a CHANGELOG-only group run tests. CONTRIBUTING says the queue reuses checks that already passed. --- .github/workflows/ci.yml | 32 +++- CONTRIBUTING.md | 5 +- app/tests/select-scrolls-layout.test.tsx | 190 +++++++++++++---------- scripts/browser-timings.test.ts | 122 +++++++++++++++ scripts/browser-timings.ts | 93 +++++++++++ scripts/browser-timings/chromium.json | 147 ++++++++++++++++++ scripts/browser-timings/webkit.json | 147 ++++++++++++++++++ scripts/ci-changes.test.ts | 44 +++++- scripts/ci-changes.ts | 27 ++-- 9 files changed, 700 insertions(+), 107 deletions(-) create mode 100644 scripts/browser-timings.test.ts create mode 100644 scripts/browser-timings.ts create mode 100644 scripts/browser-timings/chromium.json create mode 100644 scripts/browser-timings/webkit.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e042f23667..ff60a19f54 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -682,8 +682,12 @@ 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, ${{ matrix.engine }}) (shard ${{ matrix.shard }} of 3) needs: changes @@ -747,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 @@ -867,7 +875,16 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --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.engine == 'WebKit' && matrix.shard == 1 @@ -884,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 @@ -912,14 +930,16 @@ jobs: # 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 "${files[@]}" + 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: | 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/select-scrolls-layout.test.tsx b/app/tests/select-scrolls-layout.test.tsx index aeb8ad6dbf..1cb4dfc997 100644 --- a/app/tests/select-scrolls-layout.test.tsx +++ b/app/tests/select-scrolls-layout.test.tsx @@ -252,12 +252,15 @@ async function shoot(page: Page, name: string) { } describe.skipIf(!asked)("a select with less room than its options", () => { - 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(); - }); + 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(); + }, + ); inChromium("its scroll-down arrow reaches the last option", async () => { const page = await opened(); @@ -270,42 +273,51 @@ describe.skipIf(!asked)("a select with less room than its options", () => { 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(); - }); + 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(); + }, + ); - 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(); - }); + 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(); + }, + ); - 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(); - }); + 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. @@ -349,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) - 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(); - }); + 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(); + }, + ); - 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(); - }); + 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/scripts/browser-timings.test.ts b/scripts/browser-timings.test.ts new file mode 100644 index 0000000000..cd62b4ae9b --- /dev/null +++ b/scripts/browser-timings.test.ts @@ -0,0 +1,122 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { browserTimingsFile, ENGINES, engineRecord } from "./browser-timings"; +import { WEBKIT_SHARDS } from "./ci-changes"; + +const ROOT = join(import.meta.dir, ".."); + +let folder: string | undefined; +afterEach(() => { + if (folder) rmSync(folder, { recursive: true, force: true }); + folder = undefined; +}); + +/** A run's artifacts as `gh run download` leaves them: what each shard's `--update-timings` wrote. */ +function downloaded(shards: Record>) { + folder = mkdtempSync(join(tmpdir(), "browser-timings-test-")); + for (const [name, files] of Object.entries(shards)) { + const engine = name.split("-")[2] as string; + mkdirSync(join(folder, name)); + // Bun's own --update-timings output, as it writes it. + writeFileSync( + join(folder, name, `${engine}.json`), + JSON.stringify({ version: 1, files }, null, 2), + ); + } + return folder; +} + +describe("refreshing an engine's record from a run", () => { + test("every shard's own files, merged and sorted", () => { + const at = downloaded({ + "browser-timings-webkit-1": { "app/tests/b.test.tsx": 2000 }, + "browser-timings-webkit-2": { + "app/tests/c.test.tsx": 3000, + "app/tests/a.test.tsx": 1000, + }, + "browser-timings-webkit-3": { "app/tests/d.test.tsx": 4000 }, + // Another engine's shards are not this record's. + "browser-timings-chromium-1": { "app/tests/a.test.tsx": 9 }, + }); + expect(JSON.parse(engineRecord(at, "webkit"))).toEqual({ + version: 1, + files: { + "app/tests/a.test.tsx": 1000, + "app/tests/b.test.tsx": 2000, + "app/tests/c.test.tsx": 3000, + "app/tests/d.test.tsx": 4000, + }, + }); + }); + + test("a run missing a shard refreshes nothing: its files would leave the record", () => { + const at = downloaded({ + "browser-timings-chromium-1": { "app/tests/a.test.tsx": 1000 }, + "browser-timings-chromium-3": { "app/tests/c.test.tsx": 3000 }, + }); + expect(() => engineRecord(at, "chromium")).toThrow( + `not one from each of its ${WEBKIT_SHARDS} shards`, + ); + }); +}); + +/** A GitHub Actions expression as ci.yml writes it, `${{ inner }}`. */ +const expression = (inner: string) => `${"$"}{{ ${inner} }}`; + +describe("ci.yml's cross-browser shards", () => { + type Step = { run?: string; uses?: string; with?: Record }; + const job = ( + Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: Record; steps?: Step[] }>; + } + ).jobs["app-browser-webkit"]; + + test("are cut by their engine's record, and each writes and keeps its own", () => { + // Without the record, `--shard` deals the sorted list out in turn, and the slow files pile up + // on one runner: on 4 December one WebKit shard took 15.6 minutes and another 9.4. + const list = job?.steps?.find((step) => step.run?.includes("files=(")); + expect(list?.run).toContain( + '--shard="$TEST_SHARD" --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings', + ); + expect(job?.env?.BROWSER_ENGINE).toBe( + expression("matrix.engine == 'WebKit' && 'webkit' || 'chromium'"), + ); + const upload = job?.steps?.find((step) => + step.uses?.startsWith("actions/upload-artifact@"), + ); + expect(upload?.with?.name).toBe( + `browser-timings-${expression("env.BROWSER_ENGINE")}-${expression("matrix.shard")}`, + ); + expect(upload?.with?.path).toBe( + `scripts/browser-timings/${expression("env.BROWSER_ENGINE")}.json`, + ); + }); + + for (const engine of ENGINES) + test(`${engine}'s record is there, in bun's format`, () => { + const path = join(ROOT, browserTimingsFile(engine)); + expect(existsSync(path)).toBe(true); + const record = JSON.parse(readFileSync(path, "utf8")) as { + version: number; + files: Record; + }; + expect(record.version).toBe(1); + expect(Object.keys(record.files).length).toBeGreaterThan(50); + expect( + Object.values(record.files).every( + (ms) => Number.isInteger(ms) && ms >= 0, + ), + ).toBe(true); + }); +}); diff --git a/scripts/browser-timings.ts b/scripts/browser-timings.ts new file mode 100644 index 0000000000..b2828030bd --- /dev/null +++ b/scripts/browser-timings.ts @@ -0,0 +1,93 @@ +/** + * The cross-browser list's recorded durations, one record per engine + * (scripts/browser-timings/.json), which ci.yml's `app-browser-webkit` shards are cut by + * (`bun test --shard --timings`), so they take about as long as each other. + * + * Every shard writes what its own files took over its engine's record (`--update-timings`) and + * uploads it as `browser-timings--`. To refresh the records from a run: + * + * bun scripts/browser-timings.ts + * + * A file a record does not name counts as the record's median, so a new file needs no entry first; + * refresh when a run's shards drift apart. + */ +import { + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { WEBKIT_SHARDS } from "./ci-changes"; +import { mergeTimings } from "./test-floor"; + +/** The engines the cross-browser list runs in, as OPENBOT_APP_ENGINES names them. */ +export const ENGINES = ["chromium", "webkit"] as const; +export type Engine = (typeof ENGINES)[number]; + +/** Where an engine's record is, from the repository root. */ +export function browserTimingsFile(engine: Engine): string { + return `scripts/browser-timings/${engine}.json`; +} + +/** + * An engine's new record, from its shards' artifacts as `gh run download` leaves them: a folder per + * artifact. Every shard's, or none: one missing would leave its files out of the record. + */ +export function engineRecord(folder: string, engine: Engine): string { + const shards = readdirSync(folder) + .filter((name) => name.startsWith(`browser-timings-${engine}-`)) + .sort(); + const expected = Array.from( + { length: WEBKIT_SHARDS }, + (_, index) => `browser-timings-${engine}-${index + 1}`, + ); + if (JSON.stringify(shards) !== JSON.stringify(expected)) { + throw new Error( + `The run has ${shards.join(", ") || "no"} timings for ${engine}, not one from each of its ${WEBKIT_SHARDS} shards.`, + ); + } + return mergeTimings( + shards.map((name) => + readFileSync(join(folder, name, `${engine}.json`), "utf8"), + ), + ); +} + +if (import.meta.main) { + const run = process.argv[2] ?? ""; + if (!/^\d+$/.test(run)) { + console.error("Usage: bun scripts/browser-timings.ts "); + process.exit(2); + } + const folder = mkdtempSync(join(tmpdir(), "browser-timings-")); + try { + const download = Bun.spawnSync( + [ + "gh", + "run", + "download", + run, + "--pattern", + "browser-timings-*", + "--dir", + folder, + ], + { stdout: "inherit", stderr: "inherit" }, + ); + if (download.exitCode !== 0) + throw new Error(`Could not download run ${run}'s timings.`); + // Both read before either is written, so a run missing a shard changes nothing. + const records = ENGINES.map( + (engine) => [engine, engineRecord(folder, engine)] as const, + ); + for (const [engine, record] of records) { + writeFileSync(browserTimingsFile(engine), record); + console.log(`${browserTimingsFile(engine)}: from run ${run}.`); + } + } finally { + rmSync(folder, { recursive: true, force: true }); + } +} diff --git a/scripts/browser-timings/chromium.json b/scripts/browser-timings/chromium.json new file mode 100644 index 0000000000..33c1b7ec5c --- /dev/null +++ b/scripts/browser-timings/chromium.json @@ -0,0 +1,147 @@ +{ + "version": 1, + "files": { + "app/tests/a2ui-table-links.test.tsx": 3667, + "app/tests/access-requests-layout.test.tsx": 3462, + "app/tests/add-custom-mcp-card-layout.test.tsx": 6000, + "app/tests/admin-notion-one-press-layout.test.tsx": 74505, + "app/tests/admin-path-layout.test.tsx": 74000, + "app/tests/admin-request-notify-layout.test.tsx": 27509, + "app/tests/agent-orb-zoom.test.tsx": 2000, + "app/tests/another-account-layout.test.tsx": 28000, + "app/tests/app-error-reporting-browser.test.ts": 1000, + "app/tests/app-frame-skeleton-still.test.tsx": 71831, + "app/tests/approval-answered-layout.test.tsx": 35667, + "app/tests/approval-card-says-what-and-where.test.tsx": 13217, + "app/tests/approval-left-carry-on-browser.test.tsx": 11667, + "app/tests/approval-rules-layout.test.tsx": 12852, + "app/tests/artifact-bridge-browser.test.ts": 4000, + "app/tests/artifact-collab-browser.test.tsx": 43000, + "app/tests/artifact-error-notice-layout.test.tsx": 4667, + "app/tests/artifact-events-socket.test.ts": 10000, + "app/tests/artifact-kinds-browser.test.tsx": 122333, + "app/tests/artifact-page-storage-browser.test.ts": 1000, + "app/tests/artifact-sharing-screens-layout.test.tsx": 24804, + "app/tests/artifact-sign-in-refusal-browser.test.tsx": 5481, + "app/tests/artifact-tool-cards-browser.test.tsx": 17667, + "app/tests/artifacts-kit.test.ts": 3667, + "app/tests/artifacts-screens-layout-1.test.tsx": 147675, + "app/tests/artifacts-screens-layout-2.test.tsx": 147675, + "app/tests/artifacts-screens-layout-3.test.tsx": 147675, + "app/tests/artifacts-screens-layout-4.test.tsx": 147675, + "app/tests/artifacts-screens.test.tsx": 195000, + "app/tests/board-row-layout.test.tsx": 5333, + "app/tests/boot-screen.test.ts": 17452, + "app/tests/bot-file-links-browser.test.tsx": 11333, + "app/tests/bot-long-instructions-layout.test.tsx": 17183, + "app/tests/bot-owner-lists-layout.test.tsx": 24667, + "app/tests/bot-screen-sharp.test.tsx": 2794, + "app/tests/bots-panel-start-conversation.test.tsx": 9000, + "app/tests/browse-apps-pages.test.tsx": 21509, + "app/tests/browse-steps-layout.test.tsx": 11333, + "app/tests/bug-reports-layout.test.tsx": 15000, + "app/tests/canvas-colour-read.test.tsx": 4333, + "app/tests/carry-on-carried-turn-browser.test.tsx": 30000, + "app/tests/chunk-recovery.test.tsx": 19157, + "app/tests/command-card-layout.test.tsx": 1667, + "app/tests/component-bots-layout.test.tsx": 35156, + "app/tests/composer-dictation-caret.test.tsx": 14000, + "app/tests/composer-dictation-language.test.tsx": 5857, + "app/tests/composer-keeps-draft-browser.test.tsx": 11169, + "app/tests/composer-send-while-dictating.test.tsx": 9028, + "app/tests/composer-touch-return.test.tsx": 27479, + "app/tests/computer-panel-phone-layout.test.tsx": 52667, + "app/tests/computer-starting-browser.test.tsx": 77514, + "app/tests/connected-bot-mistakes-layout.test.tsx": 23333, + "app/tests/conversation-access-ended.test.tsx": 30333, + "app/tests/conversation-allowances-layout.test.tsx": 19817, + "app/tests/conversation-kept-browser.test.tsx": 63667, + "app/tests/conversation-reopen-end.test.tsx": 38490, + "app/tests/conversation-reply-toolbar-layout.test.tsx": 23333, + "app/tests/conversation-resume.test.tsx": 48333, + "app/tests/conversation-return-running.test.tsx": 19667, + "app/tests/conversation-switch.test.tsx": 81667, + "app/tests/delete-account-layout.test.tsx": 143000, + "app/tests/desktop-versions.test.tsx": 29799, + "app/tests/desktop-window-sign-in.test.tsx": 119333, + "app/tests/failed-send-browser.test.tsx": 23847, + "app/tests/finished-run-no-stopped-notice-browser.test.tsx": 212164, + "app/tests/first-message-thinking.test.tsx": 57510, + "app/tests/free-runs-heads-up-layout.test.tsx": 87000, + "app/tests/group-conversation-gutter.test.tsx": 15824, + "app/tests/hand-back-row-layout.test.tsx": 4333, + "app/tests/home-holds-still.test.tsx": 175832, + "app/tests/home-no-answer.test.tsx": 3667, + "app/tests/home-screen-connect-browser.test.tsx": 22844, + "app/tests/long-names-layout.test.tsx": 74034, + "app/tests/long-turn-reopen.test.tsx": 29000, + "app/tests/make-artifact-browser.test.tsx": 18000, + "app/tests/member-rows-long-names.test.tsx": 11190, + "app/tests/model-picker-touch.test.tsx": 2133, + "app/tests/move-to-cloud-settings.test.tsx": 2667, + "app/tests/moved-apps-reconnect.test.tsx": 259487, + "app/tests/moved-elsewhere.test.tsx": 44133, + "app/tests/name-the-admins-layout.test.tsx": 45333, + "app/tests/new-conversation-picked-model.test.tsx": 28822, + "app/tests/offline-conversation-layout.test.tsx": 14000, + "app/tests/older-safari-build.test.ts": 14754, + "app/tests/one-press-connect-layout.test.tsx": 70489, + "app/tests/organization-held-actions.test.tsx": 47000, + "app/tests/organization-held-recovery.test.tsx": 125333, + "app/tests/organization-held-reload.test.tsx": 75333, + "app/tests/organization-members-remove.test.tsx": 6515, + "app/tests/organization-moving.test.tsx": 27347, + "app/tests/organization-removed.test.tsx": 32333, + "app/tests/organization-unavailable-admin-pages.test.tsx": 38333, + "app/tests/organization-unavailable-chat.test.tsx": 167517, + "app/tests/organization-unavailable-pages.test.tsx": 43174, + "app/tests/people-lists.test.tsx": 54000, + "app/tests/plan-notices-layout.test.tsx": 204000, + "app/tests/question-answer-prompt-browser.test.tsx": 15667, + "app/tests/queue-send-now-layout.test.tsx": 13333, + "app/tests/reached-as-the-person-browser.test.tsx": 5667, + "app/tests/reconnecting-line-layout.test.tsx": 12333, + "app/tests/rejoin-fresh-token-browser.test.tsx": 33166, + "app/tests/reload-keeps-answer-browser.test.tsx": 17000, + "app/tests/renderer-crash.test.ts": 11333, + "app/tests/renewal-keeps-typing-browser.test.tsx": 1000, + "app/tests/roster-working.test.tsx": 46667, + "app/tests/routine-run-now-layout.test.tsx": 4494, + "app/tests/run-ended-unheard-layout.test.tsx": 145333, + "app/tests/run-refused-browser.test.tsx": 16333, + "app/tests/section-strip-routines.test.tsx": 13667, + "app/tests/select-long-names-layout.test.tsx": 8333, + "app/tests/select-scrolls-layout.test.tsx": 0, + "app/tests/self-contained-account-menu.test.tsx": 11180, + "app/tests/service-terms.test.tsx": 60000, + "app/tests/settings-tool-cards-admin-layout.test.tsx": 41485, + "app/tests/settings-tool-cards-core.test.tsx": 2133, + "app/tests/settings-tool-cards-personal.test.tsx": 9667, + "app/tests/sidebar-current-row.test.tsx": 30000, + "app/tests/sidebar-window-buttons.test.tsx": 44333, + "app/tests/sidebar-zoom-drag.test.tsx": 19000, + "app/tests/sign-in-app-disconnect-layout.test.tsx": 9150, + "app/tests/sign-in-reconnect-layout.test.tsx": 55000, + "app/tests/sign-in-returns-there.test.tsx": 48000, + "app/tests/sign-in-with-apple-layout.test.tsx": 15667, + "app/tests/slider-look.test.tsx": 11840, + "app/tests/staging-icon-browser.test.ts": 4521, + "app/tests/stay-signed-in-browser.test.tsx": 30000, + "app/tests/step-rows-layout.test.tsx": 51180, + "app/tests/stopped-command-layout.test.tsx": 23494, + "app/tests/stopped-turn-dismiss-browser.test.tsx": 50667, + "app/tests/stopped-turn-return-browser.test.tsx": 121328, + "app/tests/strip-version-layout.test.tsx": 98840, + "app/tests/table-export-browser.test.tsx": 115333, + "app/tests/team-connections-directory-layout.test.tsx": 15667, + "app/tests/too-many-follow-ups.test.tsx": 26502, + "app/tests/transcript-table-end.test.tsx": 19333, + "app/tests/trusted-types-build.test.ts": 16667, + "app/tests/trusted-types.test.ts": 71174, + "app/tests/upload-in-parts-browser.test.tsx": 37667, + "app/tests/web-push-browser.test.tsx": 41667, + "app/tests/what-if-handle-browser.test.tsx": 2857, + "app/tests/work-folded-layout.test.tsx": 26000, + "app/tests/workspace-snapshots-layout.test.tsx": 17333 + } +} diff --git a/scripts/browser-timings/webkit.json b/scripts/browser-timings/webkit.json new file mode 100644 index 0000000000..7e45f771a0 --- /dev/null +++ b/scripts/browser-timings/webkit.json @@ -0,0 +1,147 @@ +{ + "version": 1, + "files": { + "app/tests/a2ui-table-links.test.tsx": 4000, + "app/tests/access-requests-layout.test.tsx": 5538, + "app/tests/add-custom-mcp-card-layout.test.tsx": 9667, + "app/tests/admin-notion-one-press-layout.test.tsx": 79495, + "app/tests/admin-path-layout.test.tsx": 86333, + "app/tests/admin-request-notify-layout.test.tsx": 30824, + "app/tests/agent-orb-zoom.test.tsx": 4000, + "app/tests/another-account-layout.test.tsx": 30667, + "app/tests/app-error-reporting-browser.test.ts": 2000, + "app/tests/app-frame-skeleton-still.test.tsx": 74169, + "app/tests/approval-answered-layout.test.tsx": 43000, + "app/tests/approval-card-says-what-and-where.test.tsx": 17283, + "app/tests/approval-left-carry-on-browser.test.tsx": 12000, + "app/tests/approval-rules-layout.test.tsx": 16148, + "app/tests/artifact-bridge-browser.test.ts": 0, + "app/tests/artifact-collab-browser.test.tsx": 500, + "app/tests/artifact-error-notice-layout.test.tsx": 500, + "app/tests/artifact-events-socket.test.ts": 500, + "app/tests/artifact-kinds-browser.test.tsx": 500, + "app/tests/artifact-page-storage-browser.test.ts": 1000, + "app/tests/artifact-sharing-screens-layout.test.tsx": 35530, + "app/tests/artifact-sign-in-refusal-browser.test.tsx": 6852, + "app/tests/artifact-tool-cards-browser.test.tsx": 21333, + "app/tests/artifacts-kit.test.ts": 500, + "app/tests/artifacts-screens-layout-1.test.tsx": 500, + "app/tests/artifacts-screens-layout-2.test.tsx": 500, + "app/tests/artifacts-screens-layout-3.test.tsx": 500, + "app/tests/artifacts-screens-layout-4.test.tsx": 500, + "app/tests/artifacts-screens.test.tsx": 500, + "app/tests/board-row-layout.test.tsx": 500, + "app/tests/boot-screen.test.ts": 31548, + "app/tests/bot-file-links-browser.test.tsx": 13333, + "app/tests/bot-long-instructions-layout.test.tsx": 20817, + "app/tests/bot-owner-lists-layout.test.tsx": 34333, + "app/tests/bot-screen-sharp.test.tsx": 4540, + "app/tests/bots-panel-start-conversation.test.tsx": 500, + "app/tests/browse-apps-pages.test.tsx": 23825, + "app/tests/browse-steps-layout.test.tsx": 12667, + "app/tests/bug-reports-layout.test.tsx": 18000, + "app/tests/canvas-colour-read.test.tsx": 6667, + "app/tests/carry-on-carried-turn-browser.test.tsx": 32667, + "app/tests/chunk-recovery.test.tsx": 21510, + "app/tests/command-card-layout.test.tsx": 2667, + "app/tests/component-bots-layout.test.tsx": 40178, + "app/tests/composer-dictation-caret.test.tsx": 10000, + "app/tests/composer-dictation-language.test.tsx": 7810, + "app/tests/composer-keeps-draft-browser.test.tsx": 11498, + "app/tests/composer-send-while-dictating.test.tsx": 7639, + "app/tests/composer-touch-return.test.tsx": 35521, + "app/tests/computer-panel-phone-layout.test.tsx": 56333, + "app/tests/computer-starting-browser.test.tsx": 91486, + "app/tests/connected-bot-mistakes-layout.test.tsx": 25667, + "app/tests/conversation-access-ended.test.tsx": 33667, + "app/tests/conversation-allowances-layout.test.tsx": 24183, + "app/tests/conversation-kept-browser.test.tsx": 59333, + "app/tests/conversation-reopen-end.test.tsx": 43176, + "app/tests/conversation-reply-toolbar-layout.test.tsx": 26667, + "app/tests/conversation-resume.test.tsx": 51000, + "app/tests/conversation-return-running.test.tsx": 19000, + "app/tests/conversation-switch.test.tsx": 81333, + "app/tests/delete-account-layout.test.tsx": 169000, + "app/tests/desktop-versions.test.tsx": 45535, + "app/tests/desktop-window-sign-in.test.tsx": 129667, + "app/tests/failed-send-browser.test.tsx": 28153, + "app/tests/finished-run-no-stopped-notice-browser.test.tsx": 206502, + "app/tests/first-message-thinking.test.tsx": 50823, + "app/tests/free-runs-heads-up-layout.test.tsx": 121333, + "app/tests/group-conversation-gutter.test.tsx": 14176, + "app/tests/hand-back-row-layout.test.tsx": 6667, + "app/tests/home-holds-still.test.tsx": 178168, + "app/tests/home-no-answer.test.tsx": 4667, + "app/tests/home-screen-connect-browser.test.tsx": 25823, + "app/tests/long-names-layout.test.tsx": 90966, + "app/tests/long-turn-reopen.test.tsx": 71333, + "app/tests/make-artifact-browser.test.tsx": 22000, + "app/tests/member-rows-long-names.test.tsx": 14810, + "app/tests/model-picker-touch.test.tsx": 3200, + "app/tests/move-to-cloud-settings.test.tsx": 6000, + "app/tests/moved-apps-reconnect.test.tsx": 303846, + "app/tests/moved-elsewhere.test.tsx": 47867, + "app/tests/name-the-admins-layout.test.tsx": 52333, + "app/tests/new-conversation-picked-model.test.tsx": 33178, + "app/tests/offline-conversation-layout.test.tsx": 16333, + "app/tests/older-safari-build.test.ts": 18579, + "app/tests/one-press-connect-layout.test.tsx": 80511, + "app/tests/organization-held-actions.test.tsx": 53000, + "app/tests/organization-held-recovery.test.tsx": 124667, + "app/tests/organization-held-reload.test.tsx": 80333, + "app/tests/organization-members-remove.test.tsx": 7818, + "app/tests/organization-moving.test.tsx": 29653, + "app/tests/organization-removed.test.tsx": 38333, + "app/tests/organization-unavailable-admin-pages.test.tsx": 44333, + "app/tests/organization-unavailable-chat.test.tsx": 205816, + "app/tests/organization-unavailable-pages.test.tsx": 47159, + "app/tests/people-lists.test.tsx": 67333, + "app/tests/plan-notices-layout.test.tsx": 500, + "app/tests/question-answer-prompt-browser.test.tsx": 15000, + "app/tests/queue-send-now-layout.test.tsx": 15000, + "app/tests/reached-as-the-person-browser.test.tsx": 7000, + "app/tests/reconnecting-line-layout.test.tsx": 15000, + "app/tests/rejoin-fresh-token-browser.test.tsx": 32834, + "app/tests/reload-keeps-answer-browser.test.tsx": 13667, + "app/tests/renderer-crash.test.ts": 500, + "app/tests/renewal-keeps-typing-browser.test.tsx": 1000, + "app/tests/roster-working.test.tsx": 500, + "app/tests/routine-run-now-layout.test.tsx": 4173, + "app/tests/run-ended-unheard-layout.test.tsx": 149333, + "app/tests/run-refused-browser.test.tsx": 21667, + "app/tests/section-strip-routines.test.tsx": 500, + "app/tests/select-long-names-layout.test.tsx": 11000, + "app/tests/select-scrolls-layout.test.tsx": 19000, + "app/tests/self-contained-account-menu.test.tsx": 13153, + "app/tests/service-terms.test.tsx": 71333, + "app/tests/settings-tool-cards-admin-layout.test.tsx": 49849, + "app/tests/settings-tool-cards-core.test.tsx": 3200, + "app/tests/settings-tool-cards-personal.test.tsx": 13000, + "app/tests/sidebar-current-row.test.tsx": 35667, + "app/tests/sidebar-window-buttons.test.tsx": 500, + "app/tests/sidebar-zoom-drag.test.tsx": 500, + "app/tests/sign-in-app-disconnect-layout.test.tsx": 11183, + "app/tests/sign-in-reconnect-layout.test.tsx": 62000, + "app/tests/sign-in-returns-there.test.tsx": 43000, + "app/tests/sign-in-with-apple-layout.test.tsx": 18000, + "app/tests/slider-look.test.tsx": 12827, + "app/tests/staging-icon-browser.test.ts": 5812, + "app/tests/stay-signed-in-browser.test.tsx": 27333, + "app/tests/step-rows-layout.test.tsx": 59820, + "app/tests/stopped-command-layout.test.tsx": 25172, + "app/tests/stopped-turn-dismiss-browser.test.tsx": 55333, + "app/tests/stopped-turn-return-browser.test.tsx": 125339, + "app/tests/strip-version-layout.test.tsx": 107160, + "app/tests/table-export-browser.test.tsx": 125333, + "app/tests/team-connections-directory-layout.test.tsx": 18667, + "app/tests/too-many-follow-ups.test.tsx": 27165, + "app/tests/transcript-table-end.test.tsx": 22667, + "app/tests/trusted-types-build.test.ts": 500, + "app/tests/trusted-types.test.ts": 64826, + "app/tests/upload-in-parts-browser.test.tsx": 10333, + "app/tests/web-push-browser.test.tsx": 37333, + "app/tests/what-if-handle-browser.test.tsx": 3810, + "app/tests/work-folded-layout.test.tsx": 32000, + "app/tests/workspace-snapshots-layout.test.tsx": 500 + } +} diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 4dd361adfb..b562ad2760 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -107,6 +107,8 @@ const UNREAD_DOCS = [ /** The suite's tests that name any of these paths, found the way ci-changes.ts finds them. */ function realMentions(paths: string[]): string[] { + // As ci-changes.ts does: with no path, git would take the first pathspec for the pattern. + if (paths.length === 0) return []; const out = Bun.spawnSync( [ "git", @@ -633,6 +635,21 @@ describe("a pull request push", () => { }; const cases = [ [job, true], + // Shards cut by the engine's recorded durations still add up to the whole list. + [ + { + ...job, + steps: [ + { + run: run.replace( + '--shard="$TEST_SHARD"', + '--shard="$TEST_SHARD" --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings', + ), + }, + ], + }, + true, + ], [ { ...job, @@ -755,6 +772,29 @@ describe("a pull request push", () => { [array.replace("bun test", "bun test --test-name-pattern=one"), false], [array.replace("--parallel", "--parallel --shard=1/2"), false], [array.replace("--parallel", "--parallel --unknown"), false], + // Recorded durations every shard of an engine reads alike only move files between shards. + [ + array.replace( + "--parallel", + '--parallel --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings', + ), + true, + ], + [ + array.replace( + "--parallel", + "--parallel --timings=scripts/browser-timings/chromium.json", + ), + true, + ], + // A record that differs from shard to shard can deal a file to none of them. + [ + array.replace( + "--parallel", + '--parallel --timings="$RUNNER_TEMP/$TEST_SHARD.json"', + ), + false, + ], [array.replace(file, "$FILE"), false], [`# ${file}\nbun test app/tests/another.browser.test.ts`, false], ] as const) { @@ -3116,7 +3156,9 @@ describe("the rules name the jobs the workflows run", () => { "matrix.engine == 'WebKit' && matrix.shard == 1", ); const full = job.steps.find((step) => step.run?.includes(`"\${files[@]}"`)); - expect(full?.run).toContain(`--shard="$TEST_SHARD" "\${files[@]}"`); + expect(full?.run).toContain( + `--shard="$TEST_SHARD" --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings "\${files[@]}"`, + ); expect(full?.run).toContain('OPENBOT_APP_ENGINES="$BROWSER_ENGINE"'); }); test("ci.yml: every check a rule waits on is a job, and the shards are the matrix's", () => { diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 9814e0ae5a..c51a427599 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -890,18 +890,21 @@ function fullBrowserFiles( words[0] === "bun" && words[1] === "test" && words.at(-1) === `"\${files[@]}"` && - words - .slice(2, -1) - .every( - (flag) => - /^--parallel(?:=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*"))?$/.test( - flag, - ) || - /^--timeout=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*")$/.test( - flag, - ) || - (completeShards && flag === '--shard="$TEST_SHARD"'), - ) + words.slice(2, -1).every( + (flag) => + /^--parallel(?:=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*"))?$/.test( + flag, + ) || + /^--timeout=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*")$/.test(flag) || + (completeShards && flag === '--shard="$TEST_SHARD"') || + // Recorded durations move a file between shards, never out of them, as long + // as every shard of an engine reads the same record: a fixed path, or one named + // by the engine alone. The run writes its own durations over it after. + /^--timings=(?:[\w./-]+|"[\w./-]*\$BROWSER_ENGINE[\w./-]*")$/.test( + flag, + ) || + flag === "--update-timings", + ) ); }) ) From ee34942a3f5c238058cd99bcd39c46b59768c74b Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 20:04:21 -0800 Subject: [PATCH 21/21] CI: browser timing records measured by each engine's own shards Refreshed with scripts/browser-timings.ts from this branch's first run (47475884691), where each engine ran in its own legs: the seed split each file's time by its tests' names. --- scripts/browser-timings/chromium.json | 284 +++++++++++++------------- scripts/browser-timings/webkit.json | 284 +++++++++++++------------- 2 files changed, 284 insertions(+), 284 deletions(-) diff --git a/scripts/browser-timings/chromium.json b/scripts/browser-timings/chromium.json index 33c1b7ec5c..e2e6f49d3a 100644 --- a/scripts/browser-timings/chromium.json +++ b/scripts/browser-timings/chromium.json @@ -1,147 +1,147 @@ { "version": 1, "files": { - "app/tests/a2ui-table-links.test.tsx": 3667, - "app/tests/access-requests-layout.test.tsx": 3462, - "app/tests/add-custom-mcp-card-layout.test.tsx": 6000, - "app/tests/admin-notion-one-press-layout.test.tsx": 74505, - "app/tests/admin-path-layout.test.tsx": 74000, - "app/tests/admin-request-notify-layout.test.tsx": 27509, - "app/tests/agent-orb-zoom.test.tsx": 2000, - "app/tests/another-account-layout.test.tsx": 28000, - "app/tests/app-error-reporting-browser.test.ts": 1000, - "app/tests/app-frame-skeleton-still.test.tsx": 71831, - "app/tests/approval-answered-layout.test.tsx": 35667, - "app/tests/approval-card-says-what-and-where.test.tsx": 13217, - "app/tests/approval-left-carry-on-browser.test.tsx": 11667, - "app/tests/approval-rules-layout.test.tsx": 12852, - "app/tests/artifact-bridge-browser.test.ts": 4000, - "app/tests/artifact-collab-browser.test.tsx": 43000, - "app/tests/artifact-error-notice-layout.test.tsx": 4667, - "app/tests/artifact-events-socket.test.ts": 10000, - "app/tests/artifact-kinds-browser.test.tsx": 122333, - "app/tests/artifact-page-storage-browser.test.ts": 1000, - "app/tests/artifact-sharing-screens-layout.test.tsx": 24804, - "app/tests/artifact-sign-in-refusal-browser.test.tsx": 5481, - "app/tests/artifact-tool-cards-browser.test.tsx": 17667, - "app/tests/artifacts-kit.test.ts": 3667, - "app/tests/artifacts-screens-layout-1.test.tsx": 147675, - "app/tests/artifacts-screens-layout-2.test.tsx": 147675, - "app/tests/artifacts-screens-layout-3.test.tsx": 147675, - "app/tests/artifacts-screens-layout-4.test.tsx": 147675, - "app/tests/artifacts-screens.test.tsx": 195000, - "app/tests/board-row-layout.test.tsx": 5333, - "app/tests/boot-screen.test.ts": 17452, - "app/tests/bot-file-links-browser.test.tsx": 11333, - "app/tests/bot-long-instructions-layout.test.tsx": 17183, - "app/tests/bot-owner-lists-layout.test.tsx": 24667, - "app/tests/bot-screen-sharp.test.tsx": 2794, - "app/tests/bots-panel-start-conversation.test.tsx": 9000, - "app/tests/browse-apps-pages.test.tsx": 21509, - "app/tests/browse-steps-layout.test.tsx": 11333, - "app/tests/bug-reports-layout.test.tsx": 15000, - "app/tests/canvas-colour-read.test.tsx": 4333, - "app/tests/carry-on-carried-turn-browser.test.tsx": 30000, - "app/tests/chunk-recovery.test.tsx": 19157, - "app/tests/command-card-layout.test.tsx": 1667, - "app/tests/component-bots-layout.test.tsx": 35156, - "app/tests/composer-dictation-caret.test.tsx": 14000, - "app/tests/composer-dictation-language.test.tsx": 5857, - "app/tests/composer-keeps-draft-browser.test.tsx": 11169, - "app/tests/composer-send-while-dictating.test.tsx": 9028, - "app/tests/composer-touch-return.test.tsx": 27479, - "app/tests/computer-panel-phone-layout.test.tsx": 52667, - "app/tests/computer-starting-browser.test.tsx": 77514, - "app/tests/connected-bot-mistakes-layout.test.tsx": 23333, - "app/tests/conversation-access-ended.test.tsx": 30333, - "app/tests/conversation-allowances-layout.test.tsx": 19817, - "app/tests/conversation-kept-browser.test.tsx": 63667, - "app/tests/conversation-reopen-end.test.tsx": 38490, - "app/tests/conversation-reply-toolbar-layout.test.tsx": 23333, - "app/tests/conversation-resume.test.tsx": 48333, - "app/tests/conversation-return-running.test.tsx": 19667, - "app/tests/conversation-switch.test.tsx": 81667, - "app/tests/delete-account-layout.test.tsx": 143000, - "app/tests/desktop-versions.test.tsx": 29799, - "app/tests/desktop-window-sign-in.test.tsx": 119333, - "app/tests/failed-send-browser.test.tsx": 23847, - "app/tests/finished-run-no-stopped-notice-browser.test.tsx": 212164, - "app/tests/first-message-thinking.test.tsx": 57510, - "app/tests/free-runs-heads-up-layout.test.tsx": 87000, - "app/tests/group-conversation-gutter.test.tsx": 15824, - "app/tests/hand-back-row-layout.test.tsx": 4333, - "app/tests/home-holds-still.test.tsx": 175832, - "app/tests/home-no-answer.test.tsx": 3667, - "app/tests/home-screen-connect-browser.test.tsx": 22844, - "app/tests/long-names-layout.test.tsx": 74034, - "app/tests/long-turn-reopen.test.tsx": 29000, - "app/tests/make-artifact-browser.test.tsx": 18000, - "app/tests/member-rows-long-names.test.tsx": 11190, - "app/tests/model-picker-touch.test.tsx": 2133, - "app/tests/move-to-cloud-settings.test.tsx": 2667, - "app/tests/moved-apps-reconnect.test.tsx": 259487, - "app/tests/moved-elsewhere.test.tsx": 44133, - "app/tests/name-the-admins-layout.test.tsx": 45333, - "app/tests/new-conversation-picked-model.test.tsx": 28822, - "app/tests/offline-conversation-layout.test.tsx": 14000, - "app/tests/older-safari-build.test.ts": 14754, - "app/tests/one-press-connect-layout.test.tsx": 70489, - "app/tests/organization-held-actions.test.tsx": 47000, - "app/tests/organization-held-recovery.test.tsx": 125333, - "app/tests/organization-held-reload.test.tsx": 75333, - "app/tests/organization-members-remove.test.tsx": 6515, - "app/tests/organization-moving.test.tsx": 27347, - "app/tests/organization-removed.test.tsx": 32333, - "app/tests/organization-unavailable-admin-pages.test.tsx": 38333, - "app/tests/organization-unavailable-chat.test.tsx": 167517, - "app/tests/organization-unavailable-pages.test.tsx": 43174, - "app/tests/people-lists.test.tsx": 54000, - "app/tests/plan-notices-layout.test.tsx": 204000, - "app/tests/question-answer-prompt-browser.test.tsx": 15667, - "app/tests/queue-send-now-layout.test.tsx": 13333, - "app/tests/reached-as-the-person-browser.test.tsx": 5667, - "app/tests/reconnecting-line-layout.test.tsx": 12333, - "app/tests/rejoin-fresh-token-browser.test.tsx": 33166, - "app/tests/reload-keeps-answer-browser.test.tsx": 17000, - "app/tests/renderer-crash.test.ts": 11333, - "app/tests/renewal-keeps-typing-browser.test.tsx": 1000, - "app/tests/roster-working.test.tsx": 46667, - "app/tests/routine-run-now-layout.test.tsx": 4494, - "app/tests/run-ended-unheard-layout.test.tsx": 145333, - "app/tests/run-refused-browser.test.tsx": 16333, - "app/tests/section-strip-routines.test.tsx": 13667, - "app/tests/select-long-names-layout.test.tsx": 8333, - "app/tests/select-scrolls-layout.test.tsx": 0, - "app/tests/self-contained-account-menu.test.tsx": 11180, - "app/tests/service-terms.test.tsx": 60000, - "app/tests/settings-tool-cards-admin-layout.test.tsx": 41485, - "app/tests/settings-tool-cards-core.test.tsx": 2133, - "app/tests/settings-tool-cards-personal.test.tsx": 9667, - "app/tests/sidebar-current-row.test.tsx": 30000, - "app/tests/sidebar-window-buttons.test.tsx": 44333, - "app/tests/sidebar-zoom-drag.test.tsx": 19000, - "app/tests/sign-in-app-disconnect-layout.test.tsx": 9150, - "app/tests/sign-in-reconnect-layout.test.tsx": 55000, - "app/tests/sign-in-returns-there.test.tsx": 48000, - "app/tests/sign-in-with-apple-layout.test.tsx": 15667, - "app/tests/slider-look.test.tsx": 11840, - "app/tests/staging-icon-browser.test.ts": 4521, - "app/tests/stay-signed-in-browser.test.tsx": 30000, - "app/tests/step-rows-layout.test.tsx": 51180, - "app/tests/stopped-command-layout.test.tsx": 23494, - "app/tests/stopped-turn-dismiss-browser.test.tsx": 50667, - "app/tests/stopped-turn-return-browser.test.tsx": 121328, - "app/tests/strip-version-layout.test.tsx": 98840, - "app/tests/table-export-browser.test.tsx": 115333, - "app/tests/team-connections-directory-layout.test.tsx": 15667, - "app/tests/too-many-follow-ups.test.tsx": 26502, - "app/tests/transcript-table-end.test.tsx": 19333, - "app/tests/trusted-types-build.test.ts": 16667, - "app/tests/trusted-types.test.ts": 71174, - "app/tests/upload-in-parts-browser.test.tsx": 37667, - "app/tests/web-push-browser.test.tsx": 41667, - "app/tests/what-if-handle-browser.test.tsx": 2857, - "app/tests/work-folded-layout.test.tsx": 26000, - "app/tests/workspace-snapshots-layout.test.tsx": 17333 + "app/tests/a2ui-table-links.test.tsx": 4315, + "app/tests/access-requests-layout.test.tsx": 4423, + "app/tests/add-custom-mcp-card-layout.test.tsx": 6176, + "app/tests/admin-notion-one-press-layout.test.tsx": 86146, + "app/tests/admin-path-layout.test.tsx": 76594, + "app/tests/admin-request-notify-layout.test.tsx": 27596, + "app/tests/agent-orb-zoom.test.tsx": 2690, + "app/tests/another-account-layout.test.tsx": 30104, + "app/tests/app-error-reporting-browser.test.ts": 2335, + "app/tests/app-frame-skeleton-still.test.tsx": 89896, + "app/tests/approval-answered-layout.test.tsx": 37587, + "app/tests/approval-card-says-what-and-where.test.tsx": 13905, + "app/tests/approval-left-carry-on-browser.test.tsx": 14067, + "app/tests/approval-rules-layout.test.tsx": 14169, + "app/tests/artifact-bridge-browser.test.ts": 4696, + "app/tests/artifact-collab-browser.test.tsx": 63143, + "app/tests/artifact-error-notice-layout.test.tsx": 5207, + "app/tests/artifact-events-socket.test.ts": 10138, + "app/tests/artifact-kinds-browser.test.tsx": 127495, + "app/tests/artifact-page-storage-browser.test.ts": 1209, + "app/tests/artifact-sharing-screens-layout.test.tsx": 24351, + "app/tests/artifact-sign-in-refusal-browser.test.tsx": 6872, + "app/tests/artifact-tool-cards-browser.test.tsx": 19178, + "app/tests/artifacts-kit.test.ts": 4165, + "app/tests/artifacts-screens-layout-1.test.tsx": 172803, + "app/tests/artifacts-screens-layout-2.test.tsx": 172352, + "app/tests/artifacts-screens-layout-3.test.tsx": 154344, + "app/tests/artifacts-screens-layout-4.test.tsx": 172579, + "app/tests/artifacts-screens.test.tsx": 193082, + "app/tests/board-row-layout.test.tsx": 7420, + "app/tests/boot-screen.test.ts": 16454, + "app/tests/bot-file-links-browser.test.tsx": 14087, + "app/tests/bot-long-instructions-layout.test.tsx": 18864, + "app/tests/bot-owner-lists-layout.test.tsx": 25354, + "app/tests/bot-screen-sharp.test.tsx": 3940, + "app/tests/bots-panel-start-conversation.test.tsx": 4579, + "app/tests/browse-apps-pages.test.tsx": 22447, + "app/tests/browse-steps-layout.test.tsx": 13043, + "app/tests/bug-reports-layout.test.tsx": 15552, + "app/tests/canvas-colour-read.test.tsx": 4655, + "app/tests/carry-on-carried-turn-browser.test.tsx": 33876, + "app/tests/chunk-recovery.test.tsx": 20567, + "app/tests/command-card-layout.test.tsx": 2402, + "app/tests/component-bots-layout.test.tsx": 39279, + "app/tests/composer-dictation-caret.test.tsx": 14463, + "app/tests/composer-dictation-language.test.tsx": 7363, + "app/tests/composer-keeps-draft-browser.test.tsx": 13690, + "app/tests/composer-send-while-dictating.test.tsx": 10365, + "app/tests/composer-touch-return.test.tsx": 27086, + "app/tests/computer-panel-phone-layout.test.tsx": 60074, + "app/tests/computer-starting-browser.test.tsx": 99809, + "app/tests/connected-bot-mistakes-layout.test.tsx": 26429, + "app/tests/conversation-access-ended.test.tsx": 34466, + "app/tests/conversation-allowances-layout.test.tsx": 21119, + "app/tests/conversation-kept-browser.test.tsx": 63960, + "app/tests/conversation-reopen-end.test.tsx": 49005, + "app/tests/conversation-reply-toolbar-layout.test.tsx": 27441, + "app/tests/conversation-resume.test.tsx": 52467, + "app/tests/conversation-return-running.test.tsx": 21959, + "app/tests/conversation-switch.test.tsx": 88336, + "app/tests/delete-account-layout.test.tsx": 149854, + "app/tests/desktop-versions.test.tsx": 36840, + "app/tests/desktop-window-sign-in.test.tsx": 137485, + "app/tests/failed-send-browser.test.tsx": 25407, + "app/tests/finished-run-no-stopped-notice-browser.test.tsx": 220448, + "app/tests/first-message-thinking.test.tsx": 65677, + "app/tests/free-runs-heads-up-layout.test.tsx": 91393, + "app/tests/group-conversation-gutter.test.tsx": 20123, + "app/tests/hand-back-row-layout.test.tsx": 5267, + "app/tests/home-holds-still.test.tsx": 200574, + "app/tests/home-no-answer.test.tsx": 5539, + "app/tests/home-screen-connect-browser.test.tsx": 25496, + "app/tests/long-names-layout.test.tsx": 79788, + "app/tests/long-turn-reopen.test.tsx": 58613, + "app/tests/make-artifact-browser.test.tsx": 22395, + "app/tests/member-rows-long-names.test.tsx": 11232, + "app/tests/model-picker-touch.test.tsx": 3637, + "app/tests/move-to-cloud-settings.test.tsx": 3528, + "app/tests/moved-apps-reconnect.test.tsx": 291551, + "app/tests/moved-elsewhere.test.tsx": 48835, + "app/tests/name-the-admins-layout.test.tsx": 48339, + "app/tests/new-conversation-picked-model.test.tsx": 34314, + "app/tests/offline-conversation-layout.test.tsx": 17738, + "app/tests/older-safari-build.test.ts": 82624, + "app/tests/one-press-connect-layout.test.tsx": 73691, + "app/tests/organization-held-actions.test.tsx": 58649, + "app/tests/organization-held-recovery.test.tsx": 133454, + "app/tests/organization-held-reload.test.tsx": 86049, + "app/tests/organization-members-remove.test.tsx": 7460, + "app/tests/organization-moving.test.tsx": 29238, + "app/tests/organization-removed.test.tsx": 35590, + "app/tests/organization-unavailable-admin-pages.test.tsx": 39708, + "app/tests/organization-unavailable-chat.test.tsx": 148278, + "app/tests/organization-unavailable-pages.test.tsx": 40928, + "app/tests/people-lists.test.tsx": 56488, + "app/tests/plan-notices-layout.test.tsx": 210618, + "app/tests/question-answer-prompt-browser.test.tsx": 15506, + "app/tests/queue-send-now-layout.test.tsx": 14386, + "app/tests/reached-as-the-person-browser.test.tsx": 6437, + "app/tests/reconnecting-line-layout.test.tsx": 13048, + "app/tests/rejoin-fresh-token-browser.test.tsx": 34556, + "app/tests/reload-keeps-answer-browser.test.tsx": 16057, + "app/tests/renderer-crash.test.ts": 10246, + "app/tests/renewal-keeps-typing-browser.test.tsx": 1564, + "app/tests/roster-working.test.tsx": 22979, + "app/tests/routine-run-now-layout.test.tsx": 4681, + "app/tests/run-ended-unheard-layout.test.tsx": 145570, + "app/tests/run-refused-browser.test.tsx": 15070, + "app/tests/section-strip-routines.test.tsx": 3600, + "app/tests/select-long-names-layout.test.tsx": 9377, + "app/tests/select-scrolls-layout.test.tsx": 8841, + "app/tests/self-contained-account-menu.test.tsx": 11546, + "app/tests/service-terms.test.tsx": 65744, + "app/tests/settings-tool-cards-admin-layout.test.tsx": 33747, + "app/tests/settings-tool-cards-core.test.tsx": 2784, + "app/tests/settings-tool-cards-personal.test.tsx": 11812, + "app/tests/sidebar-current-row.test.tsx": 63967, + "app/tests/sidebar-window-buttons.test.tsx": 14043, + "app/tests/sidebar-zoom-drag.test.tsx": 10789, + "app/tests/sign-in-app-disconnect-layout.test.tsx": 9179, + "app/tests/sign-in-reconnect-layout.test.tsx": 52348, + "app/tests/sign-in-returns-there.test.tsx": 50244, + "app/tests/sign-in-with-apple-layout.test.tsx": 14498, + "app/tests/slider-look.test.tsx": 11981, + "app/tests/staging-icon-browser.test.ts": 54119, + "app/tests/stay-signed-in-browser.test.tsx": 29059, + "app/tests/step-rows-layout.test.tsx": 40675, + "app/tests/stopped-command-layout.test.tsx": 26134, + "app/tests/stopped-turn-dismiss-browser.test.tsx": 41255, + "app/tests/stopped-turn-return-browser.test.tsx": 118795, + "app/tests/strip-version-layout.test.tsx": 103223, + "app/tests/table-export-browser.test.tsx": 156181, + "app/tests/team-connections-directory-layout.test.tsx": 14572, + "app/tests/too-many-follow-ups.test.tsx": 27930, + "app/tests/transcript-table-end.test.tsx": 23314, + "app/tests/trusted-types-build.test.ts": 69132, + "app/tests/trusted-types.test.ts": 77113, + "app/tests/upload-in-parts-browser.test.tsx": 34353, + "app/tests/web-push-browser.test.tsx": 36002, + "app/tests/what-if-handle-browser.test.tsx": 4006, + "app/tests/work-folded-layout.test.tsx": 23802, + "app/tests/workspace-snapshots-layout.test.tsx": 16012 } } diff --git a/scripts/browser-timings/webkit.json b/scripts/browser-timings/webkit.json index 7e45f771a0..9c50b4fa28 100644 --- a/scripts/browser-timings/webkit.json +++ b/scripts/browser-timings/webkit.json @@ -1,147 +1,147 @@ { "version": 1, "files": { - "app/tests/a2ui-table-links.test.tsx": 4000, - "app/tests/access-requests-layout.test.tsx": 5538, - "app/tests/add-custom-mcp-card-layout.test.tsx": 9667, - "app/tests/admin-notion-one-press-layout.test.tsx": 79495, - "app/tests/admin-path-layout.test.tsx": 86333, - "app/tests/admin-request-notify-layout.test.tsx": 30824, - "app/tests/agent-orb-zoom.test.tsx": 4000, - "app/tests/another-account-layout.test.tsx": 30667, - "app/tests/app-error-reporting-browser.test.ts": 2000, - "app/tests/app-frame-skeleton-still.test.tsx": 74169, - "app/tests/approval-answered-layout.test.tsx": 43000, - "app/tests/approval-card-says-what-and-where.test.tsx": 17283, - "app/tests/approval-left-carry-on-browser.test.tsx": 12000, - "app/tests/approval-rules-layout.test.tsx": 16148, - "app/tests/artifact-bridge-browser.test.ts": 0, - "app/tests/artifact-collab-browser.test.tsx": 500, - "app/tests/artifact-error-notice-layout.test.tsx": 500, - "app/tests/artifact-events-socket.test.ts": 500, - "app/tests/artifact-kinds-browser.test.tsx": 500, - "app/tests/artifact-page-storage-browser.test.ts": 1000, - "app/tests/artifact-sharing-screens-layout.test.tsx": 35530, - "app/tests/artifact-sign-in-refusal-browser.test.tsx": 6852, - "app/tests/artifact-tool-cards-browser.test.tsx": 21333, - "app/tests/artifacts-kit.test.ts": 500, - "app/tests/artifacts-screens-layout-1.test.tsx": 500, - "app/tests/artifacts-screens-layout-2.test.tsx": 500, - "app/tests/artifacts-screens-layout-3.test.tsx": 500, - "app/tests/artifacts-screens-layout-4.test.tsx": 500, - "app/tests/artifacts-screens.test.tsx": 500, - "app/tests/board-row-layout.test.tsx": 500, - "app/tests/boot-screen.test.ts": 31548, - "app/tests/bot-file-links-browser.test.tsx": 13333, - "app/tests/bot-long-instructions-layout.test.tsx": 20817, - "app/tests/bot-owner-lists-layout.test.tsx": 34333, - "app/tests/bot-screen-sharp.test.tsx": 4540, - "app/tests/bots-panel-start-conversation.test.tsx": 500, - "app/tests/browse-apps-pages.test.tsx": 23825, - "app/tests/browse-steps-layout.test.tsx": 12667, - "app/tests/bug-reports-layout.test.tsx": 18000, - "app/tests/canvas-colour-read.test.tsx": 6667, - "app/tests/carry-on-carried-turn-browser.test.tsx": 32667, - "app/tests/chunk-recovery.test.tsx": 21510, - "app/tests/command-card-layout.test.tsx": 2667, - "app/tests/component-bots-layout.test.tsx": 40178, - "app/tests/composer-dictation-caret.test.tsx": 10000, - "app/tests/composer-dictation-language.test.tsx": 7810, - "app/tests/composer-keeps-draft-browser.test.tsx": 11498, - "app/tests/composer-send-while-dictating.test.tsx": 7639, - "app/tests/composer-touch-return.test.tsx": 35521, - "app/tests/computer-panel-phone-layout.test.tsx": 56333, - "app/tests/computer-starting-browser.test.tsx": 91486, - "app/tests/connected-bot-mistakes-layout.test.tsx": 25667, - "app/tests/conversation-access-ended.test.tsx": 33667, - "app/tests/conversation-allowances-layout.test.tsx": 24183, - "app/tests/conversation-kept-browser.test.tsx": 59333, - "app/tests/conversation-reopen-end.test.tsx": 43176, - "app/tests/conversation-reply-toolbar-layout.test.tsx": 26667, - "app/tests/conversation-resume.test.tsx": 51000, - "app/tests/conversation-return-running.test.tsx": 19000, - "app/tests/conversation-switch.test.tsx": 81333, - "app/tests/delete-account-layout.test.tsx": 169000, - "app/tests/desktop-versions.test.tsx": 45535, - "app/tests/desktop-window-sign-in.test.tsx": 129667, - "app/tests/failed-send-browser.test.tsx": 28153, - "app/tests/finished-run-no-stopped-notice-browser.test.tsx": 206502, - "app/tests/first-message-thinking.test.tsx": 50823, - "app/tests/free-runs-heads-up-layout.test.tsx": 121333, - "app/tests/group-conversation-gutter.test.tsx": 14176, - "app/tests/hand-back-row-layout.test.tsx": 6667, - "app/tests/home-holds-still.test.tsx": 178168, - "app/tests/home-no-answer.test.tsx": 4667, - "app/tests/home-screen-connect-browser.test.tsx": 25823, - "app/tests/long-names-layout.test.tsx": 90966, - "app/tests/long-turn-reopen.test.tsx": 71333, - "app/tests/make-artifact-browser.test.tsx": 22000, - "app/tests/member-rows-long-names.test.tsx": 14810, - "app/tests/model-picker-touch.test.tsx": 3200, - "app/tests/move-to-cloud-settings.test.tsx": 6000, - "app/tests/moved-apps-reconnect.test.tsx": 303846, - "app/tests/moved-elsewhere.test.tsx": 47867, - "app/tests/name-the-admins-layout.test.tsx": 52333, - "app/tests/new-conversation-picked-model.test.tsx": 33178, - "app/tests/offline-conversation-layout.test.tsx": 16333, - "app/tests/older-safari-build.test.ts": 18579, - "app/tests/one-press-connect-layout.test.tsx": 80511, - "app/tests/organization-held-actions.test.tsx": 53000, - "app/tests/organization-held-recovery.test.tsx": 124667, - "app/tests/organization-held-reload.test.tsx": 80333, - "app/tests/organization-members-remove.test.tsx": 7818, - "app/tests/organization-moving.test.tsx": 29653, - "app/tests/organization-removed.test.tsx": 38333, - "app/tests/organization-unavailable-admin-pages.test.tsx": 44333, - "app/tests/organization-unavailable-chat.test.tsx": 205816, - "app/tests/organization-unavailable-pages.test.tsx": 47159, - "app/tests/people-lists.test.tsx": 67333, - "app/tests/plan-notices-layout.test.tsx": 500, - "app/tests/question-answer-prompt-browser.test.tsx": 15000, - "app/tests/queue-send-now-layout.test.tsx": 15000, - "app/tests/reached-as-the-person-browser.test.tsx": 7000, - "app/tests/reconnecting-line-layout.test.tsx": 15000, - "app/tests/rejoin-fresh-token-browser.test.tsx": 32834, - "app/tests/reload-keeps-answer-browser.test.tsx": 13667, - "app/tests/renderer-crash.test.ts": 500, - "app/tests/renewal-keeps-typing-browser.test.tsx": 1000, - "app/tests/roster-working.test.tsx": 500, - "app/tests/routine-run-now-layout.test.tsx": 4173, - "app/tests/run-ended-unheard-layout.test.tsx": 149333, - "app/tests/run-refused-browser.test.tsx": 21667, - "app/tests/section-strip-routines.test.tsx": 500, - "app/tests/select-long-names-layout.test.tsx": 11000, - "app/tests/select-scrolls-layout.test.tsx": 19000, - "app/tests/self-contained-account-menu.test.tsx": 13153, - "app/tests/service-terms.test.tsx": 71333, - "app/tests/settings-tool-cards-admin-layout.test.tsx": 49849, - "app/tests/settings-tool-cards-core.test.tsx": 3200, - "app/tests/settings-tool-cards-personal.test.tsx": 13000, - "app/tests/sidebar-current-row.test.tsx": 35667, - "app/tests/sidebar-window-buttons.test.tsx": 500, - "app/tests/sidebar-zoom-drag.test.tsx": 500, - "app/tests/sign-in-app-disconnect-layout.test.tsx": 11183, - "app/tests/sign-in-reconnect-layout.test.tsx": 62000, - "app/tests/sign-in-returns-there.test.tsx": 43000, - "app/tests/sign-in-with-apple-layout.test.tsx": 18000, - "app/tests/slider-look.test.tsx": 12827, - "app/tests/staging-icon-browser.test.ts": 5812, - "app/tests/stay-signed-in-browser.test.tsx": 27333, - "app/tests/step-rows-layout.test.tsx": 59820, - "app/tests/stopped-command-layout.test.tsx": 25172, - "app/tests/stopped-turn-dismiss-browser.test.tsx": 55333, - "app/tests/stopped-turn-return-browser.test.tsx": 125339, - "app/tests/strip-version-layout.test.tsx": 107160, - "app/tests/table-export-browser.test.tsx": 125333, - "app/tests/team-connections-directory-layout.test.tsx": 18667, - "app/tests/too-many-follow-ups.test.tsx": 27165, - "app/tests/transcript-table-end.test.tsx": 22667, - "app/tests/trusted-types-build.test.ts": 500, - "app/tests/trusted-types.test.ts": 64826, - "app/tests/upload-in-parts-browser.test.tsx": 10333, - "app/tests/web-push-browser.test.tsx": 37333, - "app/tests/what-if-handle-browser.test.tsx": 3810, - "app/tests/work-folded-layout.test.tsx": 32000, - "app/tests/workspace-snapshots-layout.test.tsx": 500 + "app/tests/a2ui-table-links.test.tsx": 3799, + "app/tests/access-requests-layout.test.tsx": 5221, + "app/tests/add-custom-mcp-card-layout.test.tsx": 6739, + "app/tests/admin-notion-one-press-layout.test.tsx": 77771, + "app/tests/admin-path-layout.test.tsx": 73079, + "app/tests/admin-request-notify-layout.test.tsx": 28156, + "app/tests/agent-orb-zoom.test.tsx": 4469, + "app/tests/another-account-layout.test.tsx": 29127, + "app/tests/app-error-reporting-browser.test.ts": 2289, + "app/tests/app-frame-skeleton-still.test.tsx": 79431, + "app/tests/approval-answered-layout.test.tsx": 32539, + "app/tests/approval-card-says-what-and-where.test.tsx": 13614, + "app/tests/approval-left-carry-on-browser.test.tsx": 11603, + "app/tests/approval-rules-layout.test.tsx": 13193, + "app/tests/artifact-bridge-browser.test.ts": 150, + "app/tests/artifact-collab-browser.test.tsx": 167, + "app/tests/artifact-error-notice-layout.test.tsx": 167, + "app/tests/artifact-events-socket.test.ts": 123, + "app/tests/artifact-kinds-browser.test.tsx": 144, + "app/tests/artifact-page-storage-browser.test.ts": 1433, + "app/tests/artifact-sharing-screens-layout.test.tsx": 32090, + "app/tests/artifact-sign-in-refusal-browser.test.tsx": 6338, + "app/tests/artifact-tool-cards-browser.test.tsx": 18424, + "app/tests/artifacts-kit.test.ts": 1708, + "app/tests/artifacts-screens-layout-1.test.tsx": 196, + "app/tests/artifacts-screens-layout-2.test.tsx": 214, + "app/tests/artifacts-screens-layout-3.test.tsx": 186, + "app/tests/artifacts-screens-layout-4.test.tsx": 218, + "app/tests/artifacts-screens.test.tsx": 214, + "app/tests/board-row-layout.test.tsx": 256, + "app/tests/boot-screen.test.ts": 31429, + "app/tests/bot-file-links-browser.test.tsx": 12167, + "app/tests/bot-long-instructions-layout.test.tsx": 18707, + "app/tests/bot-owner-lists-layout.test.tsx": 27654, + "app/tests/bot-screen-sharp.test.tsx": 4725, + "app/tests/bots-panel-start-conversation.test.tsx": 4098, + "app/tests/browse-apps-pages.test.tsx": 22478, + "app/tests/browse-steps-layout.test.tsx": 11401, + "app/tests/bug-reports-layout.test.tsx": 16178, + "app/tests/canvas-colour-read.test.tsx": 6258, + "app/tests/carry-on-carried-turn-browser.test.tsx": 30628, + "app/tests/chunk-recovery.test.tsx": 19440, + "app/tests/command-card-layout.test.tsx": 2464, + "app/tests/component-bots-layout.test.tsx": 36495, + "app/tests/composer-dictation-caret.test.tsx": 9271, + "app/tests/composer-dictation-language.test.tsx": 6443, + "app/tests/composer-keeps-draft-browser.test.tsx": 11755, + "app/tests/composer-send-while-dictating.test.tsx": 6474, + "app/tests/composer-touch-return.test.tsx": 27001, + "app/tests/computer-panel-phone-layout.test.tsx": 53897, + "app/tests/computer-starting-browser.test.tsx": 95566, + "app/tests/connected-bot-mistakes-layout.test.tsx": 22595, + "app/tests/conversation-access-ended.test.tsx": 32451, + "app/tests/conversation-allowances-layout.test.tsx": 19141, + "app/tests/conversation-kept-browser.test.tsx": 59759, + "app/tests/conversation-reopen-end.test.tsx": 48695, + "app/tests/conversation-reply-toolbar-layout.test.tsx": 21418, + "app/tests/conversation-resume.test.tsx": 43544, + "app/tests/conversation-return-running.test.tsx": 19465, + "app/tests/conversation-switch.test.tsx": 76525, + "app/tests/delete-account-layout.test.tsx": 135015, + "app/tests/desktop-versions.test.tsx": 30171, + "app/tests/desktop-window-sign-in.test.tsx": 113036, + "app/tests/failed-send-browser.test.tsx": 22820, + "app/tests/finished-run-no-stopped-notice-browser.test.tsx": 216090, + "app/tests/first-message-thinking.test.tsx": 53021, + "app/tests/free-runs-heads-up-layout.test.tsx": 120630, + "app/tests/group-conversation-gutter.test.tsx": 15913, + "app/tests/hand-back-row-layout.test.tsx": 7347, + "app/tests/home-holds-still.test.tsx": 193825, + "app/tests/home-no-answer.test.tsx": 5469, + "app/tests/home-screen-connect-browser.test.tsx": 22969, + "app/tests/long-names-layout.test.tsx": 79088, + "app/tests/long-turn-reopen.test.tsx": 86670, + "app/tests/make-artifact-browser.test.tsx": 20502, + "app/tests/member-rows-long-names.test.tsx": 13347, + "app/tests/model-picker-touch.test.tsx": 3603, + "app/tests/move-to-cloud-settings.test.tsx": 3890, + "app/tests/moved-apps-reconnect.test.tsx": 266412, + "app/tests/moved-elsewhere.test.tsx": 50734, + "app/tests/name-the-admins-layout.test.tsx": 45063, + "app/tests/new-conversation-picked-model.test.tsx": 30924, + "app/tests/offline-conversation-layout.test.tsx": 16341, + "app/tests/older-safari-build.test.ts": 63710, + "app/tests/one-press-connect-layout.test.tsx": 71711, + "app/tests/organization-held-actions.test.tsx": 59582, + "app/tests/organization-held-recovery.test.tsx": 126489, + "app/tests/organization-held-reload.test.tsx": 83167, + "app/tests/organization-members-remove.test.tsx": 8833, + "app/tests/organization-moving.test.tsx": 28434, + "app/tests/organization-removed.test.tsx": 32762, + "app/tests/organization-unavailable-admin-pages.test.tsx": 45211, + "app/tests/organization-unavailable-chat.test.tsx": 168369, + "app/tests/organization-unavailable-pages.test.tsx": 42561, + "app/tests/people-lists.test.tsx": 72200, + "app/tests/plan-notices-layout.test.tsx": 226, + "app/tests/question-answer-prompt-browser.test.tsx": 15325, + "app/tests/queue-send-now-layout.test.tsx": 17916, + "app/tests/reached-as-the-person-browser.test.tsx": 7189, + "app/tests/reconnecting-line-layout.test.tsx": 15340, + "app/tests/rejoin-fresh-token-browser.test.tsx": 33990, + "app/tests/reload-keeps-answer-browser.test.tsx": 14643, + "app/tests/renderer-crash.test.ts": 112, + "app/tests/renewal-keeps-typing-browser.test.tsx": 1834, + "app/tests/roster-working.test.tsx": 23305, + "app/tests/routine-run-now-layout.test.tsx": 4968, + "app/tests/run-ended-unheard-layout.test.tsx": 154179, + "app/tests/run-refused-browser.test.tsx": 16119, + "app/tests/section-strip-routines.test.tsx": 5154, + "app/tests/select-long-names-layout.test.tsx": 12330, + "app/tests/select-scrolls-layout.test.tsx": 2128, + "app/tests/self-contained-account-menu.test.tsx": 13539, + "app/tests/service-terms.test.tsx": 83388, + "app/tests/settings-tool-cards-admin-layout.test.tsx": 39176, + "app/tests/settings-tool-cards-core.test.tsx": 3121, + "app/tests/settings-tool-cards-personal.test.tsx": 14270, + "app/tests/sidebar-current-row.test.tsx": 221, + "app/tests/sidebar-window-buttons.test.tsx": 22880, + "app/tests/sidebar-zoom-drag.test.tsx": 11150, + "app/tests/sign-in-app-disconnect-layout.test.tsx": 9512, + "app/tests/sign-in-reconnect-layout.test.tsx": 58756, + "app/tests/sign-in-returns-there.test.tsx": 46536, + "app/tests/sign-in-with-apple-layout.test.tsx": 17928, + "app/tests/slider-look.test.tsx": 12686, + "app/tests/staging-icon-browser.test.ts": 49313, + "app/tests/stay-signed-in-browser.test.tsx": 27170, + "app/tests/step-rows-layout.test.tsx": 48472, + "app/tests/stopped-command-layout.test.tsx": 29458, + "app/tests/stopped-turn-dismiss-browser.test.tsx": 46988, + "app/tests/stopped-turn-return-browser.test.tsx": 121862, + "app/tests/strip-version-layout.test.tsx": 101119, + "app/tests/table-export-browser.test.tsx": 171976, + "app/tests/team-connections-directory-layout.test.tsx": 18489, + "app/tests/too-many-follow-ups.test.tsx": 28386, + "app/tests/transcript-table-end.test.tsx": 25177, + "app/tests/trusted-types-build.test.ts": 165, + "app/tests/trusted-types.test.ts": 84859, + "app/tests/upload-in-parts-browser.test.tsx": 9914, + "app/tests/web-push-browser.test.tsx": 34310, + "app/tests/what-if-handle-browser.test.tsx": 4997, + "app/tests/work-folded-layout.test.tsx": 26818, + "app/tests/workspace-snapshots-layout.test.tsx": 306 } }