diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json
index aeeba8785e..57515ac4a6 100644
--- a/.github/ci-budgets.json
+++ b/.github/ci-budgets.json
@@ -7,6 +7,7 @@
"API spec": 3,
"native types": 3,
"app (real browser)": 8,
+ "app (real browser, Chromium) (shard N of N)": 15,
"app (real browser, WebKit) (shard N of N)": 15,
"app (real browser, desktop setup window)": 12,
"tests (shard N of N)": 7,
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dac8d475fd..344710af26 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,12 +36,15 @@ permissions:
# GitHub drops from the group's one pending slot is re-run later by Contributor CI
# (scripts/contributor-ci.ts), which also pauses fork runs while CopilotKit's are waiting.
#
-# Only a pull request's own push cancels. The release's call of these checks runs with the release
-# push's context, a push to main or to a release branch, and is never cancelled by the next one
-# (scripts/workflow-concurrency.test.ts).
+# A pull request's newer push, or the `full-ci` label, starts a replacement run. Any other label waits
+# for the run in progress instead of cancelling it: once that run is done, the waiting run finds every
+# check it passed on the same commit, skips them, and takes a minute. A label run cannot simply skip
+# everything up front: a skipped `verify` counts as passing, and could turn a failing pull request
+# green. The release's call runs with the release push's context, a push to main or to a release
+# branch, and is never cancelled by the next one (scripts/workflow-concurrency.test.ts).
concurrency:
group: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && format('ci-{0}-forks', github.workflow) || format('ci-{0}-{1}', github.workflow, github.ref == 'refs/heads/main' && github.sha || github.ref) }}
- cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') }}
# Runners. The checks run on the 16-core larger runners (org runner group openbot-larger, billed per
# minute) for main, releases and pull requests from this repository: the standard runners are shared
@@ -51,11 +56,13 @@ concurrency:
jobs:
# What this push has to run (scripts/ci-changes.ts). On a pull request, a job whose inputs are
# unchanged since a commit where it passed is skipped, and `verify` reads the skip as a pass: test
- # files alone run just those tests, docs alone run only the tests that name them, and a release PR
+ # files alone run just those tests (removing one reruns the suite's count floor), docs alone run
+ # only the tests that name them, and a release PR
# of only the release files runs the checks publishing re-runs on it. main's run of a commit the
# merge queue merged skips the checks the queue's run already passed on that same commit, and runs
- # only `component dockerfile` and any job whose cache key the push changed, which write the caches
- # pull requests read. A merge group is decided like a pull request, from main's history and the
+ # only `component dockerfile`, any job whose cache key the push changed, and startup when the queue
+ # ran Windows but omitted macOS. The first two write caches pull requests read. A merge group is
+ # decided like a pull request, from main's history and the
# queued pull request's: a job runs unless nothing it reads changed since it passed on one of them.
# A push to main the queue did not pass, the release's own call of these checks and a pull request
# labelled `full-ci` (in its own runs and in the queue) run everything. CHANGELOG.md is never a
@@ -100,6 +107,19 @@ jobs:
# Strings, since 0 is falsy and `&& 0 || 1` would always give 1.
fetch-depth: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '0' || '1' }}
filter: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && 'blob:none' || '' }}
+ # The run API names the PR head, while these jobs test its merge with main. Keep the actual
+ # checkout commit so a later merge group compares against the tree the jobs really tested.
+ - name: Record the tested checkout
+ if: github.event_name == 'pull_request'
+ run: git rev-parse HEAD > "$RUNNER_TEMP/ci-tested-tree.txt"
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: github.event_name == 'pull_request'
+ with:
+ # Re-running only a failed check retains changes' original proof artifact.
+ name: ci-tested-tree-${{ github.run_id }}
+ path: ${{ runner.temp }}/ci-tested-tree.txt
+ retention-days: 14
+ overwrite: true
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.4.3
@@ -141,6 +161,11 @@ jobs:
- run: bun run format:check
- run: bun run lint
- run: bun run typecheck
+ # Desktop is not a root workspace; its test files still belong to its TypeScript project.
+ - run: bun install --frozen-lockfile
+ working-directory: desktop
+ - run: bun run typecheck
+ working-directory: desktop
- name: Desktop version tracks the release version
run: bun desktop/scripts/desktop-version.ts check
# What each recorded OpenBot Desktop launch hands Compose, read with this tree's
@@ -585,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
@@ -606,12 +635,14 @@ jobs:
# 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.
app-browser-webkit:
- name: app (real browser, WebKit) (shard ${{ matrix.shard }} of ${{ strategy.job-total }})
+ name: app (real browser, ${{ matrix.engine }}) (shard ${{ matrix.shard }} of 3)
needs: changes
strategy:
- # Every shard runs to the end, so one red run names every failing test, as the suite's do.
+ # Each engine and shard has its own runner and result, so a failed leg can be re-run on its
+ # own. A failure still stops the whole run at once (.github/actions/stop-on-failure).
fail-fast: false
matrix:
+ engine: [Chromium, WebKit]
shard: [1, 2, 3]
# On a pull request, only when the app, what it imports or its tests change (scripts/ci-changes.ts,
# app_browser_webkit). A merge group and main run it every time.
@@ -627,7 +658,9 @@ jobs:
PLAYWRIGHT_IMAGE: mcr.microsoft.com/playwright:v1.62.1-noble@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e
TEST_WORKERS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '2' || '8' }}
TEST_TIMEOUT_MS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '15000' || '5000' }}
- TEST_SHARD: ${{ matrix.shard }}/${{ strategy.job-total }}
+ # Three shards per engine; strategy.job-total counts all six engine/shard jobs.
+ TEST_SHARD: ${{ matrix.shard }}/3
+ BROWSER_ENGINE: ${{ matrix.engine == 'WebKit' && 'webkit' || 'chromium' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -745,12 +778,12 @@ jobs:
docker run --rm --ipc=host \
--volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \
--volume "$(command -v bun):/usr/local/bin/bun:ro" \
- --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \
+ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES="$BROWSER_ENGINE" \
"$PLAYWRIGHT_IMAGE" \
bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" --shard="$TEST_SHARD" "${files[@]}"
# Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard.
# Only that test: the rest of the file runs in Chromium in the job above. Once, on the first shard.
- - if: matrix.shard == 1
+ - if: matrix.engine == 'WebKit' && matrix.shard == 1
run: |
docker run --rm --ipc=host \
--volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \
@@ -788,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: |
@@ -947,8 +985,12 @@ jobs:
if: needs.changes.outputs.browser_tests != '[]' || needs.changes.outputs.desktop_browser_tests != '[]'
run: bunx playwright-core install --with-deps --no-shell chromium
- name: Install WebKit
- if: needs.changes.outputs.webkit_tests != '[]'
+ if: needs.changes.outputs.webkit_tests != '[]' || contains(fromJSON(needs.changes.outputs.desktop_browser_tests), 'desktop/src/setupLayout.browser.test.ts')
run: bunx playwright-core install --with-deps webkit
+ # The print-page test serves the shipped HTML, styles and assets from app/dist.
+ - name: Build the print page and app assets
+ if: contains(fromJSON(needs.changes.outputs.browser_tests), 'app/tests/artifact-print-browser.test.ts')
+ run: bun run --cwd app build
- name: Run the changed tests
env:
TESTS: ${{ needs.changes.outputs.tests }}
diff --git a/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/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..f105354fd8
--- /dev/null
+++ b/app/tests/browser-engines.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { launchBrowserEngines, ownBrowsersAsked } from "./browser-engines";
+
+describe("browser engine selection", () => {
+ for (const [selection, expected] of [
+ [undefined, ["chromium"]],
+ ["chromium", ["chromium"]],
+ ["webkit", ["webkit"]],
+ ["chromium,webkit", ["chromium", "webkit"]],
+ [" chromium, webkit ", ["chromium", "webkit"]],
+ ] as const) {
+ test(`${selection ?? "default"} launches only its selected engines`, async () => {
+ const calls: { engine: string; options: unknown }[] = [];
+ const factory = (engine: string) => ({
+ launch: async (options?: { channel?: string }) => {
+ calls.push({ engine, options });
+ return { engine };
+ },
+ });
+ const opened: [string, { engine: string }][] = [];
+ await launchBrowserEngines(
+ { chromium: factory("chromium"), webkit: factory("webkit") },
+ selection,
+ opened,
+ );
+ expect(calls).toEqual(
+ expected.map((engine) => ({
+ engine,
+ options: engine === "chromium" ? { channel: "chromium" } : undefined,
+ })),
+ );
+ expect(opened).toEqual(expected.map((engine) => [engine, { engine }]));
+ });
+ }
+
+ test("the caller owns browsers already launched when a later engine fails", async () => {
+ const opened: [string, { close: () => void }][] = [];
+ let closed = false;
+ const chromium = {
+ close: () => {
+ closed = true;
+ },
+ };
+ await expect(
+ launchBrowserEngines(
+ {
+ chromium: { launch: async () => chromium },
+ webkit: {
+ launch: async () => {
+ throw new Error("WebKit launch failed");
+ },
+ },
+ },
+ "chromium,webkit",
+ opened,
+ ),
+ ).rejects.toThrow("WebKit launch failed");
+ expect(opened).toEqual([["chromium", chromium]]);
+ for (const [, browser] of opened) browser.close();
+ expect(closed).toBe(true);
+ });
+
+ test("an unsupported selection cannot silently run no browsers", async () => {
+ let launched = false;
+ const factory = {
+ launch: async () => {
+ launched = true;
+ return {};
+ },
+ };
+ await expect(
+ launchBrowserEngines(
+ { chromium: factory, webkit: factory },
+ "unsupported",
+ [],
+ ),
+ ).rejects.toThrow("Unsupported browser engine");
+ expect(launched).toBe(false);
+ });
+});
+
+/** Built, not written out: a file naming the variable outright is taken for a real-browser test. */
+const ASK = ["OPENBOT", "APP", "BROWSER"].join("_");
+
+describe("a file that opens its own browsers", () => {
+ test("runs where Chromium is selected, and only when real-browser tests are asked for", () => {
+ for (const [env, runs] of [
+ [{}, false],
+ [{ [ASK]: "1" }, true],
+ [{ [ASK]: "1", OPENBOT_APP_ENGINES: "chromium" }, true],
+ [{ [ASK]: "1", OPENBOT_APP_ENGINES: "chromium,webkit" }, true],
+ [{ [ASK]: "1", OPENBOT_APP_ENGINES: "webkit" }, false],
+ ] as const) {
+ expect({ env, runs: ownBrowsersAsked(env) }).toEqual({ env, runs });
+ }
+ expect(() =>
+ ownBrowsersAsked({
+ [ASK]: "1",
+ OPENBOT_APP_ENGINES: "firefox",
+ }),
+ ).toThrow("Unsupported browser engine: firefox");
+ });
+
+ test("CI's cross-browser list: every file opens only the engine its run selects, or runs once", () => {
+ // The list runs once per engine. A file that ignored the selection ran in full in both runs:
+ // artifacts-screens, the slowest file, twice. Each file must read OPENBOT_APP_ENGINES, launch
+ // through launchBrowserEngines, or gate on ownBrowsersAsked.
+ const root = join(import.meta.dir, "..", "..");
+ const ci = Bun.YAML.parse(
+ readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"),
+ ) as { jobs: Record };
+ const listed = (ci.jobs["app-browser-webkit"]?.steps ?? []).flatMap(
+ (step) =>
+ (step.run ?? "").match(/app\/tests\/[\w.-]+\.test\.tsx?/g) ?? [],
+ );
+ expect(listed.length).toBeGreaterThan(50);
+ const ignoring = [...new Set(listed)].filter(
+ (file) =>
+ !/OPENBOT_APP_ENGINES|launchBrowserEngines|ownBrowsersAsked/.test(
+ readFileSync(join(root, file), "utf8"),
+ ),
+ );
+ expect(ignoring).toEqual([]);
+ });
+});
diff --git a/app/tests/browser-engines.ts b/app/tests/browser-engines.ts
new file mode 100644
index 0000000000..d34ae22b62
--- /dev/null
+++ b/app/tests/browser-engines.ts
@@ -0,0 +1,49 @@
+type BrowserFactory = {
+ launch(options?: { channel?: string }): Promise;
+};
+
+/** The engines OPENBOT_APP_ENGINES names, Chromium when it names none. */
+export function selectedEngines(
+ selection: string | undefined,
+): Set<"chromium" | "webkit"> {
+ const selected = new Set<"chromium" | "webkit">();
+ for (const engine of (selection?.trim() || "chromium").split(",")) {
+ const name = engine.trim();
+ if (name !== "chromium" && name !== "webkit") {
+ throw new Error(`Unsupported browser engine: ${name}`);
+ }
+ selected.add(name);
+ }
+ return selected;
+}
+
+/**
+ * Whether a real-browser test file that opens its own browsers, rather than the engines
+ * OPENBOT_APP_ENGINES selects, runs: real-browser tests are asked for and Chromium is selected,
+ * as it is by default. Such a file opens Chromium alone, or both engines itself. CI's cross-browser
+ * list runs once per engine, so it runs there once, in the Chromium run, not twice.
+ */
+export function ownBrowsersAsked(
+ env: Record = process.env,
+): boolean {
+ return (
+ env.OPENBOT_APP_BROWSER === "1" &&
+ selectedEngines(env.OPENBOT_APP_ENGINES).has("chromium")
+ );
+}
+
+/** Launch only the selected engines. The caller retains cleanup ownership, including on failure. */
+export async function launchBrowserEngines(
+ factories: Record<"chromium" | "webkit", BrowserFactory>,
+ selection: string | undefined,
+ opened: [string, T][],
+): Promise {
+ for (const engine of selectedEngines(selection)) {
+ // CI installs full Chromium without the headless shell.
+ const browser =
+ engine === "chromium"
+ ? await factories.chromium.launch({ channel: "chromium" })
+ : await factories.webkit.launch();
+ opened.push([engine, browser]);
+ }
+}
diff --git a/app/tests/company-sign-in.test.tsx b/app/tests/company-sign-in.test.tsx
index 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.
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/roster-working.test.tsx b/app/tests/roster-working.test.tsx
index fbf601d216..36bb305eef 100644
--- a/app/tests/roster-working.test.tsx
+++ b/app/tests/roster-working.test.tsx
@@ -1,13 +1,9 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type {
- Browser,
- BrowserType,
- Page,
- WebSocketRoute,
-} from "playwright-core";
+import type { Browser, Page, WebSocketRoute } from "playwright-core";
import { compile } from "tailwindcss";
+import { launchBrowserEngines } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -26,7 +22,7 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/roster-working.test.tsx
*
- * Chromium always, WebKit too when `OPENBOT_APP_ENGINES` names it; light and dark. With
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both, light and dark. With
* OPENBOT_APP_SHOTS= it saves each moment as roster-working----.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -168,10 +164,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
});
afterAll(async () => {
diff --git a/app/tests/section-strip-routines.test.tsx b/app/tests/section-strip-routines.test.tsx
index 1e421b8239..491be80edd 100644
--- a/app/tests/section-strip-routines.test.tsx
+++ b/app/tests/section-strip-routines.test.tsx
@@ -1,9 +1,10 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type { Browser, BrowserType, Page } from "playwright-core";
+import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { personBody } from "./accounts-api";
+import { launchBrowserEngines } from "./browser-engines";
import { conversationPage } from "./conversations-api";
import { still } from "./page-still";
import { test } from "./renderer-crash";
@@ -26,8 +27,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/section-strip-routines.test.tsx
*
- * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when
- * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves the strip and the panel on
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both.
+ * With OPENBOT_APP_SHOTS= it saves the strip and the panel on
* Routines, after Conversations, Bots and then Routines, as section-strip-routines--.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -190,11 +191,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- // The CI job installs full Chromium without the headless shell.
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
}, 120_000);
afterAll(async () => {
diff --git a/app/tests/select-scrolls-layout.test.tsx b/app/tests/select-scrolls-layout.test.tsx
index 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/sidebar-zoom-drag.test.tsx b/app/tests/sidebar-zoom-drag.test.tsx
index 4f84b9e62c..0dc7551b7f 100644
--- a/app/tests/sidebar-zoom-drag.test.tsx
+++ b/app/tests/sidebar-zoom-drag.test.tsx
@@ -1,9 +1,10 @@
import { afterAll, beforeAll, describe, expect } from "bun:test";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import type { Browser, BrowserType, Page } from "playwright-core";
+import type { Browser, Page } from "playwright-core";
import { compile } from "tailwindcss";
import { personBody } from "./accounts-api";
+import { launchBrowserEngines } from "./browser-engines";
import { test } from "./renderer-crash";
/**
@@ -31,8 +32,8 @@ import { test } from "./renderer-crash";
*
* OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/sidebar-zoom-drag.test.tsx
*
- * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when
- * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves each case as
+ * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both.
+ * With OPENBOT_APP_SHOTS= it saves each case as
* sidebar-zoom---.png.
*/
const asked = process.env.OPENBOT_APP_BROWSER === "1";
@@ -263,11 +264,11 @@ beforeAll(async () => {
readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/),
);
css = await stylesheet([...new Set(sources)].sort());
- const { chromium, webkit } = await import("playwright-core");
- // The CI job installs full Chromium without the headless shell.
- engines.push(["chromium", await chromium.launch({ channel: "chromium" })]);
- if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit"))
- engines.push(["webkit", await (webkit as BrowserType).launch()]);
+ await launchBrowserEngines(
+ await import("playwright-core"),
+ process.env.OPENBOT_APP_ENGINES,
+ engines,
+ );
});
afterAll(async () => {
diff --git a/app/tests/trusted-types-build.test.ts b/app/tests/trusted-types-build.test.ts
index 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 57957f95d0..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,17 +99,16 @@ const watch = Bun.YAML.parse(
function names(id: string, job: Job): string[] {
const name = job.name ?? id;
if (!name.includes(EXPRESSION)) return [name];
- const [key, values] = Object.entries(job.strategy?.matrix ?? {})[0] ?? [];
- const expanded = Array.isArray(values)
- ? values.map((value) =>
- name
- .replaceAll(`${EXPRESSION} matrix.${key} }}`, String(value))
- .replaceAll(
- `${EXPRESSION} strategy.job-total }}`,
- String(values.length),
- ),
+ 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,
)
- : [name];
+ .replaceAll(`${EXPRESSION} strategy.job-total }}`, String(all.length)),
+ );
return [
...new Set(
expanded.map((n) => (n.includes(EXPRESSION) ? wildcard(n) : jobKey(n))),
@@ -76,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 eab225d564..cb5aaef190 100644
--- a/scripts/ci-changes.test.ts
+++ b/scripts/ci-changes.test.ts
@@ -1,6 +1,16 @@
import { describe, expect, test } from "bun:test";
-import { existsSync, readdirSync, readFileSync } from "node:fs";
-import { join } from "node:path";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
import {
CACHE_WRITERS,
type Change,
@@ -11,6 +21,7 @@ import {
decideDesktopMainPush,
decideMainPush,
decideMergeGroup,
+ isBrowserTest,
isBunTest,
isCode,
isDocs,
@@ -23,6 +34,7 @@ import {
queuedPullRequest,
SHARDS,
SUITE_RULE,
+ testedCheckout,
} from "./ci-changes";
import type { CiRun } from "./release-ci-gate";
@@ -30,6 +42,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 = [
@@ -118,12 +134,230 @@ 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 };
+/** 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, commits: string[]) => Record;
+ proof?: boolean | string;
+ proofs?: (commits: string[]) => Record;
+ commits?: Record[];
+ base?: string;
+ baseIndex?: number;
+ expectFailure?: boolean;
+ 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 {
+ const git = (...args: string[]) => {
+ 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(
+ "-c",
+ "user.name=CI",
+ "-c",
+ "user.email=ci@example.test",
+ "commit",
+ "--quiet",
+ "--allow-empty",
+ "-m",
+ "test",
+ );
+ 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);
+ }
+ 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, commits),
+ proof: options.proof,
+ proofs: options.proofs?.(commits),
+ sha,
+ queue: options.queue,
+ queueCalls: join(directory, "queue-calls.jsonl"),
+ historyCalls:
+ options.historyBudgetMs === undefined
+ ? undefined
+ : join(directory, "history-called"),
+ }),
+ );
+ const gh = join(directory, "gh");
+ writeFileSync(
+ gh,
+ `#!${process.execPath}
+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);
+if (args[0] === "run" && args[1] === "download") {
+ 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 (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];
+ console.log(JSON.stringify(args.includes("--slurp") ? (Array.isArray(response) ? response : [response]) : (Array.isArray(response) ? response[0] : response)));
+}
+`,
+ );
+ chmodSync(gh, 0o755);
+ 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");
+ writeFileSync(
+ 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});
+}
+if (args[0] === "grep" && ${options.grepExit !== undefined}) {
+ 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,
+ JSON.stringify({
+ before: "b".repeat(40),
+ pull_request: {
+ labels: [],
+ head: { ref: "fix", sha, repo: { full_name: repository } },
+ base: { sha: options.base ?? commits[options.baseIndex ?? 0] },
+ },
+ merge_group: {
+ 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}`,
+ },
+ }),
+ );
+ 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: "",
+ CI_HISTORY_BUDGET_MS: String(options.historyBudgetMs ?? 45_000),
+ },
+ },
+ );
+ if (options.expectFailure) {
+ expect(result.exitCode).not.toBe(0);
+ expect(existsSync(output)).toBe(false);
+ 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)
+ expect(existsSync(join(directory, "probe-called"))).toBe(true);
+ 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",
@@ -251,6 +485,495 @@ 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/artifact-print-browser.test.ts";
+ 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] : []);
+ // 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);
+ }
+ });
+ test("sharded full-array coverage requires the complete supported engine and shard matrix", () => {
+ const file = "app/tests/selected.browser.test.ts";
+ const run = `files=(\n ${file}\n)\nbun test --parallel --shard="$TEST_SHARD" "\${files[@]}"`;
+ const job = {
+ name: `app (real browser, ${expression("matrix.engine")}) (shard ${expression("matrix.shard")} of 3)`,
+ if: "needs.changes.outputs.app_browser_webkit == 'true'",
+ strategy: {
+ matrix: { engine: ["Chromium", "WebKit"], shard: [1, 2, 3] },
+ },
+ env: { TEST_SHARD: `${expression("matrix.shard")}/3` },
+ steps: [{ run }],
+ };
+ const cases = [
+ [job, true],
+ [
+ {
+ ...job,
+ strategy: { matrix: { ...job.strategy.matrix, shard: [1, 2] } },
+ },
+ false,
+ ],
+ [
+ {
+ ...job,
+ strategy: {
+ matrix: {
+ ...job.strategy.matrix,
+ exclude: [{ engine: "WebKit", shard: 2 }],
+ },
+ },
+ },
+ false,
+ ],
+ [
+ {
+ ...job,
+ strategy: {
+ matrix: { ...job.strategy.matrix, engine: ["Chromium"] },
+ },
+ },
+ false,
+ ],
+ [
+ {
+ ...job,
+ env: {
+ TEST_SHARD: `${expression("matrix.shard")}/${expression("strategy.job-total")}`,
+ },
+ },
+ false,
+ ],
+ [
+ {
+ ...job,
+ steps: [{ run: run.replace('--shard="$TEST_SHARD"', "--shard=1/3") }],
+ },
+ false,
+ ],
+ [
+ {
+ ...job,
+ steps: [
+ { run: run.replace("--parallel", '--parallel -t "one case"') },
+ ],
+ },
+ false,
+ ],
+ [{ ...job, steps: [{ run, if: "matrix.shard == 1" }] }, false],
+ ] as const;
+ for (const [manifest, covered] of cases) {
+ for (const scheduled of [false, true]) {
+ const base = deps({
+ passed: { c2: ALL_CI },
+ changes: { c2: scheduled ? ["app/src/main.tsx"] : [] },
+ });
+ 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": manifest } })
+ : "process.env.OPENBOT_APP_BROWSER",
+ });
+ expect({ covered, scheduled, files: result.browserTests }).toEqual({
+ covered,
+ scheduled,
+ files: covered ? [] : [file],
+ });
+ }
+ }
+ });
+
+ test("the cross-browser baseline requires every engine's three successful shards", () => {
+ const checks = ["Chromium", "WebKit"].flatMap((engine) =>
+ [1, 2, 3].map(
+ (shard) => `app (real browser, ${engine}) (shard ${shard} of 3)`,
+ ),
+ );
+ for (const missing of [...checks, undefined]) {
+ const result = decide(
+ "ci",
+ PR,
+ deps({
+ passed: {
+ c2: ALL_CI.filter((check) => check !== missing),
+ c1: ALL_CI,
+ },
+ changes: { c1: ["app/src/main.tsx"] },
+ }),
+ );
+ expect({ missing, run: result.run.app_browser_webkit }).toEqual({
+ missing,
+ run: missing !== undefined,
+ });
+ }
+ });
+
+ 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]) {
+ const base = deps({
+ passed: {
+ c2: recovered
+ ? ALL_CI
+ : ALL_CI.filter(
+ (name) => name !== "app (real browser, WebKit) (shard 2 of 3)",
+ ),
+ 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",
+ ".github/workflows/ci.yml": readTracked(
+ ".github/workflows/ci.yml",
+ ) as string,
+ },
+ });
+ 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/artifact-print-browser.test.ts";
+ 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) (shard 2 of 3)",
+ ),
+ 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/artifact-print-browser.test.ts";
+ 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(
+ "ci",
+ { ...PR, checkout: "merge" },
+ {
+ ...base,
+ diff: (from, to) => {
+ expect(["c2", PR.base]).toContain(from);
+ 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",
@@ -374,6 +1097,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", () => {
@@ -502,7 +1231,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,
@@ -531,13 +1260,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,
@@ -548,7 +1278,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", () => {
@@ -672,6 +1403,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/artifact-print-browser.test.ts";
+ 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(
@@ -733,8 +1512,137 @@ 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",
+ commits: [{ "README.md": "renamed source body" }],
+ responses: (sha, commits) => ({
+ [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${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("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");
@@ -745,6 +1653,7 @@ describe("a merge group", () => {
"ci",
[...UNREAD_DOCS, "CHANGELOG.md"],
REAL,
+ GROUP,
);
expect(running(decision)).toEqual(
decision.tests.length > 0 ? ["partial"] : [],
@@ -758,7 +1667,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",
@@ -775,7 +1689,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,
});
@@ -790,15 +1707,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", () => {
@@ -858,6 +1778,95 @@ 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("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/artifact-print-browser.test.ts";
+ 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.
+ 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).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 = {
passed: {
@@ -919,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", () => {
@@ -946,6 +1968,157 @@ 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("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:
+ "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}`]: {
+ 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(
@@ -967,6 +2140,454 @@ describe("a merge group", () => {
});
});
+describe("the checkout a passing run proves", () => {
+ test("a potentially lazy-fetching Git presence probe stays inside the history deadline", () => {
+ const started = performance.now();
+ const file = "app/tests/artifact-print-browser.test.ts";
+ const result = actionsDecision({
+ event: "pull_request",
+ historyBudgetMs: 1_000,
+ probeDelayMs: 3_000,
+ proof: true,
+ 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: "pull_request",
+ path: ".github/workflows/ci.yml",
+ head_repository: { full_name: "CopilotKit/OpenBot" },
+ },
+ ],
+ },
+ "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100":
+ { jobs: API_BASELINE_JOBS },
+ }),
+ });
+ expect(performance.now() - started).toBeLessThan(2_500);
+ expect(result.suite).toBe("true");
+ expect(JSON.parse(result.browser_tests)).toEqual([file]);
+ });
+
+ test("CLI CI script edits run unit fixtures in the full suite without browser partial work", () => {
+ const result = actionsDecision({
+ event: "pull_request",
+ historyBudgetMs: 0,
+ commits: [
+ {
+ "scripts/ci-changes.ts": "// changed CI source",
+ "scripts/ci-changes.test.ts":
+ "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES",
+ "scripts/ci-run-tests.test.ts":
+ "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES",
+ },
+ ],
+ responses: () => ({}),
+ });
+ expect(result.suite).toBe("true");
+ expect(result.partial).toBe("false");
+ expect(JSON.parse(result.browser_tests)).toEqual([]);
+ expect(JSON.parse(result.tests)).toEqual([]);
+ });
+
+ test("zero history budget runs unresolved checks and keeps current unlisted browser files", () => {
+ const file = "app/tests/artifact-print-browser.test.ts";
+ 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/artifact-print-browser.test.ts";
+ 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],
+ ["push", "feature", false],
+ ["push", "main", true],
+ ] as const) {
+ const result = actionsDecision({
+ event: "pull_request",
+ 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`]:
+ {
+ workflow_runs: [
+ {
+ id: 1,
+ event,
+ head_branch,
+ 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([]);
+ 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");
+ }
+ });
+
+ test("current unlisted work remains owed while partial results govern fixed-job reuse", () => {
+ const app = "app/tests/artifact-print-browser.test.ts";
+ 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,
+ head_branch: event === "push" ? "main" : "feature",
+ 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([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");
+ }
+ }, 15_000);
+
+ test("historical API failure still runs changed browser files from the local PR diff", () => {
+ const file = "app/tests/artifact-print-browser.test.ts";
+ 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/artifact-print-browser.test.ts":
+ "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",
+ 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: 3,
+ head_repository: { full_name: "CopilotKit/OpenBot" },
+ },
+ ],
+ },
+ "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100":
+ [
+ {
+ jobs: Array.from({ length: 100 }, () => ({
+ name: "app (real browser)",
+ conclusion: "failure",
+ })),
+ },
+ { jobs: API_BASELINE_JOBS },
+ ],
+ }),
+ });
+ expect(result.suite).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: API_BASELINE_JOBS },
+ }),
+ });
+ 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: API_BASELINE_JOBS },
+ }),
+ });
+ 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", () => {
+ 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";
@@ -986,10 +2607,100 @@ 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",
@@ -1030,16 +2741,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.
@@ -1162,6 +2881,65 @@ 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(
+ "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.
@@ -1246,33 +3024,98 @@ function jobNames(workflow: string): string[] {
for (const [id, job] of Object.entries(parsed.jobs)) {
const name = job.name ?? id;
const matrix = job.strategy?.matrix ?? {};
- const [key, listed] = Object.entries(matrix)[0] ?? [];
- if (!key || !name.includes("${{")) {
+ const dimensions = Object.entries(matrix);
+ if (dimensions.length === 0 || !name.includes("${{")) {
names.push(name);
continue;
}
- // The image builds' matrix is `component list`'s output, which is .github/published-images.json.
- const values: unknown = listed;
- const expanded =
- typeof values === "string" &&
- values.includes("needs.component-list.outputs.components")
- ? PUBLISHED_IMAGES
- : values;
- for (const value of expanded as unknown[]) {
- names.push(
- name
- .replace(expression(`matrix.${key}`), String(value))
- .replace(
- expression("strategy.job-total"),
- String((expanded as unknown[] | undefined)?.length),
- ),
+ let expanded = [name];
+ let total = 1;
+ for (const [key, listed] of dimensions) {
+ // The image matrix is dynamic; its source is the published-image list.
+ const values: unknown = listed;
+ const choices =
+ typeof values === "string" &&
+ values.includes("needs.component-list.outputs.components")
+ ? PUBLISHED_IMAGES
+ : (values as unknown[]);
+ total *= choices.length;
+ expanded = expanded.flatMap((value) =>
+ choices.map((choice) =>
+ value.replace(expression(`matrix.${key}`), String(choice)),
+ ),
);
}
+ names.push(
+ ...expanded.map((value) =>
+ value.replace(expression("strategy.job-total"), String(total)),
+ ),
+ );
}
return names;
}
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"),
+ ) as {
+ jobs: Record<
+ string,
+ {
+ strategy?: {
+ matrix?: { engine?: string[]; shard?: number[] };
+ "fail-fast"?: boolean;
+ };
+ name?: string;
+ env?: Record;
+ steps: { run?: string; if?: string }[];
+ }
+ >;
+ };
+ const job = ci.jobs["app-browser-webkit"];
+ expect(job.strategy?.matrix?.engine).toEqual(["Chromium", "WebKit"]);
+ expect(job.strategy?.matrix?.shard).toEqual([1, 2, 3]);
+ expect(job.strategy?.["fail-fast"]).toBe(false);
+ expect(job.name).toBe(
+ `app (real browser, ${expression("matrix.engine")}) (shard ${expression("matrix.shard")} of 3)`,
+ );
+ expect(job.env?.TEST_SHARD).toBe(`${expression("matrix.shard")}/3`);
+ const rule = CI_RULES.find((rule) => rule.output === "app_browser_webkit");
+ expect(rule?.checks).toEqual([
+ "app (real browser, Chromium) (shard 1 of 3)",
+ "app (real browser, Chromium) (shard 2 of 3)",
+ "app (real browser, Chromium) (shard 3 of 3)",
+ "app (real browser, WebKit) (shard 1 of 3)",
+ "app (real browser, WebKit) (shard 2 of 3)",
+ "app (real browser, WebKit) (shard 3 of 3)",
+ ]);
+ const clipboard = job.steps.find((step) =>
+ step.run?.includes("copies with one press"),
+ );
+ expect(clipboard?.if).toBe(
+ "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('OPENBOT_APP_ENGINES="$BROWSER_ENGINE"');
+ });
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 b1d6fa669f..6339a61d4b 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.
@@ -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
@@ -40,14 +41,20 @@
* 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. The optional queued
+ * 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.
*/
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 {
@@ -178,6 +185,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",
@@ -261,11 +270,13 @@ 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",
- // Every shard, as the suite's: the list passed only once all of them did.
- checks: Array.from(
- { length: WEBKIT_SHARDS },
- (_, index) =>
- `app (real browser, WebKit) (shard ${index + 1} of ${WEBKIT_SHARDS})`,
+ // Every shard of both engines must pass before the expanded list is reusable.
+ checks: ["Chromium", "WebKit"].flatMap((engine) =>
+ Array.from(
+ { length: WEBKIT_SHARDS },
+ (_, index) =>
+ `app (real browser, ${engine}) (shard ${index + 1} of ${WEBKIT_SHARDS})`,
+ ),
),
reads: (path) => (isCode(path) && appInputs(path)) || ciInputs(path),
},
@@ -325,13 +336,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,
};
@@ -383,6 +397,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;
};
@@ -393,6 +409,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. */
@@ -461,6 +479,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.
@@ -473,7 +505,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)) {
@@ -489,13 +526,19 @@ 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);
+ 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.
*/
@@ -504,6 +547,7 @@ function decideFrom(
head: string,
histories: string[][],
deps: Deps,
+ currentChanges?: () => Change[],
): Decision {
const rules = rulesOf(workflow);
const passedAt = new Map>();
@@ -515,16 +559,32 @@ function decideFrom(
}
return names;
};
- /** 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);
+ /** Visit each history at the same depth before looking farther back on either one. */
+ const baselinesOf = (checks: 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++) {
+ 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) found.add(lane);
+ for (const tree of trees) {
+ baselines[lane].push(tree);
+ if (since(tree).length === 0) return baselines.flat();
+ }
+ }
+ if (found.size === histories.length) break;
+ }
+ // Equal-input ties prefer the checkout/main lane, independent of interleaved discovery order.
+ return baselines.flat();
+ };
const changesSince = new Map();
const since = (sha: string) => {
let changes = changesSince.get(sha);
@@ -573,8 +633,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,
+ )
);
};
@@ -609,6 +672,7 @@ function decideFrom(
(change) =>
!change.deleted &&
isBunTest(change.path) &&
+ isBrowserTest(change.path, deps) &&
(deps.read(change.path)?.includes("OPENBOT_APP_ENGINES") ?? false),
);
if (webkitTest) {
@@ -618,7 +682,13 @@ function decideFrom(
);
}
}
- decideSuite(decision, changesFor(SUITE_RULE), changesFor, deps);
+ decideSuite(
+ decision,
+ changesFor(SUITE_RULE),
+ changesFor,
+ deps,
+ currentChanges,
+ );
}
return decision;
}
@@ -628,12 +698,20 @@ function decideSuite(
decision: Decision,
suiteChanges: Change[] | undefined,
changesFor: (rule: Rule) => Change[] | undefined,
- deps: Deps,
+ deps: Pick,
+ 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(
@@ -641,13 +719,24 @@ 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,
+ covered?: Set,
+ ) => {
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
@@ -656,28 +745,73 @@ 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);
+ }
}
};
if (!run.suite) add(suiteChanges, false);
- if (!run.app_browser) {
+ 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.
+ let changes = changesFor(
+ CI_RULES.find((rule) => rule.output === output) as Rule,
+ );
+ if (!changes) {
+ current ??= currentChanges?.().filter(
+ (change) => !isIgnored(change.path),
+ );
+ changes = current;
+ }
add(
- changesFor(
- CI_RULES.find((rule) => rule.output === "app_browser") as Rule,
- ),
+ 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.
+ 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/")) {
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);
}
}
@@ -698,11 +832,130 @@ function decideSuite(
}
}
-/** A test that drives a real browser, which `bun test` alone skips. */
-function isBrowserTest(file: string, deps: Pick): boolean {
+/** 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,
+ jobs = ["app-browser", "app-browser-webkit", "app-browser-desktop"],
+): Set {
+ const files = new Set();
+ try {
+ const workflow = Bun.YAML.parse(
+ deps.read(".github/workflows/ci.yml") ?? "",
+ ) as {
+ jobs?: Record<
+ string,
+ {
+ name?: string;
+ if?: unknown;
+ strategy?: { matrix?: Record };
+ env?: Record;
+ steps?: { run?: string; if?: unknown }[];
+ }
+ >;
+ } | null;
+ for (const id of jobs) {
+ const job = workflow?.jobs?.[id];
+ const matrix = job?.strategy?.matrix;
+ const engineExpression = ["$", "{{ matrix.engine }}"].join("");
+ const shardExpression = ["$", "{{ matrix.shard }}"].join("");
+ // This one supported shard contract schedules every shard of both engines together.
+ // A partial/dynamic matrix or a divisor counting engines as shards proves no full array.
+ const completeShards =
+ id === "app-browser-webkit" &&
+ job?.name ===
+ `app (real browser, ${engineExpression}) (shard ${shardExpression} of 3)` &&
+ job.if === "needs.changes.outputs.app_browser_webkit == 'true'" &&
+ JSON.stringify(Object.keys(matrix ?? {}).sort()) ===
+ '["engine","shard"]' &&
+ JSON.stringify(matrix?.engine) === '["Chromium","WebKit"]' &&
+ JSON.stringify(matrix?.shard) === "[1,2,3]" &&
+ job.env?.TEST_SHARD === `${shardExpression}/3`;
+ for (const step of job?.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,
+ ) ||
+ (completeShards && flag === '--shard="$TEST_SHARD"'),
+ )
+ );
+ })
+ )
+ 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;
+ // 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;
+ } catch {
+ // An unreadable or unrecognised manifest must leave every changed browser file owed.
+ return new Set();
+ }
+}
+
+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))
);
}
@@ -784,9 +1037,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(
@@ -794,6 +1047,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) {
@@ -807,6 +1061,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;
@@ -866,11 +1144,15 @@ 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[];
/** 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;
};
};
@@ -902,6 +1184,32 @@ 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,
+ });
+ 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(
+ "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) =>
isIgnored(path) ||
@@ -944,10 +1252,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.",
@@ -957,11 +1261,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.",
@@ -969,18 +1268,25 @@ 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,
- 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."
- : "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 };
}
@@ -995,9 +1301,17 @@ function describe(changes: Change[]): string {
// ---------------------------------------------------------------------------------------------
// Running it in Actions.
-function exec(cmd: string[], allowFailure = false): string {
- const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" });
- if (result.exitCode !== 0 && !allowFailure) {
+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()}`);
}
return result.stdout.toString();
@@ -1006,9 +1320,76 @@ function exec(cmd: string[], allowFailure = false): string {
type ApiRun = {
id: number;
path: string;
+ event: string;
+ head_branch: string | null;
+ 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;
+ id?: number;
+};
+
+/** Every page and attempt: a partial rerun retains the jobs that did not rerun. */
+function jobsOf(
+ repository: string,
+ run: Pick,
+ command: (cmd: string[]) => string = exec,
+): ApiJob[] {
+ const pages = JSON.parse(
+ command([
+ "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(
+ 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;
+}
+
+/**
+ * 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)
+ ? 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(perCommandMs, remaining());
+ if (timeout <= 0) throw new Error("Historical CI proof budget exhausted");
+ return exec(cmd, undefined, timeout);
+ },
+ };
+}
function liveDeps(
workflow: Workflow,
@@ -1017,22 +1398,24 @@ function liveDeps(
trustedRepositories: string[],
): Deps {
const trusted = trustedRepositories.map((name) => name.toLowerCase());
- return {
- ancestors: (head) =>
- exec([
- "git",
- "rev-list",
- "--first-parent",
- `--max-count=${MAX_ANCESTORS}`,
- head,
- ])
- .split("\n")
- .filter(Boolean),
- passed: (sha) => {
- const names = new Set();
- const runs = (
+ const { remaining, run: historyCommand } = historyCommands(45_000);
+ 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);
+ if (cached) return cached;
+ const trees = new Map>();
+ records.set(sha, trees);
+ if (remaining() <= 0) return trees;
+ let runs: ApiRun[];
+ try {
+ runs = (
JSON.parse(
- exec([
+ historyCommand([
"gh",
"api",
`repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`,
@@ -1044,20 +1427,113 @@ function liveDeps(
run.id !== currentRun &&
trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""),
);
- for (const run of runs) {
- const jobs = JSON.parse(
- exec([
+ } 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 {
+ historyCommand([
"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);
+ "run",
+ "download",
+ String(run.id),
+ "--repo",
+ repository,
+ "--name",
+ `ci-tested-tree-${run.id}`,
+ "--dir",
+ directory,
+ ]);
+ tree = testedCheckout(
+ workflow,
+ sha,
+ run.event,
+ readFileSync(join(directory, "ci-tested-tree.txt"), "utf8"),
+ );
+ if (!tree) continue;
+ const present = () => {
+ try {
+ // cat-file may lazily fetch an absent object in a partial clone, so it shares the
+ // remote-history deadline too. Missing objects still get the explicit fetch below.
+ historyCommand(["git", "cat-file", "-e", `${tree}^{commit}`]);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ if (!present()) {
+ historyCommand([
+ "git",
+ "fetch",
+ "--no-tags",
+ "--filter=blob:none",
+ "origin",
+ tree,
+ ]);
+ if (!present()) continue;
+ }
+ } catch {
+ continue;
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
}
}
- return names;
- },
+ if (!tree) continue;
+ 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.
+ }
+ }
+ return trees;
+ };
+ return {
+ testedTrees: (sha, checks) =>
+ [...recordsAt(sha)]
+ .filter(([, names]) => checks.every((check) => names.has(check)))
+ .map(([tree]) => tree),
+ ancestors: (head) =>
+ exec([
+ "git",
+ "rev-list",
+ "--first-parent",
+ `--max-count=${MAX_ANCESTORS}`,
+ head,
+ ])
+ .split("\n")
+ .filter(Boolean),
+ passed: (sha) =>
+ new Set([...recordsAt(sha).values()].flatMap((names) => [...names])),
diff: (from, to) => {
const out = exec([
"git",
@@ -1092,7 +1568,7 @@ function liveDeps(
"*.test.ts",
"*.test.tsx",
],
- true,
+ 1,
)
.split("\0")
.filter((file) => file && isBunTest(file));
@@ -1160,9 +1636,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 };
@@ -1170,21 +1647,29 @@ 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, 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 };
+ 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 {
+ fetchCommand([
+ "git",
+ "fetch",
+ "--no-tags",
+ "--filter=blob:none",
+ "origin",
+ `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`,
+ ]);
+ fetchCommand(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]);
+ return { labels, head: pull.head.sha };
+ } catch (error) {
+ return {
+ labels,
+ noHead: `its head could not be fetched: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
} catch {
return undefined;
}
@@ -1215,13 +1700,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;
}
@@ -1243,6 +1736,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
@@ -1256,8 +1750,30 @@ 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,
};
+ 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 =
@@ -1282,6 +1798,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(
@@ -1297,6 +1814,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),
},
);
@@ -1315,11 +1833,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/ci-run-tests.test.ts b/scripts/ci-run-tests.test.ts
new file mode 100644
index 0000000000..31fd84f24d
--- /dev/null
+++ b/scripts/ci-run-tests.test.ts
@@ -0,0 +1,202 @@
+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";
+
+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 {
+ 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;
}
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 839707f377..ccf1e4e0c7 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("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"),
);
@@ -285,7 +285,29 @@ 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);
+ // 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);
+ }
});
});