From 36847223443a2e671eabc6c3451163953097592a Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:06:06 -0800 Subject: [PATCH 01/17] CI: reuse tested merge trees and run browser engines separately --- .github/ci-budgets.json | 1 + .github/workflows/ci.yml | 26 ++++- scripts/ci-changes.test.ts | 76 +++++++++++++++ scripts/ci-changes.ts | 194 +++++++++++++++++++++++++++++-------- 4 files changed, 253 insertions(+), 44 deletions(-) diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json index f220da6538..cfc92d785f 100644 --- a/.github/ci-budgets.json +++ b/.github/ci-budgets.json @@ -7,6 +7,7 @@ "API spec": 3, "native types": 3, "app (real browser)": 8, + "app (real browser, Chromium)": 12, "app (real browser, WebKit)": 12, "app (real browser, desktop setup window)": 12, "tests (shard N of N)": 7, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7a4580907..dde89693a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -100,6 +100,18 @@ jobs: # Strings, since 0 is falsy and `&& 0 || 1` would always give 1. fetch-depth: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '0' || '1' }} filter: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && 'blob:none' || '' }} + # The run API names the PR head, while these jobs test its merge with main. Keep the actual + # checkout commit so a later merge group compares against the tree the jobs really tested. + - name: Record the tested checkout + if: github.event_name == 'pull_request' + run: git rev-parse HEAD > "$RUNNER_TEMP/ci-tested-tree.txt" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: github.event_name == 'pull_request' + with: + name: ci-tested-tree-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-tested-tree.txt + retention-days: 14 + overwrite: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: bun-version: 1.4.3 @@ -597,7 +609,13 @@ jobs: # instead of 5, and the job has an hour. A test's own timeout and every bound a test asserts stay # as they are. On the larger runners nothing changes: eight workers, 5 seconds, 30 minutes. app-browser-webkit: - name: app (real browser, WebKit) + name: app (real browser, ${{ matrix.engine }}) + # Each engine keeps all its coverage, on its own runner. A failure reruns only that engine, + # and eight workers no longer host Chromium and WebKit together on the same runner. + strategy: + fail-fast: false + matrix: + engine: [Chromium, WebKit] needs: changes # On a pull request, only when the app, what it imports or its tests change (scripts/ci-changes.ts, # app_browser_webkit). A merge group and main run it every time. @@ -613,6 +631,7 @@ jobs: PLAYWRIGHT_IMAGE: mcr.microsoft.com/playwright:v1.62.1-noble@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e TEST_WORKERS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '2' || '8' }} TEST_TIMEOUT_MS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '15000' || '5000' }} + BROWSER_ENGINE: ${{ matrix.engine == 'WebKit' && 'webkit' || 'chromium' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -695,12 +714,13 @@ jobs: docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ - --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \ + --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES="$BROWSER_ENGINE" \ "$PLAYWRIGHT_IMAGE" \ bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" "${files[@]}" # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. # Only that test: the rest of the file runs in Chromium in the job above. - - run: | + - if: matrix.engine == 'WebKit' + run: | docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index f8c893b1eb..72aa73f53c 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -23,6 +23,7 @@ import { queuedPullRequest, SHARDS, SUITE_RULE, + testedCheckout, } from "./ci-changes"; import type { CiRun } from "./release-ci-gate"; @@ -858,6 +859,32 @@ describe("a merge group", () => { const COMPONENTS = CI_RULES.find((rule) => rule.output === "components") ?.checks as string[]; const GROUP: MergeGroup = { head: "g", pr: { labels: [], head: "h" } }; + + test("compares a PR's passing jobs with its tested merge tree, never its untested head", () => { + // h needs a fix on main. CI passed on merge m with that fix. Main later reverted it: + // g equals h, but differs from the actual passing merge m, so its checks are owed. + const base = groupDeps({ + passed: { b: ALL_CI, h: ALL_CI }, + changes: { b: ["app/src/feature.ts"], h: [], m: ["shared/fix.ts"] }, + }); + const proof = { + ...base, + testedTrees: (sha: string) => + sha === "h" ? ["m"] : sha === "b" ? ["b"] : [], + }; + const result = decideMergeGroup("ci", ["app/src/feature.ts"], proof, GROUP); + expect(result.run.suite).toBe(true); + expect(result.run.app_browser).toBe(true); + expect(result.run.build).toBe(true); + }); + + test("full-ci forces checks even for docs alone", () => { + const result = decideMergeGroup("ci", ["README.md"], REAL, { + head: "g", + pr: { labels: ["full-ci"] }, + }); + expect(running(result)).toEqual(everyJob); + }); /** The pull request changed the app; main changed a harness since the pull request branched. */ const APP_PR_HARNESS_MAIN = { passed: { @@ -967,6 +994,30 @@ describe("a merge group", () => { }); }); +describe("the checkout a passing run proves", () => { + const head = "a".repeat(40); + const merge = "b".repeat(40); + test("CI's PR run requires its recorded merge commit, with no fallback to its head", () => { + expect(testedCheckout("ci", head, "pull_request")).toBeUndefined(); + expect(testedCheckout("ci", head, "pull_request", `${merge}\n`)).toBe( + merge, + ); + for (const invalid of ["", "main", "b".repeat(39), `${merge}\n${head}`]) { + expect( + testedCheckout("ci", head, "pull_request", invalid), + ).toBeUndefined(); + } + }); + test("main and merge groups prove their SHA, and Desktop explicitly tests the PR head", () => { + expect(testedCheckout("ci", head, "push")).toBe(head); + expect(testedCheckout("ci", head, "merge_group")).toBe(head); + expect(testedCheckout("desktop", head, "pull_request")).toBe(head); + expect( + testedCheckout("ci", head, "pull_request_target", merge), + ).toBeUndefined(); + }); +}); + describe("main's run of a push", () => { const SHA = "cad6dc08eb158054ed3fc37c0aa7b9d0cb3dc4eb"; const REPOSITORY = "CopilotKit/OpenBot"; @@ -1273,6 +1324,31 @@ function jobNames(workflow: string): string[] { } describe("the rules name the jobs the workflows run", () => { + test("the cross-browser list runs each engine in a separate job, retaining both required results", () => { + const ci = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: Record< + string, + { + strategy?: { matrix?: { engine?: string[] }; "fail-fast"?: boolean }; + steps: { run?: string; if?: string }[]; + } + >; + }; + const job = ci.jobs["app-browser-webkit"]; + expect(job.strategy?.matrix?.engine).toEqual(["Chromium", "WebKit"]); + expect(job.strategy?.["fail-fast"]).toBe(false); + const rule = CI_RULES.find((rule) => rule.output === "app_browser_webkit"); + expect(rule?.checks).toEqual([ + "app (real browser, Chromium)", + "app (real browser, WebKit)", + ]); + const clipboard = job.steps.find((step) => + step.run?.includes("copies with one press"), + ); + expect(clipboard?.if).toBe("matrix.engine == 'WebKit'"); + }); test("ci.yml: every check a rule waits on is a job, and the shards are the matrix's", () => { const names = jobNames("ci.yml"); for (const check of ALL_CI) expect(names).toContain(check); diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index a311ff90d1..d4bf05b6a5 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -47,7 +47,8 @@ */ import { randomBytes } from "node:crypto"; -import { appendFileSync, readFileSync } from "node:fs"; +import { appendFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { changedFiles } from "./release-candidate-check"; import { @@ -258,7 +259,7 @@ export const CI_RULES: Rule[] = [ // the packages the app imports and its own tests, and no server: a pull request runs it when one // of those changes. A merge group and main run it every time. output: "app_browser_webkit", - checks: ["app (real browser, WebKit)"], + checks: ["app (real browser, Chromium)", "app (real browser, WebKit)"], reads: (path) => (isCode(path) && appInputs(path)) || ciInputs(path), }, { @@ -375,6 +376,8 @@ export type PullRequest = { headRepository: string; repository: string; head: string; + /** The actual CI checkout (a PR's synthetic merge). Desktop's jobs test the head itself. */ + checkout?: string; base: string; }; @@ -385,6 +388,8 @@ export type Deps = { ancestors: (head: string) => string[]; /** The job names that passed on a commit in this workflow's runs, the current run left out. */ passed: (sha: string) => Set; + /** Actual checkout trees where these jobs passed, rather than the run's PR head SHA. */ + testedTrees?: (sha: string, checks: string[]) => string[]; /** What changed between two commits. */ diff: (from: string, to: string) => Change[]; /** The suite's test files that name any of these paths. */ @@ -481,7 +486,12 @@ export function decide( // A release PR that changes more than the release files is checked like any other PR. } - return decideFrom(workflow, pr.head, [deps.ancestors(pr.head)], deps); + return decideFrom( + workflow, + pr.checkout ?? pr.head, + [deps.ancestors(pr.head)], + deps, + ); } /** @@ -509,14 +519,17 @@ function decideFrom( }; /** Along each history, the newest commit where every one of these checks passed. */ const baselinesOf = (checks: string[]) => - histories - .map((ancestors) => - ancestors.find((sha) => { - const names = passed(sha); - return checks.every((check) => names.has(check)); - }), - ) - .filter((sha): sha is string => sha !== undefined); + histories.flatMap((ancestors) => { + for (const sha of ancestors) { + const trees = deps.testedTrees + ? deps.testedTrees(sha, checks) + : checks.every((check) => passed(sha).has(check)) + ? [sha] + : []; + if (trees.length > 0) return trees; + } + return []; + }); const changesSince = new Map(); const since = (sha: string) => { let changes = changesSince.get(sha); @@ -894,6 +907,16 @@ export function decideMergeGroup( group?: MergeGroup, ): Decision & { ignoredOnly: boolean } { const rules = rulesOf(workflow); + // The explicit override applies even when every changed file is a document. + if (group?.pr?.labels.includes("full-ci")) { + return { + ...everything( + rules, + "A merge group of a pull request labelled full-ci: everything runs.", + ), + ignoredOnly: false, + }; + } // A file no job's rule reads: CHANGELOG.md, and the docs. A test that names a doc still runs. const unread = (path: string) => isIgnored(path) || @@ -964,6 +987,7 @@ export function decideMergeGroup( const decision = decideFrom(workflow, group.head, histories, { ancestors, passed, + testedTrees: deps.testedTrees, diff, releaseViolations, mentions: deps.mentions, @@ -998,10 +1022,31 @@ function exec(cmd: string[], allowFailure = false): string { type ApiRun = { id: number; path: string; + event: string; + run_attempt: number; head_repository?: { full_name?: string } | null; }; type ApiJob = { name: string; conclusion: string | null }; +/** The run API's SHA proves CI's PR head only when checkout explicitly used it (Desktop). */ +export function testedCheckout( + workflow: Workflow, + head: string, + event: string, + proof?: string, +): string | undefined { + const sha = /^[0-9a-f]{40}$/; + if (!sha.test(head)) return undefined; + if ( + workflow === "desktop" || + ["push", "merge_group", "schedule", "workflow_dispatch"].includes(event) + ) + return head; + if (event === "pull_request" && sha.test(proof?.trim() ?? "")) + return proof?.trim(); + return undefined; +} + function liveDeps( workflow: Workflow, repository: string, @@ -1009,7 +1054,101 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); + const records = new Map>>(); + const recordsAt = (sha: string): Map> => { + const cached = records.get(sha); + if (cached) return cached; + const trees = new Map>(); + const runs = ( + JSON.parse( + exec([ + "gh", + "api", + `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, + ]), + ).workflow_runs as ApiRun[] + ).filter( + (run) => + run.path === WORKFLOW_PATH[workflow] && + run.id !== currentRun && + trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), + ); + for (const run of runs) { + let tree = testedCheckout(workflow, sha, run.event); + if (workflow === "ci" && run.event === "pull_request") { + // Actions attributes this run to the PR head, but checkout tested its temporary merge. + // Runs before this proof existed, expired artifacts and unreachable trees never stand in. + const directory = mkdtempSync(join(tmpdir(), "openbot-ci-tree-")); + try { + const downloaded = Bun.spawnSync( + [ + "gh", + "run", + "download", + String(run.id), + "--repo", + repository, + "--name", + `ci-tested-tree-${run.id}-${run.run_attempt}`, + "--dir", + directory, + ], + { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, + ); + if (downloaded.exitCode !== 0) continue; + tree = testedCheckout( + workflow, + sha, + run.event, + readFileSync(join(directory, "ci-tested-tree.txt"), "utf8"), + ); + if (!tree) continue; + const present = () => + Bun.spawnSync(["git", "cat-file", "-e", `${tree}^{commit}`], { + stdout: "pipe", + stderr: "pipe", + }).exitCode === 0; + if (!present()) { + const fetched = Bun.spawnSync( + [ + "git", + "fetch", + "--no-tags", + "--filter=blob:none", + "origin", + tree, + ], + { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, + ); + if (fetched.exitCode !== 0 || !present()) continue; + } + } catch { + continue; + } finally { + rmSync(directory, { recursive: true, force: true }); + } + } + if (!tree) continue; + const names = trees.get(tree) ?? new Set(); + const jobs = JSON.parse( + exec([ + "gh", + "api", + `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, + ]), + ).jobs as ApiJob[]; + for (const job of jobs) + if (job.conclusion === "success") names.add(job.name); + trees.set(tree, names); + } + records.set(sha, trees); + return trees; + }; return { + testedTrees: (sha, checks) => + [...recordsAt(sha)] + .filter(([, names]) => checks.every((check) => names.has(check))) + .map(([tree]) => tree), ancestors: (head) => exec([ "git", @@ -1020,36 +1159,8 @@ function liveDeps( ]) .split("\n") .filter(Boolean), - passed: (sha) => { - const names = new Set(); - const runs = ( - JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, - ]), - ).workflow_runs as ApiRun[] - ).filter( - (run) => - run.path === WORKFLOW_PATH[workflow] && - run.id !== currentRun && - trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), - ); - for (const run of runs) { - const jobs = JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, - ]), - ).jobs as ApiJob[]; - for (const job of jobs) { - if (job.conclusion === "success") names.add(job.name); - } - } - return names; - }, + passed: (sha) => + new Set([...recordsAt(sha).values()].flatMap((names) => [...names])), diff: (from, to) => { const out = exec([ "git", @@ -1248,6 +1359,7 @@ if (import.meta.main) { headRepository: pull.head.repo?.full_name ?? "", repository, head: pull.head.sha, + checkout: workflow === "ci" ? process.env.GITHUB_SHA : undefined, base: pull.base.sha, }; // main's own run of a push. Not the release's call of these checks, which sees the push that From 3baeceb6511c88d0c022b31205b54838c8cb1984 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:15:39 -0800 Subject: [PATCH 02/17] CI: preserve required coverage when reusing passing checks --- .github/workflows/ci.yml | 10 +- scripts/ci-changes.test.ts | 392 ++++++++++++++++++++++++++++++++++- scripts/ci-changes.ts | 88 ++++++-- scripts/ci-run-tests.test.ts | 154 ++++++++++++++ scripts/ci-run-tests.ts | 9 + 5 files changed, 622 insertions(+), 31 deletions(-) create mode 100644 scripts/ci-run-tests.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dde89693a2..167a833fc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,8 +54,9 @@ jobs: # files alone run just those tests, docs alone run only the tests that name them, and a release PR # of only the release files runs the checks publishing re-runs on it. main's run of a commit the # merge queue merged skips the checks the queue's run already passed on that same commit, and runs - # only `component dockerfile` and any job whose cache key the push changed, which write the caches - # pull requests read. A merge group is decided like a pull request, from main's history and the + # only `component dockerfile`, any job whose cache key the push changed, and startup when the queue + # ran Windows but omitted macOS. The first two write caches pull requests read. A merge group is + # decided like a pull request, from main's history and the # queued pull request's: a job runs unless nothing it reads changed since it passed on one of them. # A push to main the queue did not pass, the release's own call of these checks and a pull request # labelled `full-ci` (in its own runs and in the queue) run everything. CHANGELOG.md is never a @@ -108,7 +109,8 @@ jobs: - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'pull_request' with: - name: ci-tested-tree-${{ github.run_id }}-${{ github.run_attempt }} + # Re-running only a failed check retains changes' original proof artifact. + name: ci-tested-tree-${{ github.run_id }} path: ${{ runner.temp }}/ci-tested-tree.txt retention-days: 14 overwrite: true @@ -916,7 +918,7 @@ jobs: if: needs.changes.outputs.browser_tests != '[]' || needs.changes.outputs.desktop_browser_tests != '[]' run: bunx playwright-core install --with-deps --no-shell chromium - name: Install WebKit - if: needs.changes.outputs.webkit_tests != '[]' + if: needs.changes.outputs.webkit_tests != '[]' || contains(fromJSON(needs.changes.outputs.desktop_browser_tests), 'desktop/src/setupLayout.browser.test.ts') run: bunx playwright-core install --with-deps webkit - name: Run the changed tests env: diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 72aa73f53c..ac33818e4b 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1,5 +1,14 @@ import { describe, expect, test } from "bun:test"; -import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { CACHE_WRITERS, @@ -125,6 +134,114 @@ const isBrowserFile = (file: string) => /** This checkout, as the merge group's `changes` job reads it. */ const REAL = { mentions: realMentions, read: readTracked }; +/** Runs the real Actions entry point with a local repository and recorded GitHub responses. */ +function actionsDecision(options: { + event: "pull_request" | "merge_group" | "push"; + responses: (sha: string) => Record; + proof?: boolean | string; +}) { + const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); + try { + const git = (...args: string[]) => { + const result = Bun.spawnSync(["git", ...args], { cwd: directory }); + if (result.exitCode !== 0) throw new Error(result.stderr.toString()); + return result.stdout.toString().trim(); + }; + git("init", "--quiet"); + git( + "-c", + "user.name=CI", + "-c", + "user.email=ci@example.test", + "commit", + "--quiet", + "--allow-empty", + "-m", + "test", + ); + const sha = git("rev-parse", "HEAD"); + const repository = "CopilotKit/OpenBot"; + const fixture = join(directory, "fixture.json"); + writeFileSync( + fixture, + JSON.stringify({ + responses: options.responses(sha), + proof: options.proof, + sha, + }), + ); + const gh = join(directory, "gh"); + writeFileSync( + gh, + `#!${process.execPath} +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +const fixture = JSON.parse(readFileSync(process.env.CI_FIXTURE, "utf8")); +const args = process.argv.slice(2); +if (args[0] === "run" && args[1] === "download") { + if (!fixture.proof || args[args.indexOf("--name") + 1] !== "ci-tested-tree-1") process.exit(1); + writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), typeof fixture.proof === "string" ? fixture.proof : fixture.sha); +} else { + const endpoint = args.find((arg) => arg.startsWith("repos/")); + if (!(endpoint in fixture.responses)) process.exit(1); + const response = fixture.responses[endpoint]; + console.log(JSON.stringify(args.includes("--slurp") && !Array.isArray(response) ? [response] : response)); +} +`, + ); + chmodSync(gh, 0o755); + const event = join(directory, "event.json"); + writeFileSync( + event, + JSON.stringify({ + before: "b".repeat(40), + pull_request: { + labels: [], + head: { ref: "fix", sha, repo: { full_name: repository } }, + base: { sha }, + }, + merge_group: { + base_sha: "b".repeat(40), + head_sha: sha, + head_ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha}`, + }, + }), + ); + const output = join(directory, "outputs"); + const result = Bun.spawnSync( + [process.execPath, join(ROOT, "scripts/ci-changes.ts"), "ci"], + { + cwd: directory, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH}`, + CI_FIXTURE: fixture, + GITHUB_EVENT_NAME: options.event, + GITHUB_EVENT_PATH: event, + GITHUB_REPOSITORY: repository, + GITHUB_SHA: sha, + GITHUB_REF: + options.event === "push" ? "refs/heads/main" : "refs/pull/7/merge", + GITHUB_RUN_ID: "2", + WORKFLOW_NAME: "CI", + GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: "", + }, + }, + ); + expect(result.exitCode).toBe(0); + return Object.fromEntries( + [ + ...readFileSync(output, "utf8").matchAll( + /^(\w+)<<([^\n]+)\n([^\n]*)\n\2$/gm, + ), + ].map((match) => [match[1], match[3]]), + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + const PR: PullRequest = { labels: [], headRef: "fix/a-thing", @@ -252,6 +369,48 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("compares the current PR's tested synthetic merge rather than its head", () => { + const base = deps({ passed: { c2: ALL_CI }, changes: {} }); + const decision = decide( + "ci", + { ...PR, checkout: "merge" }, + { + ...base, + diff: (from, to) => { + expect(from).toBe("c2"); + return to === "merge" + ? [{ path: "app/src/main.tsx", deleted: false }] + : []; + }, + }, + ); + expect(decision.run.suite).toBe(true); + }); + + test("a suite whose shards passed but aggregate failed must run again", () => { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI.filter((check) => check !== "tests") }, + changes: { c2: ["README.md"] }, + }), + ); + expect(decision.run.suite).toBe(true); + }); + + test("API examples read by the WebKit clipboard scenario require its browser jobs", () => { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: ["api/openapi.yaml"] }, + }), + ); + expect(decision.run.app_browser_webkit).toBe(true); + }); + test("one test file changed since a green push runs that test and the lint, nothing else", () => { const decision = decide( "ci", @@ -734,6 +893,53 @@ describe("CHANGELOG.md", () => { describe("a merge group", () => { const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); + test("a source file renamed to a document cannot use the docs-only shortcut", () => { + const result = actionsDecision({ + event: "merge_group", + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + files: [ + { + filename: "README.md", + previous_filename: "server/src/main.ts", + status: "renamed", + }, + ], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { workflow_runs: [] }, + }), + }); + expect(result.ignored_only).toBe("false"); + expect(result.suite).toBe("true"); + expect(result.build).toBe("true"); + }); + + test("rename expansion does not mistake 150 complete API entries for the 300-file cap", () => { + const result = actionsDecision({ + event: "merge_group", + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + files: Array.from({ length: 150 }, (_, index) => ({ + filename: `docs/new-${index}.md`, + previous_filename: `docs/old-${index}.md`, + status: "renamed", + })), + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + }), + }); + expect(result.ignored_only).toBe("true"); + expect(result.suite).toBe("false"); + }); + test("that changes only CHANGELOG.md runs nothing, not even the tests that name it", () => { const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL); expect(running(decision)).toEqual([]); @@ -995,6 +1201,74 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("a successful partial rerun reuses the original run-scoped checkout proof", () => { + const result = actionsDecision({ + event: "pull_request", + proof: true, + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + path: ".github/workflows/ci.yml", + event: "pull_request", + run_attempt: 2, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + }), + }); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + }); + + test("missing or malformed artifacts cannot stand in for a tested checkout", () => { + for (const proof of [false, "not a commit"]) { + const result = actionsDecision({ + event: "pull_request", + proof, + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + path: ".github/workflows/ci.yml", + event: "pull_request", + run_attempt: 2, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + }), + }); + expect(result.suite).toBe("true"); + expect(result.static).toBe("true"); + } + }); + + test("the proof uploader uses the same run-scoped name across attempts", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: { + changes: { steps: { uses?: string; with?: { name?: string } }[] }; + }; + }; + const artifact = workflow.jobs.changes.steps.find((step) => + step.uses?.startsWith("actions/upload-artifact@"), + ); + expect(artifact?.with?.name).toBe( + `ci-tested-tree-${expression("github.run_id")}`, + ); + }); + const head = "a".repeat(40); const merge = "b".repeat(40); test("CI's PR run requires its recorded merge commit, with no fallback to its head", () => { @@ -1037,11 +1311,101 @@ describe("main's run of a push", () => { }); const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); - test("a commit the merge queue passed runs none of the checks again, and names the queue's run", () => { - const decision = decideMainPush([ciRun()], SHA, REPOSITORY, [ - "app/src/lib/marks.ts", + test("main runs the macOS startup omitted by a queue that ran Windows startup", () => { + const decision = decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["app/src/main.tsx"], + () => [{ name: "startup (windows-latest)", conclusion: "success" }], + ); + expect(running(decision)).toEqual(["startup"]); + }); + + test("main reuses a queue's safely skipped startup", () => { + const decision = decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["app/src/main.tsx"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ); + expect(running(decision)).toEqual([]); + }); + + test("main reuses an explicitly skipped whole startup matrix", () => { + const decision = decideMainPush([ciRun()], SHA, REPOSITORY, [], () => [ + { name: `startup (${expression("matrix.os")})`, conclusion: "skipped" }, ]); expect(running(decision)).toEqual([]); + }); + + test("main runs startup when queue jobs are missing or unreadable", () => { + for (const read of [ + () => [], + () => { + throw new Error("unreadable jobs"); + }, + ]) { + expect( + decideMainPush([ciRun()], SHA, REPOSITORY, [], read).run.startup, + ).toBe(true); + } + }); + + test("main reads every page of actual queue jobs and handles unreadable results", () => { + for (const conclusion of ["success", "skipped", undefined]) { + const result = actionsDecision({ + event: "push", + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/workflows/ci.yml/runs?head_sha=${sha}&event=merge_group&per_page=100`]: + { workflow_runs: [ciRun({ id: 1, head_sha: sha })] }, + [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + files: [{ filename: "app/src/main.tsx" }], + }, + ...(conclusion + ? { + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + [ + { jobs: [{ name: "build", conclusion: "success" }] }, + { + jobs: [{ name: "startup (windows-latest)", conclusion }], + }, + ], + } + : {}), + }), + }); + expect(result.startup).toBe(conclusion === "skipped" ? "false" : "true"); + expect(result.suite).toBe("false"); + } + }); + + test("the latest attempt's explicit startup skip supersedes older queue attempts", () => { + const result = decideMainPush([ciRun()], SHA, REPOSITORY, [], () => [ + { + name: "startup (windows-latest)", + conclusion: "success", + run_attempt: 1, + }, + { + name: "startup (windows-latest)", + conclusion: "skipped", + run_attempt: 2, + }, + ]); + expect(result.run.startup).toBe(false); + }); + + test("a commit the merge queue passed runs none of the checks again, and names the queue's run", () => { + const decision = decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["app/src/lib/marks.ts"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ); + expect(running(decision)).toEqual([]); expect(decision.queueRun?.html_url).toBe( "https://github.com/CopilotKit/OpenBot/actions/runs/46561913641", ); @@ -1081,16 +1445,24 @@ describe("main's run of a push", () => { test("a queue-tested push still runs the jobs whose cache key it changed", () => { expect( running( - decideMainPush([ciRun()], SHA, REPOSITORY, [ - "mobile/package-lock.json", - ]), + decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["mobile/package-lock.json"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ), ), ).toEqual(["mobile"]); expect( running( - decideMainPush([ciRun()], SHA, REPOSITORY, [ - "agent-crewai/requirements.txt", - ]), + decideMainPush( + [ciRun()], + SHA, + REPOSITORY, + ["agent-crewai/requirements.txt"], + () => [{ name: "startup (windows-latest)", conclusion: "skipped" }], + ), ), ).toEqual(["python_harness"]); // Files it could not read run every job that writes a cache, never a check it can skip less. diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index d4bf05b6a5..0963125531 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -24,7 +24,8 @@ * * main's own run of a commit the merge queue merged runs none of CI's checks again: the queue's run * tested that very commit, so it skips them and names that run (decideMainPush), keeping only the - * jobs that write a cache the push changed the key of. A push the queue did not test (an admin's + * jobs that write a cache the push changed the key of, and macOS startup when the queue ran only + * Windows. A push the queue did not test (an admin's * merge, a direct push) runs everything. A merge group (decideMergeGroup) runs nothing when all it * changes is files no check reads (CHANGELOG.md, docs no test names); otherwise each job is decided * from two histories, main's and the queued pull request's, and runs unless nothing it reads changed @@ -176,6 +177,8 @@ const appInputs = matcher( "tests/**", "desktop/src/**", "scripts/**", + // connect-your-ai's browser fixture reads the API's own response examples. + "api/openapi.yaml", "package.json", "bun.lock", "bunfig.toml", @@ -318,13 +321,16 @@ export const CI_RULES: Rule[] = [ }, ]; -/** The suite: every shard must have passed on the commit it stands in from. */ +/** The suite: every shard and the aggregate count/floor check must have passed. */ export const SUITE_RULE: Rule = { output: "suite", - checks: Array.from( - { length: SHARDS }, - (_, index) => `tests (shard ${index + 1} of ${SHARDS})`, - ), + checks: [ + ...Array.from( + { length: SHARDS }, + (_, index) => `tests (shard ${index + 1} of ${SHARDS})`, + ), + "tests", + ], reads: isCode, }; @@ -789,9 +795,9 @@ export function queueRunAt( /** * Decides main's run of CI for a push. A commit the merge queue merged is the very commit the queue's - * run tested, so when that run passed nothing is run again but the jobs that write a cache whose key - * this push changed. `pushed` is the files the push changed, or undefined when they could not be read, - * which runs every cache writer. Any other push (an admin's merge past the queue, a direct push) runs + * run tested, so when that run passed only startup coverage omitted by the queue and the jobs that + * write a cache whose key this push changed run. `pushed` is the files the push changed, or undefined + * when they could not be read, which runs every cache writer. Any other push (an admin's merge past the queue, a direct push) runs * everything, as before. */ export function decideMainPush( @@ -799,6 +805,7 @@ export function decideMainPush( sha: string, repository: string, pushed: string[] | undefined, + queueJobs?: (run: CiRun) => ApiJob[], ): Decision & { queueRun?: CiRun } { const queueRun = queueRunAt(runs, sha, repository); if (!queueRun) { @@ -812,6 +819,30 @@ export function decideMainPush( const reasons = [ `Tested in the merge queue: ${queueRun.html_url}. Its checks are not run again on the same commit.`, ]; + // A queue that runs startup omits macOS. Only an explicitly skipped Windows job (or the whole + // matrix) proves it reused a baseline for both platforms. Missing/unreadable jobs owe startup too. + try { + const startup = queueJobs?.(queueRun) + .filter( + (job) => + job.name === "startup (windows-latest)" || + job.name === `startup (\${{ matrix.os }})`, + ) + .sort((a, b) => (b.run_attempt ?? 0) - (a.run_attempt ?? 0))[0]; + run.startup = startup?.conclusion !== "skipped"; + if (run.startup) { + reasons.push( + startup?.conclusion === "success" + ? "startup: runs, the merge queue tested Windows but omitted macOS." + : "startup: runs, the merge queue's skipped startup could not be proved.", + ); + } + } catch (error) { + run.startup = true; + reasons.push( + `startup: runs, the merge queue's jobs could not be read: ${String(error)}.`, + ); + } for (const writer of CACHE_WRITERS) { const changed = pushed?.filter(writer.key); if (changed && changed.length === 0) continue; @@ -1026,7 +1057,21 @@ type ApiRun = { run_attempt: number; head_repository?: { full_name?: string } | null; }; -type ApiJob = { name: string; conclusion: string | null }; +type ApiJob = { name: string; conclusion: string | null; run_attempt?: number }; + +/** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ +function jobsOf(repository: string, run: CiRun): ApiJob[] { + const pages = JSON.parse( + exec([ + "gh", + "api", + "--paginate", + "--slurp", + `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, + ]), + ) as { jobs: ApiJob[] }[]; + return pages.flatMap((page) => page.jobs); +} /** The run API's SHA proves CI's PR head only when checkout explicitly used it (Desktop). */ export function testedCheckout( @@ -1089,7 +1134,7 @@ function liveDeps( "--repo", repository, "--name", - `ci-tested-tree-${run.id}-${run.run_attempt}`, + `ci-tested-tree-${run.id}`, "--dir", directory, ], @@ -1318,13 +1363,21 @@ function pushedFiles( ): string[] | undefined { if (!before || /^0+$/.test(before)) return undefined; try { - const files = ( - JSON.parse( - exec(["gh", "api", `repos/${repository}/compare/${before}...${sha}`]), - ).files ?? [] - ).map((file: { filename: string }) => file.filename) as string[]; + const files = (JSON.parse( + exec(["gh", "api", `repos/${repository}/compare/${before}...${sha}`]), + ).files ?? []) as { filename: string; previous_filename?: string }[]; // The compare API lists at most 300 files. - return files.length < 300 ? files : undefined; + if (files.length >= 300) return undefined; + // A rename removes its old path too. A source file moved into docs must not look docs-only. + return [ + ...new Set( + files.flatMap((file) => + file.previous_filename + ? [file.filename, file.previous_filename] + : [file.filename], + ), + ), + ]; } catch { return undefined; } @@ -1386,6 +1439,7 @@ if (import.meta.main) { sha, repository, pushedFiles(repository, event.before, sha), + (run) => jobsOf(repository, run), ); } else if (eventName === "merge_group" && event.merge_group) { decision = decideMergeGroup( diff --git a/scripts/ci-run-tests.test.ts b/scripts/ci-run-tests.test.ts new file mode 100644 index 0000000000..aac9487dc1 --- /dev/null +++ b/scripts/ci-run-tests.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, test } from "bun:test"; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { data, Evaluator, Lexer, Parser } from "@actions/expressions"; + +const ROOT = join(import.meta.dir, ".."); +const SETUP_TEST = "desktop/src/setupLayout.browser.test.ts"; + +function runDesktopTests(files: string[], failWebKit = false) { + const directory = mkdtempSync(join(tmpdir(), "openbot-ci-run-tests-")); + try { + mkdirSync(join(directory, "desktop/src"), { recursive: true }); + for (const file of files) writeFileSync(join(directory, file), ""); + const log = join(directory, "calls.jsonl"); + const bun = join(directory, "bun"); + writeFileSync( + bun, + `#!${process.execPath} +import { appendFileSync } from "node:fs"; +appendFileSync(process.env.TEST_CALLS, JSON.stringify({ + args: process.argv.slice(2), cwd: process.cwd(), + browser: process.env.OPENBOT_APP_BROWSER, + engine: process.env.OPENBOT_APP_ENGINE ?? "chromium", +}) + "\\n"); +console.error("Ran 1 test across 1 file."); +if (process.env.FAIL_WEBKIT === "1" && process.env.OPENBOT_APP_ENGINE === "webkit") process.exit(1); +`, + ); + chmodSync(bun, 0o755); + const result = Bun.spawnSync( + [process.execPath, join(ROOT, "scripts/ci-run-tests.ts")], + { + cwd: directory, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH}`, + TEST_CALLS: log, + FAIL_WEBKIT: failWebKit ? "1" : "0", + TESTS: "[]", + BROWSER_TESTS: "[]", + WEBKIT_TESTS: "[]", + DESKTOP_BROWSER_TESTS: JSON.stringify(files), + OPENBOT_APP_ENGINE: "", + }, + }, + ); + const calls = readFileSync(log, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)) as { + args: string[]; + cwd: string; + browser: string; + engine: string; + }[]; + return { + status: result.exitCode, + calls, + cwd: realpathSync(join(directory, "desktop")), + }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +describe("changed desktop browser tests", () => { + test("setup-window test-only edits retain the full job's WebKit scenario", () => { + const result = runDesktopTests([ + SETUP_TEST, + "desktop/src/other.browser.test.ts", + ]); + expect(result.status).toBe(0); + expect(result.calls).toEqual([ + { + args: [ + "test", + "./src/setupLayout.browser.test.ts", + "./src/other.browser.test.ts", + ], + cwd: result.cwd, + browser: "1", + engine: "", + }, + { + args: [ + "test", + "-t", + "the key field and the tab row", + "./src/setupLayout.browser.test.ts", + ], + cwd: result.cwd, + browser: "1", + engine: "webkit", + }, + ]); + }); + + test("a failed WebKit setup-window scenario fails the changed-tests job", () => { + expect(runDesktopTests([SETUP_TEST], true).status).toBe(1); + }); + + test("other desktop browser tests do not add a WebKit run", () => { + const result = runDesktopTests(["desktop/src/other.browser.test.ts"]); + expect(result.status).toBe(0); + expect(result.calls).toHaveLength(1); + }); + + test("the changed-tests job installs WebKit for the setup-window scenario", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { jobs: Record }; + const condition = workflow.jobs["changed-tests"].steps.find( + (step) => step.name === "Install WebKit", + )?.if; + expect(condition).toBeDefined(); + const tree = new Parser( + new Lexer(condition ?? "").lex().tokens, + ["needs"], + [], + ).parse(); + const needed = (desktop: string[], webkit: string[] = []) => { + const context = JSON.parse( + JSON.stringify({ + needs: { + changes: { + outputs: { + desktop_browser_tests: JSON.stringify(desktop), + webkit_tests: JSON.stringify(webkit), + }, + }, + }, + }), + data.reviver, + ) as data.Dictionary; + return new Evaluator(tree, context).evaluate(); + }; + expect(needed([SETUP_TEST])).toEqual(new data.BooleanData(true)); + expect(needed(["desktop/src/other.browser.test.ts"])).toEqual( + new data.BooleanData(false), + ); + expect(needed([], ["app/tests/browser.test.tsx"])).toEqual( + new data.BooleanData(true), + ); + }); +}); diff --git a/scripts/ci-run-tests.ts b/scripts/ci-run-tests.ts index 3712b782a2..ed15643fd0 100644 --- a/scripts/ci-run-tests.ts +++ b/scripts/ci-run-tests.ts @@ -103,6 +103,15 @@ if (import.meta.main) { desktop.map((path) => `./${path.slice("desktop/".length)}`), { cwd: "desktop", env: browserEnv }, ), + // Match the desktop browser job's WebKit coverage for test-only edits too. + await runGroup( + "Changed desktop setup-window test, in WebKit", + ["bun", "test", "-t", "the key field and the tab row"], + desktop + .filter((path) => path === "desktop/src/setupLayout.browser.test.ts") + .map((path) => `./${path.slice("desktop/".length)}`), + { cwd: "desktop", env: { ...browserEnv, OPENBOT_APP_ENGINE: "webkit" } }, + ), ]; if (results.some((passed) => !passed)) process.exitCode = 1; } From 2c1127e3e18f93ef3bd77b0d302cddef90a963cc Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:27:56 -0800 Subject: [PATCH 03/17] CI: keep browser obligations and complete reuse evidence --- .github/workflows/ci.yml | 8 +- scripts/ci-changes.test.ts | 247 +++++++++++++++++++++++++++++++++++-- scripts/ci-changes.ts | 107 +++++++++++----- 3 files changed, 320 insertions(+), 42 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 167a833fc8..bebb5d1779 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,8 @@ concurrency: jobs: # What this push has to run (scripts/ci-changes.ts). On a pull request, a job whose inputs are # unchanged since a commit where it passed is skipped, and `verify` reads the skip as a pass: test - # files alone run just those tests, docs alone run only the tests that name them, and a release PR + # files alone run just those tests (removing one reruns the suite's count floor), docs alone run + # only the tests that name them, and a release PR # of only the release files runs the checks publishing re-runs on it. main's run of a commit the # merge queue merged skips the checks the queue's run already passed on that same commit, and runs # only `component dockerfile`, any job whose cache key the push changed, and startup when the queue @@ -155,6 +156,11 @@ jobs: - run: bun run format:check - run: bun run lint - run: bun run typecheck + # Desktop is not a root workspace; its test files still belong to its TypeScript project. + - run: bun install --frozen-lockfile + working-directory: desktop + - run: bun run typecheck + working-directory: desktop - name: Desktop version tracks the release version run: bun desktop/scripts/desktop-version.ts check # What each recorded OpenBot Desktop launch hands Compose, read with this tree's diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index ac33818e4b..b9db408ca3 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -185,7 +185,7 @@ if (args[0] === "run" && args[1] === "download") { const endpoint = args.find((arg) => arg.startsWith("repos/")); if (!(endpoint in fixture.responses)) process.exit(1); const response = fixture.responses[endpoint]; - console.log(JSON.stringify(args.includes("--slurp") && !Array.isArray(response) ? [response] : response)); + console.log(JSON.stringify(args.includes("--slurp") ? (Array.isArray(response) ? response : [response]) : (Array.isArray(response) ? response[0] : response))); } `, ); @@ -369,6 +369,140 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("an outstanding WebKit test survives a docs-only push after Chromium passed", () => { + const file = "app/tests/composer-dictation-language.test.tsx"; + for (const recovered of [false, true]) { + const base = deps({ + passed: { + c2: recovered + ? ALL_CI + : ALL_CI.filter((name) => name !== "app (real browser, WebKit)"), + c1: ALL_CI, + }, + changes: { + c2: ["README.md"], + c1: ["server/src/main.ts", file, "README.md"], + }, + files: { + [file]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + }, + }); + const result = decide("ci", PR, { + ...base, + // The whole PR still includes the older edit; current passing baselines must supersede it. + diff: (from, to) => + from === PR.base + ? [{ path: file, deleted: false }] + : base.diff(from, to), + }); + expect(result.run.app_browser).toBe(false); + expect(result.run.app_browser_webkit).toBe(false); + expect(result.browserTests).toEqual(recovered ? [] : [file]); + expect(result.webkitTests).toEqual(recovered ? [] : [file]); + } + }); + + test("an edited unlisted browser file runs even when no reusable baseline exists", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + const base = deps({ passed: {}, changes: {} }); + const result = decide( + "ci", + { ...PR, checkout: "merge" }, + { + ...base, + diff: (from, to) => { + expect(from).toBe(PR.base); + expect(to).toBe("merge"); + return [{ path: file, deleted: false }]; + }, + read: () => "process.env.OPENBOT_APP_BROWSER", + }, + ); + expect(result.run.app_browser).toBe(true); + expect(result.browserTests).toEqual([file]); + expect(result.webkitTests).toEqual([file]); + }); + + test("cross-browser candidates importing their engines still run in WebKit", () => { + const file = "app/tests/with-shared-engines.test.tsx"; + const result = decide( + "ci", + PR, + deps({ + passed: { + c2: ALL_CI.filter((name) => name !== "app (real browser, WebKit)"), + c1: ALL_CI, + }, + changes: { c2: ["README.md"], c1: [file, "README.md"] }, + files: { + [file]: + 'import { engines } from "./browser-support"; process.env.OPENBOT_APP_BROWSER;', + }, + }), + ); + expect(result.browserTests).toEqual([file]); + expect(result.webkitTests).toEqual([file]); + }); + + test("mixed code and test edits run browser files outside the full jobs' fixed lists", () => { + for (const source of [false, true]) { + const app = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/another.browser.test.ts"; + const result = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { + c2: [...(source ? ["server/src/main.ts"] : []), app, desktop], + }, + files: { [app]: "process.env.OPENBOT_APP_BROWSER" }, + }), + ); + expect(result.run.app_browser).toBe(source); + expect(result.run.suite).toBe(source); + expect(result.browserTests).toEqual([app]); + expect(result.desktopBrowserTests).toEqual([desktop]); + } + }); + + test("code-only full browser runs do not repeat the same browser files in the partial job", () => { + const source = "app/src/main.tsx"; + const file = "app/tests/existing-layout.test.tsx"; + const result = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: [source] }, + mentions: { [source]: [file] }, + files: { + [file]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + }, + }), + ); + expect(result.run.app_browser).toBe(true); + expect(result.run.app_browser_webkit).toBe(true); + expect(result.run.partial).toBe(false); + }); + + test("removing a Bun test reruns the suite to validate its aggregate floor", () => { + // Change records expose paths/deletions, not how many cases remain inside a retained test file. + const file = "tests/removed.test.ts"; + const result = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: [file] }, + deleted: [file], + }), + ); + expect(result.run.suite).toBe(true); + expect(result.tests).toEqual([]); + }); test("compares the current PR's tested synthetic merge rather than its head", () => { const base = deps({ passed: { c2: ALL_CI }, changes: {} }); const decision = decide( @@ -534,6 +668,12 @@ describe("a pull request push", () => { ); expect(decision.run.app_browser).toBe(true); expect(decision.run.app_browser_webkit).toBe(true); + expect(decision.browserTests).toContain( + "app/tests/composer-dictation-language.test.tsx", + ); + expect(decision.webkitTests).toContain( + "app/tests/composer-dictation-language.test.tsx", + ); }); test("a change to a package the app imports runs the app's list in WebKit", () => { @@ -662,7 +802,7 @@ describe("a pull request push", () => { expect(decision.tests).toEqual([]); }); - test("a changed browser test runs in a browser, with WebKit when it asks for it", () => { + test("changed browser files retain browser coverage from both browser baselines", () => { const decision = decide( "ci", PR, @@ -691,13 +831,14 @@ describe("a pull request push", () => { ]); expect(decision.webkitTests).toEqual([ "app/tests/composer-dictation-language.test.tsx", + "app/tests/maths-rendering.test.tsx", ]); expect(decision.desktopBrowserTests).toEqual([ "desktop/src/setupLayout.browser.test.ts", ]); }); - test("a deleted test is not run, a test that names it is", () => { + test("a deleted test is not selected; the full suite runs tests that name it", () => { const decision = decide( "ci", PR, @@ -708,7 +849,8 @@ describe("a pull request push", () => { mentions: { "tests/old.test.ts": ["scripts/test-floor.test.ts"] }, }), ); - expect(decision.tests).toEqual(["scripts/test-floor.test.ts"]); + expect(decision.run.suite).toBe(true); + expect(decision.tests).toEqual([]); }); test("a change to CI itself runs every job", () => { @@ -1066,6 +1208,23 @@ describe("a merge group", () => { ?.checks as string[]; const GROUP: MergeGroup = { head: "g", pr: { labels: [], head: "h" } }; + test("a merge group without passing baselines retains changed browser files from its event base", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + const base = groupDeps({ passed: {}, changes: { "event-base": [file] } }); + const result = decideMergeGroup( + "ci", + [file], + { + ...base, + read: () => "process.env.OPENBOT_APP_BROWSER", + }, + { ...GROUP, base: "event-base" }, + ); + expect(result.run.app_browser).toBe(true); + expect(result.browserTests).toEqual([file]); + expect(result.webkitTests).toEqual([file]); + }); + test("compares a PR's passing jobs with its tested merge tree, never its untested head", () => { // h needs a fix on main. CI passed on merge m with that fix. Main later reverted it: // g equals h, but differs from the actual passing merge m, so its checks are owed. @@ -1201,7 +1360,7 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { - test("a successful partial rerun reuses the original run-scoped checkout proof", () => { + test("passing checks on later job pages remain reusable after partial reruns", () => { const result = actionsDecision({ event: "pull_request", proof: true, @@ -1213,17 +1372,52 @@ describe("the checkout a passing run proves", () => { id: 1, path: ".github/workflows/ci.yml", event: "pull_request", - run_attempt: 2, + run_attempt: 3, head_repository: { full_name: "CopilotKit/OpenBot" }, }, ], }, "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + [ + { + jobs: Array.from({ length: 100 }, () => ({ + name: "app (real browser)", + conclusion: "failure", + })), + }, + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + ], }), }); expect(result.suite).toBe("false"); - expect(result.static).toBe("false"); + expect(result.app_browser).toBe("false"); + expect(result.app_browser_webkit).toBe("false"); + }); + test("first attempts and successful partial reruns reuse the run-scoped checkout proof", () => { + for (const attempt of [1, 2]) { + const result = actionsDecision({ + event: "pull_request", + proof: true, + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + path: ".github/workflows/ci.yml", + event: "pull_request", + run_attempt: attempt, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + }), + }); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + } }); test("missing or malformed artifacts cannot stand in for a tested checkout", () => { @@ -1585,6 +1779,43 @@ describe("a release PR", () => { describe("the Desktop workflow", () => { const ALL_DESKTOP = DESKTOP_RULES.flatMap((rule) => rule.checks); + test("a Desktop test-only edit gets a frozen install and Desktop types in static CI", () => { + for (const source of [false, true]) { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { + c2: [ + "desktop/src/App.test.tsx", + ...(source ? ["server/src/main.ts"] : []), + ], + }, + }), + ); + expect(decision.run.static).toBe(true); + } + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: { + static: { steps: { run?: string; "working-directory"?: string }[] }; + }; + }; + const steps = workflow.jobs.static.steps; + const check = steps.findIndex( + (step) => + step["working-directory"] === "desktop" && + step.run === "bun run typecheck", + ); + expect(check).toBeGreaterThanOrEqual(0); + expect(steps.slice(0, check)).toContainEqual({ + run: "bun install --frozen-lockfile", + "working-directory": "desktop", + }); + }); + test("a release commit on main builds nothing; any other push, or one it cannot read, builds everything", () => { // v1.2.7's release commit (843b8029f): CHANGELOG.md, and package.json, backend-images.env and // Cargo's two files each by their version alone, which releaseFileViolations reads as no violation. diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 0963125531..c6b1597d1e 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -11,7 +11,7 @@ * * Three shapes of change come out small: * - * - Test files only. The suite's shards are skipped and the changed test files run on their own, + * - Test files only, with none removed. The suite's shards are skipped and changed files run on their own, * with any test that names one of them, in `tests (changed files)`; `format, lint, types` still * runs, since it formats, lints and type checks the tests. A test file that drives a real browser * runs in one there. @@ -497,6 +497,7 @@ export function decide( pr.checkout ?? pr.head, [deps.ancestors(pr.head)], deps, + () => deps.diff(pr.base, pr.checkout ?? pr.head), ); } @@ -512,6 +513,7 @@ function decideFrom( head: string, histories: string[][], deps: Deps, + currentChanges?: () => Change[], ): Decision { const rules = rulesOf(workflow); const passedAt = new Map>(); @@ -629,7 +631,13 @@ function decideFrom( ); } } - decideSuite(decision, changesFor(SUITE_RULE), changesFor, deps); + decideSuite( + decision, + changesFor(SUITE_RULE), + changesFor, + deps, + currentChanges, + ); } return decision; } @@ -640,11 +648,19 @@ function decideSuite( suiteChanges: Change[] | undefined, changesFor: (rule: Rule) => Change[] | undefined, deps: Deps, + currentChanges?: () => Change[], ) { const { run, reasons } = decision; const code = suiteChanges?.filter((change) => isCode(change.path)); - run.suite = !suiteChanges || (code?.length ?? 0) > 0; - if (suiteChanges && code && code.length > 0) { + const removed = suiteChanges?.filter( + (change) => change.deleted && isBunTest(change.path), + ); + run.suite = !suiteChanges || (code?.length ?? 0) + (removed?.length ?? 0) > 0; + if (suiteChanges && removed && removed.length > 0) { + reasons.push( + `suite: runs, ${describe(removed)} removed; the aggregate test floor must be checked again.`, + ); + } else if (suiteChanges && code && code.length > 0) { reasons.push(`suite: runs, ${describe(code)} changed.`); } else if (suiteChanges) { reasons.push( @@ -652,13 +668,23 @@ function decideSuite( ); } - // The test files to run on their own: the ones changed since the suite last passed, and every test - // that names a changed file. Those the full suite or the browser job runs anyway are left out. + // Non-browser tests can reuse the suite. Browser jobs run fixed file lists, so changed browser + // files remain candidates even when those jobs run. Each browser rule has its own passing tree. const candidates = new Set(); - const add = (changes: Change[] | undefined, browser: boolean) => { + const webkit = new Set(); + const add = ( + changes: Change[] | undefined, + browser: boolean, + fullJob = false, + forceWebKit = false, + ) => { if (!changes) return; const named = changes - .filter((change) => !manualOnly(change.path)) + .filter( + (change) => + !manualOnly(change.path) && + (!fullJob || isTestFile(change.path) || isDocs(change.path)), + ) .map((change) => change.path); const files = [ ...changes @@ -667,18 +693,27 @@ function decideSuite( ...deps.mentions(named), ]; for (const file of files) { - if (isBunTest(file) && isBrowserTest(file, deps) === browser) + if (isBunTest(file) && isBrowserTest(file, deps) === browser) { candidates.add(file); + if (forceWebKit && !file.startsWith("desktop/")) webkit.add(file); + } } }; if (!run.suite) add(suiteChanges, false); - if (!run.app_browser) { - add( - changesFor( - CI_RULES.find((rule) => rule.output === "app_browser") as Rule, - ), - true, + let current: Change[] | undefined; + for (const output of ["app_browser", "app_browser_webkit"]) { + // Without a historical pass, full jobs still cannot cover edited files outside their lists. + // Only then fall back to this PR/group's diff; an old PR edit may already have passed later. + let changes = changesFor( + CI_RULES.find((rule) => rule.output === output) as Rule, ); + if (!changes) { + current ??= currentChanges?.().filter( + (change) => !isIgnored(change.path), + ); + changes = current; + } + add(changes, true, run[output], output === "app_browser_webkit"); } for (const file of [...candidates].sort()) { @@ -688,7 +723,10 @@ function decideSuite( decision.desktopBrowserTests.push(file); } else { decision.browserTests.push(file); - if (deps.read(file)?.includes("OPENBOT_APP_ENGINES")) { + if ( + webkit.has(file) || + deps.read(file)?.includes("OPENBOT_APP_ENGINES") + ) { decision.webkitTests.push(file); } } @@ -902,6 +940,8 @@ export function decideDesktopMainPush( export type MergeGroup = { /** The group's commit: main, or the groups queued ahead, with this pull request on top. */ head: string; + /** The event's base commit, before the queued changes. */ + base?: string; /** The queued pull request, or undefined when it could not be read. */ pr?: { labels: string[]; @@ -1015,15 +1055,21 @@ export function decideMergeGroup( } const histories = [ancestors(group.head)]; if (group.pr?.head) histories.push(ancestors(group.pr.head)); - const decision = decideFrom(workflow, group.head, histories, { - ancestors, - passed, - testedTrees: deps.testedTrees, - diff, - releaseViolations, - mentions: deps.mentions, - read: deps.read, - }); + const decision = decideFrom( + workflow, + group.head, + histories, + { + ancestors, + passed, + testedTrees: deps.testedTrees, + diff, + releaseViolations, + mentions: deps.mentions, + read: deps.read, + }, + () => diff(group.base ?? histories[0]?.[1] ?? group.head, group.head), + ); decision.reasons.unshift( group.pr?.head ? "A merge group: each job runs unless nothing it reads changed since it passed on main or on the pull request." @@ -1060,7 +1106,7 @@ type ApiRun = { type ApiJob = { name: string; conclusion: string | null; run_attempt?: number }; /** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ -function jobsOf(repository: string, run: CiRun): ApiJob[] { +function jobsOf(repository: string, run: Pick): ApiJob[] { const pages = JSON.parse( exec([ "gh", @@ -1175,13 +1221,7 @@ function liveDeps( } if (!tree) continue; const names = trees.get(tree) ?? new Set(); - const jobs = JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs/${run.id}/jobs?filter=all&per_page=100`, - ]), - ).jobs as ApiJob[]; + const jobs = jobsOf(repository, run); for (const job of jobs) if (job.conclusion === "success") names.add(job.name); trees.set(tree, names); @@ -1455,6 +1495,7 @@ if (import.meta.main) { ]), { head: event.merge_group.head_sha, + base: event.merge_group.base_sha, pr: queuedPull(repository, event.merge_group.head_ref), }, ); From 3989214d37017e5ef53b1bf667516a127968ac98 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:40:38 -0800 Subject: [PATCH 04/17] CI: retain partial browser failures through full-check transitions --- .github/workflows/ci.yml | 6 +- scripts/ci-changes.test.ts | 264 +++++++++++++++++++++++++-- scripts/ci-changes.ts | 131 +++++++++++-- scripts/workflow-concurrency.test.ts | 20 +- 4 files changed, 375 insertions(+), 46 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bebb5d1779..e88581ca0c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,6 +2,8 @@ name: CI on: pull_request: + # Adding full-ci must start the full replacement run on the same commit. + types: [opened, synchronize, reopened, labeled] push: branches: [main] # The merge queue: main's merge queue builds each pull request on top of main and the pull @@ -18,7 +20,7 @@ on: permissions: contents: read -# The newest push on a pull request wins. Every commit on main keeps its own run, for the badge and +# The newest run on a pull request wins. Every commit on main keeps its own run, for the badge and # for the release: publishing a release relies on main's CI having passed on the commit the release # PR merged onto (scripts/release-ci-gate.ts). In one group, a push landing while another commit's # run was in progress replaced the pending run of the commit before it, and that commit never got a @@ -34,7 +36,7 @@ permissions: # GitHub drops from the group's one pending slot is re-run later by Contributor CI # (scripts/contributor-ci.ts), which also pauses fork runs while CopilotKit's are waiting. # -# Only a pull request's own push cancels. The release's call of these checks runs with the release +# A pull request's newer push or label starts a replacement run. The release's call runs with the release # push's context, a push to main or to a release branch, and is never cancelled by the next one # (scripts/workflow-concurrency.test.ts). concurrency: diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index b9db408ca3..82a8b1532d 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import { chmodSync, existsSync, + mkdirSync, mkdtempSync, readFileSync, readdirSync, @@ -9,7 +10,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { CACHE_WRITERS, type Change, @@ -40,6 +41,10 @@ const ROOT = join(import.meta.dir, ".."); /** Every check a full CI run passes, by the job names the Actions API reports. */ const ALL_CI = [...CI_RULES, SUITE_RULE].flatMap((rule) => rule.checks); +const API_BASELINE_JOBS = [ + ...ALL_CI.map((name) => ({ name, conclusion: "success" })), + { name: "tests (changed files)", conclusion: "skipped" }, +]; /** The tests that name CHANGELOG.md, as `git grep -l CHANGELOG.md -- '*.test.ts'` finds them. */ const NAME_CHANGELOG = [ @@ -137,8 +142,12 @@ const REAL = { mentions: realMentions, read: readTracked }; /** Runs the real Actions entry point with a local repository and recorded GitHub responses. */ function actionsDecision(options: { event: "pull_request" | "merge_group" | "push"; - responses: (sha: string) => Record; + responses: (sha: string, commits: string[]) => Record; proof?: boolean | string; + proofs?: (commits: string[]) => Record; + commits?: Record[]; + base?: string; + expectFailure?: boolean; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -159,14 +168,34 @@ function actionsDecision(options: { "-m", "test", ); - const sha = git("rev-parse", "HEAD"); + const commits = [git("rev-parse", "HEAD")]; + for (const files of options.commits ?? []) { + for (const [file, content] of Object.entries(files)) { + mkdirSync(dirname(join(directory, file)), { recursive: true }); + writeFileSync(join(directory, file), content); + } + git("add", "--all"); + git( + "-c", + "user.name=CI", + "-c", + "user.email=ci@example.test", + "commit", + "--quiet", + "-m", + "next", + ); + commits.push(git("rev-parse", "HEAD")); + } + const sha = commits.at(-1) as string; const repository = "CopilotKit/OpenBot"; const fixture = join(directory, "fixture.json"); writeFileSync( fixture, JSON.stringify({ - responses: options.responses(sha), + responses: options.responses(sha, commits), proof: options.proof, + proofs: options.proofs?.(commits), sha, }), ); @@ -179,8 +208,10 @@ import { join } from "node:path"; const fixture = JSON.parse(readFileSync(process.env.CI_FIXTURE, "utf8")); const args = process.argv.slice(2); if (args[0] === "run" && args[1] === "download") { - if (!fixture.proof || args[args.indexOf("--name") + 1] !== "ci-tested-tree-1") process.exit(1); - writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), typeof fixture.proof === "string" ? fixture.proof : fixture.sha); + const name = args[args.indexOf("--name") + 1]; + const proof = fixture.proofs?.[name] ?? (fixture.proof && name === "ci-tested-tree-1" ? (typeof fixture.proof === "string" ? fixture.proof : fixture.sha) : undefined); + if (!proof) process.exit(1); + writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), proof); } else { const endpoint = args.find((arg) => arg.startsWith("repos/")); if (!(endpoint in fixture.responses)) process.exit(1); @@ -198,10 +229,10 @@ if (args[0] === "run" && args[1] === "download") { pull_request: { labels: [], head: { ref: "fix", sha, repo: { full_name: repository } }, - base: { sha }, + base: { sha: options.base ?? commits[0] }, }, merge_group: { - base_sha: "b".repeat(40), + base_sha: options.commits?.length ? commits[0] : "b".repeat(40), head_sha: sha, head_ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha}`, }, @@ -229,6 +260,11 @@ if (args[0] === "run" && args[1] === "download") { }, }, ); + if (options.expectFailure) { + expect(result.exitCode).not.toBe(0); + expect(existsSync(output)).toBe(false); + return {}; + } expect(result.exitCode).toBe(0); return Object.fromEntries( [ @@ -974,6 +1010,54 @@ describe("manual Workbench changes", () => { }); describe("everything runs", () => { + test("full-ci retains changed app and Desktop browser files without history lookups", () => { + const app = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/unlisted.browser.test.ts"; + for (const event of ["pull_request", "merge_group"]) { + const base = deps({ + passed: {}, + changes: {}, + files: { [app]: "process.env.OPENBOT_APP_BROWSER" }, + }); + const noHistory = { + ...base, + ancestors: () => { + throw new Error("full-ci must not read history"); + }, + passed: () => { + throw new Error("full-ci must not read history"); + }, + diff: (from: string, to: string) => { + expect(from).toBe("base"); + expect(to).toBe("checkout"); + return [app, desktop].map((path) => ({ path, deleted: false })); + }, + }; + const result = + event === "pull_request" + ? decide( + "ci", + { + ...PR, + base: "base", + checkout: "checkout", + labels: ["full-ci"], + }, + noHistory, + ) + : decideMergeGroup("ci", [app, desktop], noHistory, { + head: "checkout", + base: "base", + pr: { labels: ["full-ci"] }, + }); + expect(result.browserTests).toEqual([app]); + expect(result.webkitTests).toEqual([app]); + expect(result.desktopBrowserTests).toEqual([desktop]); + expect(result.run.partial).toBe(true); + for (const rule of [...CI_RULES, SUITE_RULE]) + expect(result.run[rule.output]).toBe(true); + } + }); test("on any event but a pull request: main, the release's call, a schedule", () => { const decision = decide("ci", undefined, deps({ passed: {}, changes: {} })); expect(running(decision)).toEqual( @@ -1038,8 +1122,9 @@ describe("a merge group", () => { test("a source file renamed to a document cannot use the docs-only shortcut", () => { const result = actionsDecision({ event: "merge_group", - responses: (sha) => ({ - [`repos/CopilotKit/OpenBot/compare/${"b".repeat(40)}...${sha}`]: { + commits: [{ "README.md": "renamed source body" }], + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { files: [ { filename: "README.md", @@ -1124,7 +1209,10 @@ describe("a merge group", () => { "scripts/release-note-check.fixtures/pr-2654.md", ]) { const decision = decideMergeGroup("ci", [path], REAL); - expect({ path, run: running(decision) }).toEqual({ + expect({ + path, + run: running(decision).filter((job) => job !== "partial"), + }).toEqual({ path, run: everyJob, }); @@ -1139,15 +1227,18 @@ describe("a merge group", () => { ["README.md", "app/src/lib/marks.ts"], ]) { const decision = decideMergeGroup("ci", files, REAL); - expect(running(decision)).toEqual(everyJob); + expect(running(decision).filter((job) => job !== "partial")).toEqual( + everyJob, + ); expect(decision.ignoredOnly).toBe(false); } }); - test("whose files could not be read, or are none, runs everything", () => { - for (const files of [undefined, []]) { - expect(running(decideMergeGroup("ci", files, REAL))).toEqual(everyJob); - } + test("an empty group runs everything; unreadable changed paths cannot claim browser coverage", () => { + expect(running(decideMergeGroup("ci", [], REAL))).toEqual(everyJob); + expect(() => decideMergeGroup("ci", undefined, REAL)).toThrow( + "changed browser files", + ); }); test("ci.yml: the image builds follow the group's `components` decision, and always run on main", () => { @@ -1248,7 +1339,9 @@ describe("a merge group", () => { head: "g", pr: { labels: ["full-ci"] }, }); - expect(running(result)).toEqual(everyJob); + expect(running(result).filter((job) => job !== "partial")).toEqual( + everyJob, + ); }); /** The pull request changed the app; main changed a harness since the pull request branched. */ const APP_PR_HARNESS_MAIN = { @@ -1360,6 +1453,121 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("a docs push retains failed partial browser work until the latest partial attempt passes", () => { + const app = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/unlisted.browser.test.ts"; + for (const state of [ + "failure", + "cancelled", + "missing", + "unreadable", + "success", + "skipped", + "retry", + ]) { + const recovered = ["success", "skipped", "retry"].includes(state); + const result = actionsDecision({ + event: "pull_request", + commits: [ + { + "app/src/main.tsx": "changed source", + [app]: "process.env.OPENBOT_APP_BROWSER", + [desktop]: "", + }, + { "README.md": "docs-only followup" }, + ], + proofs: (commits) => ({ "ci-tested-tree-3": commits[1] }), + responses: (sha, commits) => { + const run = (id: number, event: string) => ({ + id, + event, + path: ".github/workflows/ci.yml", + run_attempt: state === "retry" ? 2 : 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }); + const partial = + state === "missing" + ? [] + : [ + ...(state === "retry" + ? [ + { + name: "tests (changed files)", + conclusion: "failure", + run_attempt: 1, + }, + ] + : []), + { + name: "tests (changed files)", + conclusion: + state === "unreadable" + ? null + : state === "retry" + ? "success" + : state, + run_attempt: state === "retry" ? 2 : 1, + }, + ]; + const full = ALL_CI.map((name) => ({ name, conclusion: "success" })); + return { + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { workflow_runs: [] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[1]}&per_page=100`]: + { workflow_runs: [run(3, "pull_request")] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[0]}&per_page=100`]: + { workflow_runs: [run(1, "push")] }, + "repos/CopilotKit/OpenBot/actions/runs/3/jobs?filter=all&per_page=100": + { jobs: [...full, ...partial] }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { + jobs: [ + ...full, + { name: "tests (changed files)", conclusion: "skipped" }, + ], + }, + }; + }, + }); + expect(JSON.parse(result.browser_tests)).toEqual(recovered ? [] : [app]); + expect(JSON.parse(result.desktop_browser_tests)).toEqual( + recovered ? [] : [desktop], + ); + expect(result.partial).toBe(String(!recovered)); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + expect(result.build).toBe("false"); + } + }, 15_000); + + test("historical API failure still runs changed browser files from the local PR diff", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + for (const event of ["pull_request", "merge_group"] as const) { + const result = actionsDecision({ + event, + commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + responses: () => ({}), + }); + expect(result.suite).toBe("true"); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + expect(result.partial).toBe("true"); + } + }); + + test("unreadable historical evidence and local changes fail the changes job", () => { + actionsDecision({ + event: "pull_request", + commits: [ + { + "app/tests/access-requests-layout.test.tsx": + "process.env.OPENBOT_APP_BROWSER", + }, + ], + base: "b".repeat(40), + expectFailure: true, + responses: () => ({}), + }); + }); test("passing checks on later job pages remain reusable after partial reruns", () => { const result = actionsDecision({ event: "pull_request", @@ -1385,7 +1593,7 @@ describe("the checkout a passing run proves", () => { conclusion: "failure", })), }, - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + { jobs: API_BASELINE_JOBS }, ], }), }); @@ -1412,7 +1620,7 @@ describe("the checkout a passing run proves", () => { ], }, "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + { jobs: API_BASELINE_JOBS }, }), }); expect(result.suite).toBe("false"); @@ -1439,7 +1647,7 @@ describe("the checkout a passing run proves", () => { ], }, "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": - { jobs: ALL_CI.map((name) => ({ name, conclusion: "success" })) }, + { jobs: API_BASELINE_JOBS }, }), }); expect(result.suite).toBe("true"); @@ -1927,6 +2135,22 @@ function jobNames(workflow: string): string[] { } describe("the rules name the jobs the workflows run", () => { + test("adding a label triggers replacement CI with the normal changes and verify jobs", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + on: { pull_request: { types?: string[] } | null }; + jobs: Record; + }; + expect(workflow.on.pull_request?.types).toEqual([ + "opened", + "synchronize", + "reopened", + "labeled", + ]); + expect(workflow.jobs.changes.if).toBeUndefined(); + expect(workflow.jobs.verify.if).toBe("always()"); + }); test("the cross-browser list runs each engine in a separate job, retaining both required results", () => { const ci = Bun.YAML.parse( readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index c6b1597d1e..be2148d555 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -464,6 +464,20 @@ export function rulesOf(workflow: Workflow): Rule[] { return workflow === "ci" ? [...CI_RULES, SUITE_RULE] : DESKTOP_RULES; } +/** Full fixed-list jobs still need the browser files changed outside those lists. No history read. */ +function fullDecision( + workflow: Workflow, + why: string, + deps: Pick, + currentChanges: () => Change[], +): Decision { + const decision = everything(rulesOf(workflow), why); + if (workflow === "ci") { + decideSuite(decision, undefined, () => undefined, deps, currentChanges); + } + return decision; +} + /** * Decides every job of a workflow for one pull request push. `pr` undefined is any other event, * which runs everything. @@ -476,7 +490,12 @@ export function decide( const rules = rulesOf(workflow); if (!pr) return everything(rules, "Not a pull request: everything runs."); if (pr.labels.includes("full-ci")) { - return everything(rules, "Labelled full-ci: everything runs."); + return fullDecision( + workflow, + "Labelled full-ci: everything runs.", + deps, + () => deps.diff(pr.base, pr.checkout ?? pr.head), + ); } if (releaseShaped(pr)) { @@ -647,7 +666,7 @@ function decideSuite( decision: Decision, suiteChanges: Change[] | undefined, changesFor: (rule: Rule) => Change[] | undefined, - deps: Deps, + deps: Pick, currentChanges?: () => Change[], ) { const { run, reasons } = decision; @@ -978,15 +997,26 @@ export function decideMergeGroup( group?: MergeGroup, ): Decision & { ignoredOnly: boolean } { const rules = rulesOf(workflow); + const currentChanges = () => { + if (group?.base && deps.diff) return deps.diff(group.base, group.head); + if (changed) + return changed.map((path) => ({ + path, + deleted: deps.read(path) === undefined, + })); + throw new Error( + "Could not determine this merge group's changed browser files.", + ); + }; + const full = (why: string) => ({ + ...fullDecision(workflow, why, deps, currentChanges), + ignoredOnly: false, + }); // The explicit override applies even when every changed file is a document. if (group?.pr?.labels.includes("full-ci")) { - return { - ...everything( - rules, - "A merge group of a pull request labelled full-ci: everything runs.", - ), - ignoredOnly: false, - }; + return full( + "A merge group of a pull request labelled full-ci: everything runs.", + ); } // A file no job's rule reads: CHANGELOG.md, and the docs. A test that names a doc still runs. const unread = (path: string) => @@ -1030,10 +1060,6 @@ export function decideMergeGroup( } return decision; } - const full = (why: string) => ({ - ...everything(rulesOf(workflow), why), - ignoredOnly: false, - }); if (!changed) { return full( "A merge group whose files could not be read: everything runs.", @@ -1103,7 +1129,12 @@ type ApiRun = { run_attempt: number; head_repository?: { full_name?: string } | null; }; -type ApiJob = { name: string; conclusion: string | null; run_attempt?: number }; +type ApiJob = { + name: string; + conclusion: string | null; + run_attempt?: number; + id?: number; +}; /** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ function jobsOf(repository: string, run: Pick): ApiJob[] { @@ -1145,6 +1176,11 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); + const browserChecks = new Set( + CI_RULES.filter((rule) => + ["app_browser", "app_browser_webkit"].includes(rule.output), + ).flatMap((rule) => rule.checks), + ); const records = new Map>>(); const recordsAt = (sha: string): Map> => { const cached = records.get(sha); @@ -1222,8 +1258,25 @@ function liveDeps( if (!tree) continue; const names = trees.get(tree) ?? new Set(); const jobs = jobsOf(repository, run); + // A fixed browser list cannot discharge a failed unlisted-file obligation. Failed-only + // reruns retain older jobs, so only the latest partial result establishes that coverage. + const partial = jobs + .filter((job) => job.name === "tests (changed files)") + .sort( + (a, b) => + (b.run_attempt ?? 0) - (a.run_attempt ?? 0) || + (b.id ?? 0) - (a.id ?? 0), + )[0]; + const browserCovered = + workflow !== "ci" || + partial?.conclusion === "success" || + partial?.conclusion === "skipped"; for (const job of jobs) - if (job.conclusion === "success") names.add(job.name); + if ( + job.conclusion === "success" && + (browserCovered || !browserChecks.has(job.name)) + ) + names.add(job.name); trees.set(tree, names); } records.set(sha, trees); @@ -1439,6 +1492,7 @@ if (import.meta.main) { const repository = process.env.GITHUB_REPOSITORY ?? ""; const eventName = process.env.GITHUB_EVENT_NAME ?? ""; let decision: Decision & { queueRun?: CiRun; ignoredOnly?: boolean }; + let fallbackChanges: { base: string; head: string } | undefined; try { const event = ( process.env.GITHUB_EVENT_PATH @@ -1455,6 +1509,27 @@ if (import.meta.main) { checkout: workflow === "ci" ? process.env.GITHUB_SHA : undefined, base: pull.base.sha, }; + if (workflow === "ci" && pr) { + fallbackChanges = { base: pr.base, head: pr.checkout ?? pr.head }; + } else if ( + workflow === "ci" && + eventName === "merge_group" && + event.merge_group + ) { + fallbackChanges = { + base: event.merge_group.base_sha, + head: event.merge_group.head_sha, + }; + } + if ( + workflow === "ci" && + ["pull_request", "merge_group"].includes(eventName) && + (!fallbackChanges?.base || !fallbackChanges.head) + ) { + throw new Error( + "The event does not identify the base and checkout needed to check changed browser files.", + ); + } // main's own run of a push. Not the release's call of these checks, which sees the push that // published it as its event too: `github.workflow` there is the caller's, Publish release. const mainPush = @@ -1514,11 +1589,27 @@ if (import.meta.main) { ); } } catch (error) { - // Unable to decide is never a reason to skip: everything runs. - decision = everything( - rulesOf(workflow), - `Could not decide, so everything runs: ${error instanceof Error ? error.message : String(error)}`, - ); + const why = `Could not decide, so everything runs: ${error instanceof Error ? error.message : String(error)}`; + if ( + workflow === "ci" && + ["pull_request", "merge_group"].includes(eventName) + ) { + // Historical API evidence may fail while the event's local Git diff remains readable. + // If that diff fails too, fail changes rather than claim fixed lists cover unknown files. + if (!fallbackChanges) throw error; + const local = liveDeps( + workflow, + repository, + Number(process.env.GITHUB_RUN_ID ?? 0), + [repository], + ); + const { base, head } = fallbackChanges; + decision = fullDecision(workflow, why, local, () => + local.diff(base, head), + ); + } else { + decision = everything(rulesOf(workflow), why); + } } for (const [output, value] of Object.entries(decision.run)) { writeOutput(output, String(value)); diff --git a/scripts/workflow-concurrency.test.ts b/scripts/workflow-concurrency.test.ts index 839707f377..5ae8a243db 100644 --- a/scripts/workflow-concurrency.test.ts +++ b/scripts/workflow-concurrency.test.ts @@ -1,6 +1,6 @@ /** * A pull request's newer push cancels the run of the push before it, in every workflow a pull - * request starts, and nothing else is ever cancelled. + * request starts. A label can also start a complete replacement CI run. * * CI waits on the 16-core runners. A pull request pushed again while its run is in progress leaves * that run spending minutes on a commit nobody will merge, so each workflow's `concurrency` cancels @@ -31,7 +31,7 @@ type Workflow = { concurrency?: | string | { group?: string; "cancel-in-progress"?: boolean | string }; - jobs?: Record; + jobs?: Record; }; const files = readdirSync(directory) @@ -276,7 +276,7 @@ describe("main, a release branch, a tag, a schedule and a manual run are never c }); }); -describe("a pull request labelled while its run is in progress keeps that run", () => { +describe("a label preserves the active run or starts its complete CI replacement", () => { const labelled = pullRequestWorkflows.filter((file) => triggers(file).pull_request?.types?.includes("labeled"), ); @@ -285,7 +285,19 @@ describe("a pull request labelled while its run is in progress keeps that run", action: "labeled", label: "full-ci", }); - expect(concurrency(file, label)?.cancel).toBe(false); + if (file === "ci.yml") { + // CI runs its normal decision/check graph for every label, including the full-ci override. + // Replacing the active run is safe because the new run supplies every required obligation. + expect(triggers(file).pull_request?.types).toContain("labeled"); + expect(workflow(file).jobs?.changes?.if).toBeUndefined(); + expect(workflow(file).jobs?.verify?.if).toBe("always()"); + expect(concurrency(file, label)?.group).toBe( + concurrency(file, pullRequest(file, 101, "same-push"))?.group, + ); + expect(concurrency(file, label)?.cancel).toBe(true); + } else { + expect(concurrency(file, label)?.cancel).toBe(false); + } }); }); From 499ac14e0eb1d74258642945cd562b62688f1a51 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:52:30 -0800 Subject: [PATCH 05/17] CI: fail on dependency-search errors and isolate browser engines --- .../bots-panel-start-conversation.test.tsx | 17 ++-- app/tests/browser-engines.test.ts | 80 +++++++++++++++++++ app/tests/browser-engines.ts | 25 ++++++ app/tests/roster-working.test.tsx | 19 ++--- app/tests/section-strip-routines.test.tsx | 17 ++-- app/tests/sidebar-zoom-drag.test.tsx | 17 ++-- scripts/ci-changes.test.ts | 56 +++++++++++++ scripts/ci-changes.ts | 6 +- 8 files changed, 199 insertions(+), 38 deletions(-) create mode 100644 app/tests/browser-engines.test.ts create mode 100644 app/tests/browser-engines.ts diff --git a/app/tests/bots-panel-start-conversation.test.tsx b/app/tests/bots-panel-start-conversation.test.tsx index 1189a22937..9407f68361 100644 --- a/app/tests/bots-panel-start-conversation.test.tsx +++ b/app/tests/bots-panel-start-conversation.test.tsx @@ -1,9 +1,10 @@ import { afterAll, beforeAll, describe, expect } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import type { Browser, BrowserType, Locator, Page } from "playwright-core"; +import type { Browser, Locator, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { personBody } from "./accounts-api"; +import { launchBrowserEngines } from "./browser-engines"; import { conversationPage } from "./conversations-api"; import { still } from "./page-still"; import { test } from "./renderer-crash"; @@ -24,8 +25,8 @@ import { test } from "./renderer-crash"; * * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/bots-panel-start-conversation.test.tsx * - * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when - * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves the panel, light and dark, + * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both. + * With OPENBOT_APP_SHOTS= it saves the panel, light and dark, * in a desktop window and a narrow one, as bots-panel---.png. */ const asked = process.env.OPENBOT_APP_BROWSER === "1"; @@ -195,11 +196,11 @@ beforeAll(async () => { readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/), ); css = await stylesheet([...new Set(sources)].sort()); - const { chromium, webkit } = await import("playwright-core"); - // The CI job installs full Chromium without the headless shell. - engines.push(["chromium", await chromium.launch({ channel: "chromium" })]); - if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit")) - engines.push(["webkit", await (webkit as BrowserType).launch()]); + await launchBrowserEngines( + await import("playwright-core"), + process.env.OPENBOT_APP_ENGINES, + engines, + ); }, 120_000); afterAll(async () => { diff --git a/app/tests/browser-engines.test.ts b/app/tests/browser-engines.test.ts new file mode 100644 index 0000000000..a68423fef3 --- /dev/null +++ b/app/tests/browser-engines.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, test } from "bun:test"; +import { launchBrowserEngines } from "./browser-engines"; + +describe("browser engine selection", () => { + for (const [selection, expected] of [ + [undefined, ["chromium"]], + ["chromium", ["chromium"]], + ["webkit", ["webkit"]], + ["chromium,webkit", ["chromium", "webkit"]], + [" chromium, webkit ", ["chromium", "webkit"]], + ] as const) { + test(`${selection ?? "default"} launches only its selected engines`, async () => { + const calls: { engine: string; options: unknown }[] = []; + const factory = (engine: string) => ({ + launch: async (options?: { channel?: string }) => { + calls.push({ engine, options }); + return { engine }; + }, + }); + const opened: [string, { engine: string }][] = []; + await launchBrowserEngines( + { chromium: factory("chromium"), webkit: factory("webkit") }, + selection, + opened, + ); + expect(calls).toEqual( + expected.map((engine) => ({ + engine, + options: engine === "chromium" ? { channel: "chromium" } : undefined, + })), + ); + expect(opened).toEqual(expected.map((engine) => [engine, { engine }])); + }); + } + + test("the caller owns browsers already launched when a later engine fails", async () => { + const opened: [string, { close: () => void }][] = []; + let closed = false; + const chromium = { + close: () => { + closed = true; + }, + }; + await expect( + launchBrowserEngines( + { + chromium: { launch: async () => chromium }, + webkit: { + launch: async () => { + throw new Error("WebKit launch failed"); + }, + }, + }, + "chromium,webkit", + opened, + ), + ).rejects.toThrow("WebKit launch failed"); + expect(opened).toEqual([["chromium", chromium]]); + for (const [, browser] of opened) browser.close(); + expect(closed).toBe(true); + }); + + test("an unsupported selection cannot silently run no browsers", async () => { + let launched = false; + const factory = { + launch: async () => { + launched = true; + return {}; + }, + }; + await expect( + launchBrowserEngines( + { chromium: factory, webkit: factory }, + "unsupported", + [], + ), + ).rejects.toThrow("Unsupported browser engine"); + expect(launched).toBe(false); + }); +}); diff --git a/app/tests/browser-engines.ts b/app/tests/browser-engines.ts new file mode 100644 index 0000000000..95cfa526b4 --- /dev/null +++ b/app/tests/browser-engines.ts @@ -0,0 +1,25 @@ +type BrowserFactory = { + launch(options?: { channel?: string }): Promise; +}; + +/** Launch only the selected engines. The caller retains cleanup ownership, including on failure. */ +export async function launchBrowserEngines( + factories: Record<"chromium" | "webkit", BrowserFactory>, + selection: string | undefined, + opened: [string, T][], +): Promise { + const selected = new Set( + (selection?.trim() || "chromium").split(",").map((engine) => engine.trim()), + ); + for (const engine of selected) { + if (engine !== "chromium" && engine !== "webkit") { + throw new Error(`Unsupported browser engine: ${engine}`); + } + // CI installs full Chromium without the headless shell. + const browser = + engine === "chromium" + ? await factories.chromium.launch({ channel: "chromium" }) + : await factories.webkit.launch(); + opened.push([engine, browser]); + } +} diff --git a/app/tests/roster-working.test.tsx b/app/tests/roster-working.test.tsx index fbf601d216..36bb305eef 100644 --- a/app/tests/roster-working.test.tsx +++ b/app/tests/roster-working.test.tsx @@ -1,13 +1,9 @@ import { afterAll, beforeAll, describe, expect } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import type { - Browser, - BrowserType, - Page, - WebSocketRoute, -} from "playwright-core"; +import type { Browser, Page, WebSocketRoute } from "playwright-core"; import { compile } from "tailwindcss"; +import { launchBrowserEngines } from "./browser-engines"; import { test } from "./renderer-crash"; /** @@ -26,7 +22,7 @@ import { test } from "./renderer-crash"; * * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/roster-working.test.tsx * - * Chromium always, WebKit too when `OPENBOT_APP_ENGINES` names it; light and dark. With + * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both, light and dark. With * OPENBOT_APP_SHOTS= it saves each moment as roster-working----.png. */ const asked = process.env.OPENBOT_APP_BROWSER === "1"; @@ -168,10 +164,11 @@ beforeAll(async () => { readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/), ); css = await stylesheet([...new Set(sources)].sort()); - const { chromium, webkit } = await import("playwright-core"); - engines.push(["chromium", await chromium.launch({ channel: "chromium" })]); - if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit")) - engines.push(["webkit", await (webkit as BrowserType).launch()]); + await launchBrowserEngines( + await import("playwright-core"), + process.env.OPENBOT_APP_ENGINES, + engines, + ); }); afterAll(async () => { diff --git a/app/tests/section-strip-routines.test.tsx b/app/tests/section-strip-routines.test.tsx index 1e421b8239..491be80edd 100644 --- a/app/tests/section-strip-routines.test.tsx +++ b/app/tests/section-strip-routines.test.tsx @@ -1,9 +1,10 @@ import { afterAll, beforeAll, describe, expect } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import type { Browser, BrowserType, Page } from "playwright-core"; +import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { personBody } from "./accounts-api"; +import { launchBrowserEngines } from "./browser-engines"; import { conversationPage } from "./conversations-api"; import { still } from "./page-still"; import { test } from "./renderer-crash"; @@ -26,8 +27,8 @@ import { test } from "./renderer-crash"; * * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/section-strip-routines.test.tsx * - * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when - * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves the strip and the panel on + * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both. + * With OPENBOT_APP_SHOTS= it saves the strip and the panel on * Routines, after Conversations, Bots and then Routines, as section-strip-routines--.png. */ const asked = process.env.OPENBOT_APP_BROWSER === "1"; @@ -190,11 +191,11 @@ beforeAll(async () => { readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/), ); css = await stylesheet([...new Set(sources)].sort()); - const { chromium, webkit } = await import("playwright-core"); - // The CI job installs full Chromium without the headless shell. - engines.push(["chromium", await chromium.launch({ channel: "chromium" })]); - if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit")) - engines.push(["webkit", await (webkit as BrowserType).launch()]); + await launchBrowserEngines( + await import("playwright-core"), + process.env.OPENBOT_APP_ENGINES, + engines, + ); }, 120_000); afterAll(async () => { diff --git a/app/tests/sidebar-zoom-drag.test.tsx b/app/tests/sidebar-zoom-drag.test.tsx index 4f84b9e62c..0dc7551b7f 100644 --- a/app/tests/sidebar-zoom-drag.test.tsx +++ b/app/tests/sidebar-zoom-drag.test.tsx @@ -1,9 +1,10 @@ import { afterAll, beforeAll, describe, expect } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import type { Browser, BrowserType, Page } from "playwright-core"; +import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { personBody } from "./accounts-api"; +import { launchBrowserEngines } from "./browser-engines"; import { test } from "./renderer-crash"; /** @@ -31,8 +32,8 @@ import { test } from "./renderer-crash"; * * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/sidebar-zoom-drag.test.tsx * - * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when - * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves each case as + * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit or both. + * With OPENBOT_APP_SHOTS= it saves each case as * sidebar-zoom---.png. */ const asked = process.env.OPENBOT_APP_BROWSER === "1"; @@ -263,11 +264,11 @@ beforeAll(async () => { readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/), ); css = await stylesheet([...new Set(sources)].sort()); - const { chromium, webkit } = await import("playwright-core"); - // The CI job installs full Chromium without the headless shell. - engines.push(["chromium", await chromium.launch({ channel: "chromium" })]); - if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit")) - engines.push(["webkit", await (webkit as BrowserType).launch()]); + await launchBrowserEngines( + await import("playwright-core"), + process.env.OPENBOT_APP_ENGINES, + engines, + ); }); afterAll(async () => { diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 82a8b1532d..09dd0c8db2 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -148,6 +148,7 @@ function actionsDecision(options: { commits?: Record[]; base?: string; expectFailure?: boolean; + grepExit?: number; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -221,6 +222,26 @@ if (args[0] === "run" && args[1] === "download") { `, ); chmodSync(gh, 0o755); + if (options.grepExit !== undefined) { + const realGit = Bun.which("git"); + if (!realGit) throw new Error("git is not installed"); + const wrappedGit = join(directory, "git"); + writeFileSync( + wrappedGit, + `#!${process.execPath} +const args = process.argv.slice(2); +if (args[0] === "grep") { + if (${options.grepExit} !== 1) console.error("fatal: failed to read test file"); + process.exit(${options.grepExit}); +} +const result = Bun.spawnSync([${JSON.stringify(realGit)}, ...args]); +process.stdout.write(result.stdout); +process.stderr.write(result.stderr); +process.exit(result.exitCode); +`, + ); + chmodSync(wrappedGit, 0o755); + } const event = join(directory, "event.json"); writeFileSync( event, @@ -1119,6 +1140,41 @@ describe("CHANGELOG.md", () => { describe("a merge group", () => { const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); + test("dependency discovery accepts grep's no-match status but fails on unreadable tests", () => { + for (const grepExit of [undefined, 1, 128]) { + const result = actionsDecision({ + event: "merge_group", + commits: [ + { + "README.md": "changed docs", + "app/tests/unlisted.test.ts": + grepExit === 1 + ? "OPENBOT_APP_BROWSER" + : "README.md OPENBOT_APP_BROWSER", + }, + ], + grepExit, + expectFailure: grepExit === 128, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "README.md" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + }), + }); + if (grepExit !== 128) { + expect(result.suite).toBe("false"); + expect(result.partial).toBe(String(grepExit === undefined)); + expect(JSON.parse(result.browser_tests)).toEqual( + grepExit === undefined ? ["app/tests/unlisted.test.ts"] : [], + ); + } + } + }); + test("a source file renamed to a document cannot use the docs-only shortcut", () => { const result = actionsDecision({ event: "merge_group", diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index be2148d555..96d2e51ca2 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1114,9 +1114,9 @@ function describe(changes: Change[]): string { // --------------------------------------------------------------------------------------------- // Running it in Actions. -function exec(cmd: string[], allowFailure = false): string { +function exec(cmd: string[], allowedExitCode?: number): string { const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" }); - if (result.exitCode !== 0 && !allowFailure) { + if (result.exitCode !== 0 && result.exitCode !== allowedExitCode) { throw new Error(`${cmd.join(" ")}: ${result.stderr.toString().trim()}`); } return result.stdout.toString(); @@ -1333,7 +1333,7 @@ function liveDeps( "*.test.ts", "*.test.tsx", ], - true, + 1, ) .split("\0") .filter((file) => file && isBunTest(file)); From d8ff4b661bf17182abd25fc66fa10ef9687e537f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:53:56 -0800 Subject: [PATCH 06/17] CI: keep manual runs from erasing changed browser obligations --- scripts/ci-changes.test.ts | 33 +++++++++++++++++++++++++++++++++ scripts/ci-changes.ts | 6 ++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 09dd0c8db2..de12c5bfcf 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1509,6 +1509,39 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("manual and scheduled fixed-list runs cannot discharge a PR's unlisted browser edit", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + for (const event of ["workflow_dispatch", "schedule"]) { + const result = actionsDecision({ + event: "pull_request", + commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event, + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[0]}&per_page=100`]: + { workflow_runs: [] }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: API_BASELINE_JOBS }, + }), + }); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + expect(result.partial).toBe("true"); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + expect(result.build).toBe("false"); + } + }); + test("a docs push retains failed partial browser work until the latest partial attempt passes", () => { const app = "app/tests/access-requests-layout.test.tsx"; const desktop = "desktop/src/unlisted.browser.test.ts"; diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 96d2e51ca2..42ff62ad2f 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1269,8 +1269,10 @@ function liveDeps( )[0]; const browserCovered = workflow !== "ci" || - partial?.conclusion === "success" || - partial?.conclusion === "skipped"; + // Manual/scheduled runs do not discover a feature branch's changed browser files. + (["pull_request", "push", "merge_group"].includes(run.event) && + (partial?.conclusion === "success" || + partial?.conclusion === "skipped")); for (const job of jobs) if ( job.conclusion === "success" && From f5207aafed010ac0a696861bb64ddb244879f87f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 03:55:45 -0800 Subject: [PATCH 07/17] CI: limit push browser baselines to main --- scripts/ci-changes.test.ts | 15 +++++++++++---- scripts/ci-changes.ts | 6 ++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index de12c5bfcf..3b99c75476 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1509,9 +1509,14 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { - test("manual and scheduled fixed-list runs cannot discharge a PR's unlisted browser edit", () => { + test("only supported producer events can discharge a PR's unlisted browser edit", () => { const file = "app/tests/access-requests-layout.test.tsx"; - for (const event of ["workflow_dispatch", "schedule"]) { + for (const [event, head_branch, covered] of [ + ["workflow_dispatch", "feature", false], + ["schedule", "main", false], + ["push", "feature", false], + ["push", "main", true], + ] as const) { const result = actionsDecision({ event: "pull_request", commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], @@ -1522,6 +1527,7 @@ describe("the checkout a passing run proves", () => { { id: 1, event, + head_branch, path: ".github/workflows/ci.yml", run_attempt: 1, head_repository: { full_name: "CopilotKit/OpenBot" }, @@ -1534,8 +1540,8 @@ describe("the checkout a passing run proves", () => { { jobs: API_BASELINE_JOBS }, }), }); - expect(JSON.parse(result.browser_tests)).toEqual([file]); - expect(result.partial).toBe("true"); + expect(JSON.parse(result.browser_tests)).toEqual(covered ? [] : [file]); + expect(result.partial).toBe(String(!covered)); expect(result.suite).toBe("false"); expect(result.static).toBe("false"); expect(result.build).toBe("false"); @@ -1570,6 +1576,7 @@ describe("the checkout a passing run proves", () => { const run = (id: number, event: string) => ({ id, event, + head_branch: event === "push" ? "main" : "feature", path: ".github/workflows/ci.yml", run_attempt: state === "retry" ? 2 : 1, head_repository: { full_name: "CopilotKit/OpenBot" }, diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 42ff62ad2f..71d03c8d75 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1126,6 +1126,7 @@ type ApiRun = { id: number; path: string; event: string; + head_branch: string | null; run_attempt: number; head_repository?: { full_name?: string } | null; }; @@ -1269,8 +1270,9 @@ function liveDeps( )[0]; const browserCovered = workflow !== "ci" || - // Manual/scheduled runs do not discover a feature branch's changed browser files. - (["pull_request", "push", "merge_group"].includes(run.event) && + // Only supported producers discover PR changes or test the protected main branch. + ((["pull_request", "merge_group"].includes(run.event) || + (run.event === "push" && run.head_branch === "main")) && (partial?.conclusion === "success" || partial?.conclusion === "skipped")); for (const job of jobs) From 7ca893f12d6a3ea210f54e976c7363bc6f90a7fb Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:08:20 -0800 Subject: [PATCH 08/17] CI: keep current unlisted browser files owed across reused trees --- scripts/ci-changes.test.ts | 146 ++++++++++++++++++++++++++++++++++--- scripts/ci-changes.ts | 85 ++++++++++++++++++++- 2 files changed, 218 insertions(+), 13 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 3b99c75476..6d5cdc2384 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -145,8 +145,9 @@ function actionsDecision(options: { responses: (sha: string, commits: string[]) => Record; proof?: boolean | string; proofs?: (commits: string[]) => Record; - commits?: Record[]; + commits?: Record[]; base?: string; + baseIndex?: number; expectFailure?: boolean; grepExit?: number; }) { @@ -172,6 +173,10 @@ function actionsDecision(options: { const commits = [git("rev-parse", "HEAD")]; for (const files of options.commits ?? []) { for (const [file, content] of Object.entries(files)) { + if (content === null) { + rmSync(join(directory, file), { force: true }); + continue; + } mkdirSync(dirname(join(directory, file)), { recursive: true }); writeFileSync(join(directory, file), content); } @@ -250,10 +255,12 @@ process.exit(result.exitCode); pull_request: { labels: [], head: { ref: "fix", sha, repo: { full_name: repository } }, - base: { sha: options.base ?? commits[0] }, + base: { sha: options.base ?? commits[options.baseIndex ?? 0] }, }, merge_group: { - base_sha: options.commits?.length ? commits[0] : "b".repeat(40), + base_sha: options.commits?.length + ? commits[options.baseIndex ?? 0] + : "b".repeat(40), head_sha: sha, head_ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha}`, }, @@ -426,6 +433,58 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("only literal unfiltered full-job arrays prove current browser-file coverage", () => { + const file = "app/tests/selected.browser.test.ts"; + const array = `files=(\n ${file}\n)\nbun test --parallel "\${files[@]}"`; + for (const [run, covered] of [ + [array, true], + [ + array + .split("\n") + .map((line) => `# ${line}`) + .join("\n"), + false, + ], + [array.replace("bun test", 'bun test -t "one case"'), false], + [array.replace("bun test", "bun test --test-name-pattern=one"), false], + [array.replace("--parallel", "--parallel --shard=1/2"), false], + [array.replace("--parallel", "--parallel --unknown"), false], + [array.replace(file, "$FILE"), false], + [`# ${file}\nbun test app/tests/another.browser.test.ts`, false], + ] as const) { + const base = deps({ passed: { c2: ALL_CI }, changes: {} }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? [{ path: file, deleted: false }] + : base.diff(from, to), + read: (path) => + path === ".github/workflows/ci.yml" + ? JSON.stringify({ + jobs: { "app-browser-webkit": { steps: [{ run }] } }, + }) + : "process.env.OPENBOT_APP_BROWSER", + }); + expect(result.browserTests).toEqual(covered ? [] : [file]); + } + for (const manifest of [undefined, "jobs: ["]) { + const base = deps({ passed: { c2: ALL_CI }, changes: {} }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? [{ path: file, deleted: false }] + : base.diff(from, to), + read: (path) => + path === ".github/workflows/ci.yml" + ? manifest + : "process.env.OPENBOT_APP_BROWSER", + }); + expect(result.browserTests).toEqual([file]); + } + }); + test("an outstanding WebKit test survives a docs-only push after Chromium passed", () => { const file = "app/tests/composer-dictation-language.test.tsx"; for (const recovered of [false, true]) { @@ -443,6 +502,9 @@ describe("a pull request push", () => { files: { [file]: "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, }, }); const result = decide("ci", PR, { @@ -568,7 +630,7 @@ describe("a pull request push", () => { { ...base, diff: (from, to) => { - expect(from).toBe("c2"); + expect(["c2", PR.base]).toContain(from); return to === "merge" ? [{ path: "app/src/main.tsx", deleted: false }] : []; @@ -1509,8 +1571,62 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { - test("only supported producer events can discharge a PR's unlisted browser edit", () => { + test("restoring an unlisted browser file remains owed even when its old main tree passed", () => { const file = "app/tests/access-requests-layout.test.tsx"; + const content = "process.env.OPENBOT_APP_BROWSER"; + for (const event of ["pull_request", "merge_group"] as const) { + const result = actionsDecision({ + event, + commits: [ + { + [file]: content, + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + { [file]: null }, + { [file]: content }, + ], + baseIndex: 2, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { workflow_runs: [] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[2]}&per_page=100`]: + { workflow_runs: [] }, + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${commits[1]}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event: "push", + head_branch: "main", + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: API_BASELINE_JOBS }, + [`repos/CopilotKit/OpenBot/compare/${commits[2]}...${sha}`]: { + files: [{ filename: file }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "someone/OpenBot" } }, + }, + }), + }); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + expect(result.partial).toBe("true"); + expect(result.suite).toBe("false"); + expect(result.static).toBe("false"); + expect(result.app_browser).toBe("false"); + } + }); + + test("only supported producer events provide reusable fixed-list browser checks", () => { + const file = "app/tests/composer-dictation-language.test.tsx"; for (const [event, head_branch, covered] of [ ["workflow_dispatch", "feature", false], ["schedule", "main", false], @@ -1519,7 +1635,14 @@ describe("the checkout a passing run proves", () => { ] as const) { const result = actionsDecision({ event: "pull_request", - commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + commits: [ + { + [file]: "process.env.OPENBOT_APP_BROWSER", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + ], responses: (sha, commits) => ({ [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: { @@ -1548,7 +1671,7 @@ describe("the checkout a passing run proves", () => { } }); - test("a docs push retains failed partial browser work until the latest partial attempt passes", () => { + test("current unlisted work remains owed while partial results govern fixed-job reuse", () => { const app = "app/tests/access-requests-layout.test.tsx"; const desktop = "desktop/src/unlisted.browser.test.ts"; for (const state of [ @@ -1625,11 +1748,10 @@ describe("the checkout a passing run proves", () => { }; }, }); - expect(JSON.parse(result.browser_tests)).toEqual(recovered ? [] : [app]); - expect(JSON.parse(result.desktop_browser_tests)).toEqual( - recovered ? [] : [desktop], - ); - expect(result.partial).toBe(String(!recovered)); + expect(JSON.parse(result.browser_tests)).toEqual([app]); + expect(JSON.parse(result.desktop_browser_tests)).toEqual([desktop]); + expect(result.partial).toBe("true"); + expect(result.app_browser).toBe(String(!recovered)); expect(result.suite).toBe("false"); expect(result.static).toBe("false"); expect(result.build).toBe("false"); diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 71d03c8d75..30358c22ad 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -696,6 +696,7 @@ function decideSuite( browser: boolean, fullJob = false, forceWebKit = false, + covered?: Set, ) => { if (!changes) return; const named = changes @@ -712,7 +713,11 @@ function decideSuite( ...deps.mentions(named), ]; for (const file of files) { - if (isBunTest(file) && isBrowserTest(file, deps) === browser) { + if ( + isBunTest(file) && + isBrowserTest(file, deps) === browser && + !covered?.has(file) + ) { candidates.add(file); if (forceWebKit && !file.startsWith("desktop/")) webkit.add(file); } @@ -734,6 +739,10 @@ function decideSuite( } add(changes, true, run[output], output === "app_browser_webkit"); } + // Passing fixed lists prove nothing about files outside them, even when an older passing tree + // is restored exactly. Keep those files owed by this PR/group's own diff until they join a list. + current ??= currentChanges?.().filter((change) => !isIgnored(change.path)); + add(current, true, true, true, fullBrowserFiles(deps)); for (const file of [...candidates].sort()) { if (!isBrowserTest(file, deps)) { @@ -766,6 +775,80 @@ function decideSuite( } } +/** Only literal full arrays in the current browser jobs prove file coverage. Unknown is no proof. */ +function fullBrowserFiles(deps: Pick): Set { + const files = new Set(); + try { + const workflow = Bun.YAML.parse( + deps.read(".github/workflows/ci.yml") ?? "", + ) as { + jobs?: Record; + } | null; + for (const id of [ + "app-browser", + "app-browser-webkit", + "app-browser-desktop", + ]) { + for (const step of workflow?.jobs?.[id]?.steps ?? []) { + const run = step.run; + if ( + typeof run !== "string" || + step.if !== undefined || + run.includes("<<") || + /^(?:[ \t]*)(?:if|case|for|while|until)\b/m.test(run) + ) + continue; + const commands = run + .split("\n") + .filter((line) => /^[ \t]*bun[ \t]+test\b/.test(line)); + if ( + !commands.some((command) => { + const words = command.trim().split(/\s+/); + return ( + words[0] === "bun" && + words[1] === "test" && + words.at(-1) === `"\${files[@]}"` && + words + .slice(2, -1) + .every( + (flag) => + /^--parallel(?:=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*"))?$/.test( + flag, + ) || + /^--timeout=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*")$/.test(flag), + ) + ); + }) + ) + continue; + if ((run.match(/^[ \t]*files(?:\+|\[[^\]]+\])?=/gm) ?? []).length !== 1) + continue; + const body = run.match( + /^[ \t]*files=\([ \t]*\r?\n([\s\S]*?)^[ \t]*\)[ \t]*\r?$/m, + )?.[1]; + if (!body) continue; + const paths = body + .split("\n") + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith("#")); + if ( + !paths.every( + (path) => + /^(?:[\w.-]+\/)*[\w.-]+\.test\.tsx?$/.test(path) && + !path.split("/").includes(".."), + ) + ) + continue; + for (const path of paths) files.add(path); + } + } + return files; + } catch { + // An unreadable or unrecognised manifest must leave every changed browser file owed. + return new Set(); + } +} + /** A test that drives a real browser, which `bun test` alone skips. */ function isBrowserTest(file: string, deps: Pick): boolean { return ( From ec549ae13e61d1ab04c8085236079c48674ea28f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:15:52 -0800 Subject: [PATCH 09/17] Tests: disable commit signing in CI decision fixtures --- scripts/ci-changes.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 6d5cdc2384..450fdfa735 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -159,6 +159,7 @@ function actionsDecision(options: { return result.stdout.toString().trim(); }; git("init", "--quiet"); + git("config", "--local", "commit.gpgsign", "false"); git( "-c", "user.name=CI", From d3dd79aa6d2609881169693a27d1a382a0d9d0d0 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:17:03 -0800 Subject: [PATCH 10/17] Tests: override inherited signing for fixture Git commands --- scripts/ci-changes.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 450fdfa735..f2cf16c3c1 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -154,12 +154,14 @@ function actionsDecision(options: { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { const git = (...args: string[]) => { - const result = Bun.spawnSync(["git", ...args], { cwd: directory }); + const result = Bun.spawnSync( + ["git", "-c", "commit.gpgsign=false", ...args], + { cwd: directory }, + ); if (result.exitCode !== 0) throw new Error(result.stderr.toString()); return result.stdout.toString().trim(); }; git("init", "--quiet"); - git("config", "--local", "commit.gpgsign", "false"); git( "-c", "user.name=CI", From 766dc48cf1816420ec27be38e509bb0e25052a41 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:44:05 -0800 Subject: [PATCH 11/17] CI: bound and interleave historical proof lookups --- scripts/ci-changes.test.ts | 145 ++++++++++++++++++++++- scripts/ci-changes.ts | 230 +++++++++++++++++++++++-------------- 2 files changed, 285 insertions(+), 90 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index f2cf16c3c1..0d2336fb52 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -150,6 +150,7 @@ function actionsDecision(options: { baseIndex?: number; expectFailure?: boolean; grepExit?: number; + historyBudgetMs?: number; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -206,6 +207,10 @@ function actionsDecision(options: { proof: options.proof, proofs: options.proofs?.(commits), sha, + historyCalls: + options.historyBudgetMs === undefined + ? undefined + : join(directory, "history-called"), }), ); const gh = join(directory, "gh"); @@ -223,6 +228,7 @@ if (args[0] === "run" && args[1] === "download") { writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), proof); } else { const endpoint = args.find((arg) => arg.startsWith("repos/")); + if (fixture.historyCalls && endpoint?.includes("/actions/runs")) writeFileSync(fixture.historyCalls, "called"); if (!(endpoint in fixture.responses)) process.exit(1); const response = fixture.responses[endpoint]; console.log(JSON.stringify(args.includes("--slurp") ? (Array.isArray(response) ? response : [response]) : (Array.isArray(response) ? response[0] : response))); @@ -288,6 +294,7 @@ process.exit(result.exitCode); WORKFLOW_NAME: "CI", GITHUB_OUTPUT: output, GITHUB_STEP_SUMMARY: "", + CI_HISTORY_BUDGET_MS: String(options.historyBudgetMs ?? 45_000), }, }, ); @@ -297,6 +304,8 @@ process.exit(result.exitCode); return {}; } expect(result.exitCode).toBe(0); + if (options.historyBudgetMs === 0) + expect(existsSync(join(directory, "history-called"))).toBe(false); return Object.fromEntries( [ ...readFileSync(output, "utf8").matchAll( @@ -436,6 +445,39 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("scheduled cross-browser jobs cover listed files without duplicate partial work", () => { + const listed = "app/tests/composer-dictation-language.test.tsx"; + const unlisted = "app/tests/access-requests-layout.test.tsx"; + const desktop = "desktop/src/setupLayout.browser.test.ts"; + for (const extra of [false, true]) { + const files = [listed, ...(extra ? [unlisted, desktop] : [])]; + const base = deps({ + passed: { c2: ALL_CI }, + changes: { c2: ["app/src/main.tsx", ...files] }, + files: { + [listed]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + [unlisted]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? files.map((path) => ({ path, deleted: false })) + : base.diff(from, to), + }); + expect(result.run.app_browser_webkit).toBe(true); + expect(result.browserTests).toEqual(extra ? [unlisted] : []); + expect(result.webkitTests).toEqual(extra ? [unlisted] : []); + expect(result.desktopBrowserTests).toEqual(extra ? [desktop] : []); + expect(result.run.partial).toBe(extra); + } + }); test("only literal unfiltered full-job arrays prove current browser-file coverage", () => { const file = "app/tests/selected.browser.test.ts"; const array = `files=(\n ${file}\n)\nbun test --parallel "\${files[@]}"`; @@ -1420,6 +1462,50 @@ describe("a merge group", () => { ?.checks as string[]; const GROUP: MergeGroup = { head: "g", pr: { labels: [], head: "h" } }; + test("an exact PR proof is found before obsolete main-history lookups", () => { + const base = groupDeps({ passed: {}, changes: {} }); + const visited: string[] = []; + const result = decideMergeGroup( + "ci", + ["app/src/main.tsx"], + { + ...base, + passed: (sha) => { + visited.push(sha); + if (sha === "b" || sha === "b1") + throw new Error("obsolete main history must not be queried"); + return new Set(sha === "h" ? ALL_CI : []); + }, + diff: (from) => + from === "h" ? [] : [{ path: "app/src/main.tsx", deleted: false }], + }, + GROUP, + ); + expect(visited).toEqual(["g", "h"]); + expect(result.run.suite).toBe(false); + expect(result.run.app_browser_webkit).toBe(false); + }); + + test("an empty tree diff wins over an earlier equal-input test-only diff", () => { + const file = "app/tests/composer-dictation-language.test.tsx"; + const base = groupDeps({ + passed: { g: ALL_CI, h: ALL_CI }, + changes: { g: [file], h: [] }, + }); + const result = decideMergeGroup( + "ci", + [file], + { + ...base, + read: () => + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + }, + GROUP, + ); + expect(result.browserTests).toEqual([]); + expect(result.run.partial).toBe(false); + }); + test("a merge group without passing baselines retains changed browser files from its event base", () => { const file = "app/tests/access-requests-layout.test.tsx"; const base = groupDeps({ passed: {}, changes: { "event-base": [file] } }); @@ -1574,6 +1660,60 @@ describe("a merge group", () => { }); describe("the checkout a passing run proves", () => { + test("zero history budget runs unresolved checks and keeps current unlisted browser files", () => { + const file = "app/tests/access-requests-layout.test.tsx"; + const result = actionsDecision({ + event: "pull_request", + historyBudgetMs: 0, + commits: [{ [file]: "process.env.OPENBOT_APP_BROWSER" }], + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event: "push", + head_branch: "main", + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: API_BASELINE_JOBS }, + }), + }); + expect(result.static).toBe("true"); + expect(result.suite).toBe("true"); + expect(JSON.parse(result.browser_tests)).toEqual([file]); + }); + + test("a cached static proof survives unreadable older history for unresolved checks", () => { + const result = actionsDecision({ + event: "pull_request", + commits: [{ "README.md": "docs" }], + responses: (sha) => ({ + [`repos/CopilotKit/OpenBot/actions/runs?head_sha=${sha}&per_page=100`]: + { + workflow_runs: [ + { + id: 1, + event: "push", + head_branch: "main", + path: ".github/workflows/ci.yml", + run_attempt: 1, + head_repository: { full_name: "CopilotKit/OpenBot" }, + }, + ], + }, + "repos/CopilotKit/OpenBot/actions/runs/1/jobs?filter=all&per_page=100": + { jobs: [{ name: "format, lint, types", conclusion: "success" }] }, + }), + }); + expect(result.static).toBe("false"); + expect(result.suite).toBe("true"); + }); test("restoring an unlisted browser file remains owed even when its old main tree passed", () => { const file = "app/tests/access-requests-layout.test.tsx"; const content = "process.env.OPENBOT_APP_BROWSER"; @@ -1666,8 +1806,9 @@ describe("the checkout a passing run proves", () => { { jobs: API_BASELINE_JOBS }, }), }); - expect(JSON.parse(result.browser_tests)).toEqual(covered ? [] : [file]); - expect(result.partial).toBe(String(!covered)); + expect(JSON.parse(result.browser_tests)).toEqual([]); + expect(result.app_browser_webkit).toBe(String(!covered)); + expect(result.partial).toBe("false"); expect(result.suite).toBe("false"); expect(result.static).toBe("false"); expect(result.build).toBe("false"); diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 30358c22ad..010ec3eaf9 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -41,7 +41,9 @@ * bun scripts/ci-changes.ts ci|desktop * * Env: GITHUB_EVENT_PATH, GITHUB_EVENT_NAME, GITHUB_REF, GITHUB_SHA, GITHUB_REPOSITORY, - * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). Writes one + * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). + * CI_HISTORY_BUDGET_MS can shorten the 45000 ms historical-proof deadline (0..45000); each remote + * history call is limited to the remaining time or 5000 ms, whichever is less. Writes one * output per job (`true` to run it), the changed tests as JSON arrays, and `queue_run` (the merge * queue's run that stands in for this one, or empty) to $GITHUB_OUTPUT, and what it decided and why * to $GITHUB_STEP_SUMMARY. @@ -544,19 +546,31 @@ function decideFrom( } return names; }; - /** Along each history, the newest commit where every one of these checks passed. */ - const baselinesOf = (checks: string[]) => - histories.flatMap((ancestors) => { - for (const sha of ancestors) { + /** Visit each history at the same depth before looking farther back on either one. */ + const baselinesOf = (checks: string[]) => { + const baselines: string[] = []; + const found = new Set(); + const depth = Math.max(0, ...histories.map((history) => history.length)); + for (let index = 0; index < depth; index++) { + for (const [lane, ancestors] of histories.entries()) { + if (found.has(lane)) continue; + const sha = ancestors[index]; + if (!sha) continue; const trees = deps.testedTrees ? deps.testedTrees(sha, checks) : checks.every((check) => passed(sha).has(check)) ? [sha] : []; - if (trees.length > 0) return trees; + if (trees.length > 0) found.add(lane); + for (const tree of trees) { + baselines.push(tree); + if (since(tree).length === 0) return baselines; + } } - return []; - }); + if (found.size === histories.length) break; + } + return baselines; + }; const changesSince = new Map(); const since = (sha: string) => { let changes = changesSince.get(sha); @@ -605,8 +619,11 @@ function decideFrom( changes.filter( (change) => !manualOnly(change.path) && rule.reads(change.path), ).length; - return usable.reduce((best, changes) => - readBy(changes) < readBy(best) ? changes : best, + return ( + usable.find((changes) => changes.length === 0) ?? + usable.reduce((best, changes) => + readBy(changes) < readBy(best) ? changes : best, + ) ); }; @@ -744,7 +761,16 @@ function decideSuite( current ??= currentChanges?.().filter((change) => !isIgnored(change.path)); add(current, true, true, true, fullBrowserFiles(deps)); + const coveredByCrossBrowser = run.app_browser_webkit + ? fullBrowserFiles(deps, ["app-browser-webkit"]) + : new Set(); for (const file of [...candidates].sort()) { + if ( + !file.startsWith("desktop/") && + coveredByCrossBrowser.has(file) && + isBrowserTest(file, deps) + ) + continue; if (!isBrowserTest(file, deps)) { decision.tests.push(file); } else if (file.startsWith("desktop/")) { @@ -776,7 +802,10 @@ function decideSuite( } /** Only literal full arrays in the current browser jobs prove file coverage. Unknown is no proof. */ -function fullBrowserFiles(deps: Pick): Set { +function fullBrowserFiles( + deps: Pick, + jobs = ["app-browser", "app-browser-webkit", "app-browser-desktop"], +): Set { const files = new Set(); try { const workflow = Bun.YAML.parse( @@ -784,11 +813,7 @@ function fullBrowserFiles(deps: Pick): Set { ) as { jobs?: Record; } | null; - for (const id of [ - "app-browser", - "app-browser-webkit", - "app-browser-desktop", - ]) { + for (const id of jobs) { for (const step of workflow?.jobs?.[id]?.steps ?? []) { const run = step.run; if ( @@ -1197,8 +1222,16 @@ function describe(changes: Change[]): string { // --------------------------------------------------------------------------------------------- // Running it in Actions. -function exec(cmd: string[], allowedExitCode?: number): string { - const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" }); +function exec( + cmd: string[], + allowedExitCode?: number, + timeout?: number, +): string { + const result = Bun.spawnSync(cmd, { + stdout: "pipe", + stderr: "pipe", + timeout, + }); if (result.exitCode !== 0 && result.exitCode !== allowedExitCode) { throw new Error(`${cmd.join(" ")}: ${result.stderr.toString().trim()}`); } @@ -1221,9 +1254,13 @@ type ApiJob = { }; /** Every page and attempt: a partial rerun retains the jobs that did not rerun. */ -function jobsOf(repository: string, run: Pick): ApiJob[] { +function jobsOf( + repository: string, + run: Pick, + command: (cmd: string[]) => string = exec, +): ApiJob[] { const pages = JSON.parse( - exec([ + command([ "gh", "api", "--paginate", @@ -1260,6 +1297,19 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); + // Test overrides can shorten this deadline, never extend it beyond the production bound. + const requestedBudget = process.env.CI_HISTORY_BUDGET_MS; + const budgetMs = + requestedBudget !== undefined && /^\d+$/.test(requestedBudget) + ? Math.min(45_000, Number(requestedBudget)) + : 45_000; + const deadline = performance.now() + budgetMs; + const remaining = () => Math.max(0, Math.floor(deadline - performance.now())); + const historyCommand = (cmd: string[]) => { + const timeout = Math.min(5_000, remaining()); + if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); + return exec(cmd, undefined, timeout); + }; const browserChecks = new Set( CI_RULES.filter((rule) => ["app_browser", "app_browser_webkit"].includes(rule.output), @@ -1270,43 +1320,47 @@ function liveDeps( const cached = records.get(sha); if (cached) return cached; const trees = new Map>(); - const runs = ( - JSON.parse( - exec([ - "gh", - "api", - `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, - ]), - ).workflow_runs as ApiRun[] - ).filter( - (run) => - run.path === WORKFLOW_PATH[workflow] && - run.id !== currentRun && - trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), - ); + records.set(sha, trees); + if (remaining() <= 0) return trees; + let runs: ApiRun[]; + try { + runs = ( + JSON.parse( + historyCommand([ + "gh", + "api", + `repos/${repository}/actions/runs?head_sha=${sha}&per_page=100`, + ]), + ).workflow_runs as ApiRun[] + ).filter( + (run) => + run.path === WORKFLOW_PATH[workflow] && + run.id !== currentRun && + trusted.includes(run.head_repository?.full_name?.toLowerCase() ?? ""), + ); + } catch { + return trees; + } for (const run of runs) { + if (remaining() <= 0) break; let tree = testedCheckout(workflow, sha, run.event); if (workflow === "ci" && run.event === "pull_request") { // Actions attributes this run to the PR head, but checkout tested its temporary merge. // Runs before this proof existed, expired artifacts and unreachable trees never stand in. const directory = mkdtempSync(join(tmpdir(), "openbot-ci-tree-")); try { - const downloaded = Bun.spawnSync( - [ - "gh", - "run", - "download", - String(run.id), - "--repo", - repository, - "--name", - `ci-tested-tree-${run.id}`, - "--dir", - directory, - ], - { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, - ); - if (downloaded.exitCode !== 0) continue; + historyCommand([ + "gh", + "run", + "download", + String(run.id), + "--repo", + repository, + "--name", + `ci-tested-tree-${run.id}`, + "--dir", + directory, + ]); tree = testedCheckout( workflow, sha, @@ -1320,18 +1374,15 @@ function liveDeps( stderr: "pipe", }).exitCode === 0; if (!present()) { - const fetched = Bun.spawnSync( - [ - "git", - "fetch", - "--no-tags", - "--filter=blob:none", - "origin", - tree, - ], - { stdout: "pipe", stderr: "pipe", timeout: 15_000 }, - ); - if (fetched.exitCode !== 0 || !present()) continue; + historyCommand([ + "git", + "fetch", + "--no-tags", + "--filter=blob:none", + "origin", + tree, + ]); + if (!present()) continue; } } catch { continue; @@ -1340,33 +1391,36 @@ function liveDeps( } } if (!tree) continue; - const names = trees.get(tree) ?? new Set(); - const jobs = jobsOf(repository, run); - // A fixed browser list cannot discharge a failed unlisted-file obligation. Failed-only - // reruns retain older jobs, so only the latest partial result establishes that coverage. - const partial = jobs - .filter((job) => job.name === "tests (changed files)") - .sort( - (a, b) => - (b.run_attempt ?? 0) - (a.run_attempt ?? 0) || - (b.id ?? 0) - (a.id ?? 0), - )[0]; - const browserCovered = - workflow !== "ci" || - // Only supported producers discover PR changes or test the protected main branch. - ((["pull_request", "merge_group"].includes(run.event) || - (run.event === "push" && run.head_branch === "main")) && - (partial?.conclusion === "success" || - partial?.conclusion === "skipped")); - for (const job of jobs) - if ( - job.conclusion === "success" && - (browserCovered || !browserChecks.has(job.name)) - ) - names.add(job.name); - trees.set(tree, names); + try { + const names = trees.get(tree) ?? new Set(); + const jobs = jobsOf(repository, run, historyCommand); + // A fixed browser list cannot discharge a failed unlisted-file obligation. Failed-only + // reruns retain older jobs, so only the latest partial result establishes that coverage. + const partial = jobs + .filter((job) => job.name === "tests (changed files)") + .sort( + (a, b) => + (b.run_attempt ?? 0) - (a.run_attempt ?? 0) || + (b.id ?? 0) - (a.id ?? 0), + )[0]; + const browserCovered = + workflow !== "ci" || + // Only supported producers discover PR changes or test the protected main branch. + ((["pull_request", "merge_group"].includes(run.event) || + (run.event === "push" && run.head_branch === "main")) && + (partial?.conclusion === "success" || + partial?.conclusion === "skipped")); + for (const job of jobs) + if ( + job.conclusion === "success" && + (browserCovered || !browserChecks.has(job.name)) + ) + names.add(job.name); + trees.set(tree, names); + } catch { + // An unreadable run is no proof; earlier completed/cached proofs remain usable. + } } - records.set(sha, trees); return trees; }; return { From d3b887c15f5c3d6847d543955e040f1b8a19a148 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 04:54:24 -0800 Subject: [PATCH 12/17] CI: reuse current main history and classify browser tests by root --- scripts/ci-changes.test.ts | 125 ++++++++++++++++++++++++++++++++++++- scripts/ci-changes.ts | 41 +++++++----- 2 files changed, 149 insertions(+), 17 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 0d2336fb52..9ba5fe6b07 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -22,6 +22,7 @@ import { decideMainPush, decideMergeGroup, isBunTest, + isBrowserTest, isCode, isDocs, isIgnored, @@ -133,8 +134,7 @@ const readTracked = (path: string) => { /** A test that drives a real browser, as ci-changes.ts tells one. */ const isBrowserFile = (file: string) => - file.endsWith(".browser.test.ts") || - (readTracked(file)?.includes("OPENBOT_APP_BROWSER") ?? false); + isBrowserTest(file, { read: readTracked }); /** This checkout, as the merge group's `changes` job reads it. */ const REAL = { mentions: realMentions, read: readTracked }; @@ -445,6 +445,105 @@ describe("what a changed file is", () => { }); describe("a pull request push", () => { + test("CI compares checkout/main and PR history without replaying upstream-only browser edits", () => { + const own = "app/tests/composer-dictation-language.test.tsx"; + const upstream = "app/tests/upstream-only.browser.test.ts"; + const base = deps({ + passed: {}, + changes: {}, + files: { + [own]: + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ".github/workflows/ci.yml": readTracked( + ".github/workflows/ci.yml", + ) as string, + }, + }); + const histories = { + checkout: ["checkout", "main", "old"], + head: ["head", "old"], + }; + const result = decide( + "ci", + { ...PR, head: "head", checkout: "checkout", base: "main" }, + { + ...base, + ancestors: (head) => histories[head as keyof typeof histories], + passed: (sha) => + new Set(["main", "head", "old"].includes(sha) ? ALL_CI : []), + diff: (from, to) => { + expect(to).toBe("checkout"); + return ( + from === "main" + ? [own] + : from === "head" + ? [upstream] + : [own, upstream] + ).map((path) => ({ path, deleted: false })); + }, + }, + ); + expect(result.browserTests).toEqual([own]); + expect(result.webkitTests).toEqual([own]); + expect(result.run.suite).toBe(false); + }); + + test("script fixture markers stay ordinary suite tests rather than browser obligations", () => { + const scripts = [ + "scripts/ci-changes.test.ts", + "scripts/ci-run-tests.test.ts", + ]; + for (const source of [false, true]) { + const paths = [...scripts, ...(source ? ["server/src/main.ts"] : [])]; + const base = deps({ + passed: { c2: ALL_CI }, + changes: { c2: paths }, + files: Object.fromEntries( + scripts.map((file) => [ + file, + "process.env.OPENBOT_APP_BROWSER; process.env.OPENBOT_APP_ENGINES", + ]), + ), + }); + const result = decide("ci", PR, { + ...base, + diff: (from, to) => + from === PR.base + ? paths.map((path) => ({ path, deleted: false })) + : base.diff(from, to), + }); + expect(result.tests).toEqual(source ? [] : scripts); + expect(result.browserTests).toEqual([]); + expect(result.webkitTests).toEqual([]); + expect(result.run.partial).toBe(!source); + expect(result.run.app_browser_webkit).toBe(false); + } + }); + + test("frontend/root test markers and explicit browser filenames still select browsers", () => { + const files = [ + "app/tests/view.test.tsx", + "desktop/src/view.test.tsx", + "extension/tests/view.test.ts", + "tests/view.test.ts", + "scripts/opt-in.browser.test.ts", + ]; + const base = deps({ + passed: { c2: ALL_CI }, + changes: { c2: files }, + files: Object.fromEntries( + files + .filter((file) => !file.startsWith("scripts/")) + .map((file) => [file, "process.env.OPENBOT_APP_BROWSER"]), + ), + }); + const result = decide("ci", PR, base); + expect(result.browserTests).toEqual( + files.filter((file) => !file.startsWith("desktop/")).sort(), + ); + expect(result.desktopBrowserTests).toEqual(["desktop/src/view.test.tsx"]); + expect(result.tests).toEqual([]); + }); test("scheduled cross-browser jobs cover listed files without duplicate partial work", () => { const listed = "app/tests/composer-dictation-language.test.tsx"; const unlisted = "app/tests/access-requests-layout.test.tsx"; @@ -2349,6 +2448,28 @@ describe("a release PR", () => { describe("the Desktop workflow", () => { const ALL_DESKTOP = DESKTOP_RULES.flatMap((rule) => rule.checks); + test("Desktop keeps only raw PR-head history and compares the raw head", () => { + const base = deps({ passed: {}, changes: {} }); + const result = decide( + "desktop", + { ...PR, head: "desktop-head", checkout: "ci-merge" }, + { + ...base, + ancestors: (head) => { + expect(head).toBe("desktop-head"); + return [head]; + }, + passed: () => new Set(ALL_DESKTOP), + diff: (from, to) => { + expect(from).toBe("desktop-head"); + expect(to).toBe("desktop-head"); + return []; + }, + }, + ); + expect(running(result)).toEqual([]); + }); + test("a Desktop test-only edit gets a frozen install and Desktop types in static CI", () => { for (const source of [false, true]) { const decision = decide( diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 010ec3eaf9..c4922ffa59 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -513,19 +513,19 @@ export function decide( // A release PR that changes more than the release files is checked like any other PR. } - return decideFrom( - workflow, - pr.checkout ?? pr.head, - [deps.ancestors(pr.head)], - deps, - () => deps.diff(pr.base, pr.checkout ?? pr.head), + const checkout = workflow === "ci" ? (pr.checkout ?? pr.head) : pr.head; + const histories = [deps.ancestors(checkout)]; + if (workflow === "ci" && checkout !== pr.head) + histories.push(deps.ancestors(pr.head)); + return decideFrom(workflow, checkout, histories, deps, () => + deps.diff(pr.base, checkout), ); } /** * Decides every job for the tree at `head`, from the commits where each job last passed. `histories` - * are lists of commits newest first, each a line of first parents: for a pull request its own, for a - * merge group main's and the pull request's. A job is skipped when, along any one of them, nothing it + * are lists of commits newest first, each a line of first parents: CI uses the checkout/main and PR + * lines, Desktop the PR head alone. A job is skipped when, along any one of them, nothing it * reads changed between the newest commit where it passed and `head`: its inputs are then the very * files a passing run already checked. */ @@ -548,7 +548,7 @@ function decideFrom( }; /** Visit each history at the same depth before looking farther back on either one. */ const baselinesOf = (checks: string[]) => { - const baselines: string[] = []; + const baselines: string[][] = histories.map(() => []); const found = new Set(); const depth = Math.max(0, ...histories.map((history) => history.length)); for (let index = 0; index < depth; index++) { @@ -563,13 +563,14 @@ function decideFrom( : []; if (trees.length > 0) found.add(lane); for (const tree of trees) { - baselines.push(tree); - if (since(tree).length === 0) return baselines; + baselines[lane].push(tree); + if (since(tree).length === 0) return baselines.flat(); } } if (found.size === histories.length) break; } - return baselines; + // Equal-input ties prefer the checkout/main lane, independent of interleaved discovery order. + return baselines.flat(); }; const changesSince = new Map(); const since = (sha: string) => { @@ -658,6 +659,7 @@ function decideFrom( (change) => !change.deleted && isBunTest(change.path) && + isBrowserTest(change.path, deps) && (deps.read(change.path)?.includes("OPENBOT_APP_ENGINES") ?? false), ); if (webkitTest) { @@ -874,11 +876,20 @@ function fullBrowserFiles( } } -/** A test that drives a real browser, which `bun test` alone skips. */ -function isBrowserTest(file: string, deps: Pick): boolean { +const browserMarkerRoot = matcher( + "app/tests/**", + "desktop/src/**", + "desktop/tests/**", + "extension/tests/**", + "tests/**", +); + +/** Frontend/root tests may opt in by marker; explicit browser filenames opt in anywhere. */ +export function isBrowserTest(file: string, deps: Pick): boolean { return ( file.endsWith(".browser.test.ts") || - (deps.read(file)?.includes("OPENBOT_APP_BROWSER") ?? false) + (browserMarkerRoot(file) && + (deps.read(file)?.includes("OPENBOT_APP_BROWSER") ?? false)) ); } From 029bc762bb0ce201fba16e3cf20bfd6eb83996f3 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:11:30 -0800 Subject: [PATCH 13/17] CI: build app assets for partial print browser tests --- .github/workflows/ci.yml | 4 +++ scripts/ci-run-tests.test.ts | 48 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c664bfb60..49d111acc1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -974,6 +974,10 @@ jobs: - name: Install WebKit if: needs.changes.outputs.webkit_tests != '[]' || contains(fromJSON(needs.changes.outputs.desktop_browser_tests), 'desktop/src/setupLayout.browser.test.ts') run: bunx playwright-core install --with-deps webkit + # The print-page test serves the shipped HTML, styles and assets from app/dist. + - name: Build the print page and app assets + if: contains(fromJSON(needs.changes.outputs.browser_tests), 'app/tests/artifact-print-browser.test.ts') + run: bun run --cwd app build - name: Run the changed tests env: TESTS: ${{ needs.changes.outputs.tests }} diff --git a/scripts/ci-run-tests.test.ts b/scripts/ci-run-tests.test.ts index aac9487dc1..31fd84f24d 100644 --- a/scripts/ci-run-tests.test.ts +++ b/scripts/ci-run-tests.test.ts @@ -15,6 +15,54 @@ import { data, Evaluator, Lexer, Parser } from "@actions/expressions"; const ROOT = join(import.meta.dir, ".."); const SETUP_TEST = "desktop/src/setupLayout.browser.test.ts"; +test("the partial job builds the shipped app only for the print-page browser test, before testing", () => { + const workflow = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { + jobs: Record; + }; + const steps = workflow.jobs["changed-tests"].steps; + const build = steps.findIndex( + (step) => step.run === "bun run --cwd app build", + ); + const install = steps.findIndex( + (step) => step.run === "bun install --frozen-lockfile", + ); + const tests = steps.findIndex( + (step) => step.run === "bun scripts/ci-run-tests.ts", + ); + expect(build).toBeGreaterThan(install); + expect(build).toBeLessThan(tests); + const condition = steps[build]?.if; + expect(condition).toBeDefined(); + const tree = new Parser( + new Lexer(condition ?? "").lex().tokens, + ["needs"], + [], + ).parse(); + const print = "app/tests/artifact-print-browser.test.ts"; + for (const [files, expected] of [ + [[], false], + [["app/tests/composer-dictation-language.test.tsx"], false], + [[print], true], + [["app/tests/composer-dictation-language.test.tsx", print], true], + [[`${print}.other.test.ts`], false], + [[SETUP_TEST], false], + ] as const) { + const context = JSON.parse( + JSON.stringify({ + needs: { + changes: { outputs: { browser_tests: JSON.stringify(files) } }, + }, + }), + data.reviver, + ) as data.Dictionary; + expect(new Evaluator(tree, context).evaluate()).toEqual( + new data.BooleanData(expected), + ); + } +}); + function runDesktopTests(files: string[], failWebKit = false) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-run-tests-")); try { From 82028b64961abea884b11df4a30333e7b269bc10 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:17:01 -0800 Subject: [PATCH 14/17] CI: bound the entire queued pull request lookup --- scripts/ci-changes.test.ts | 164 ++++++++++++++++++++++++++++++++++++- scripts/ci-changes.ts | 68 ++++++++------- 2 files changed, 201 insertions(+), 31 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 4b97a68811..6268522e94 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -152,6 +152,12 @@ function actionsDecision(options: { grepExit?: number; historyBudgetMs?: number; probeDelayMs?: number; + queue?: { + delays?: Partial>; + fetchFails?: boolean; + calls: string[]; + reason: string; + }; }) { const directory = mkdtempSync(join(tmpdir(), "openbot-ci-changes-test-")); try { @@ -208,6 +214,8 @@ function actionsDecision(options: { proof: options.proof, proofs: options.proofs?.(commits), sha, + queue: options.queue, + queueCalls: join(directory, "queue-calls.jsonl"), historyCalls: options.historyBudgetMs === undefined ? undefined @@ -218,7 +226,7 @@ function actionsDecision(options: { writeFileSync( gh, `#!${process.execPath} -import { readFileSync, writeFileSync } from "node:fs"; +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; const fixture = JSON.parse(readFileSync(process.env.CI_FIXTURE, "utf8")); const args = process.argv.slice(2); @@ -229,6 +237,10 @@ if (args[0] === "run" && args[1] === "download") { writeFileSync(join(args[args.indexOf("--dir") + 1], "ci-tested-tree.txt"), proof); } else { const endpoint = args.find((arg) => arg.startsWith("repos/")); + if (fixture.queue && endpoint?.includes("/pulls/")) { + appendFileSync(fixture.queueCalls, JSON.stringify("api") + "\\n"); + Bun.sleepSync(fixture.queue.delays?.api ?? 0); + } if (fixture.historyCalls && endpoint?.includes("/actions/runs")) writeFileSync(fixture.historyCalls, "called"); if (!(endpoint in fixture.responses)) process.exit(1); const response = fixture.responses[endpoint]; @@ -237,7 +249,11 @@ if (args[0] === "run" && args[1] === "download") { `, ); chmodSync(gh, 0o755); - if (options.grepExit !== undefined || options.probeDelayMs !== undefined) { + if ( + options.grepExit !== undefined || + options.probeDelayMs !== undefined || + options.queue + ) { const realGit = Bun.which("git"); if (!realGit) throw new Error("git is not installed"); const wrappedGit = join(directory, "git"); @@ -245,6 +261,13 @@ if (args[0] === "run" && args[1] === "download") { wrappedGit, `#!${process.execPath} const args = process.argv.slice(2); +const fixture = JSON.parse(require("node:fs").readFileSync(process.env.CI_FIXTURE, "utf8")); +if (fixture.queue && ["fetch", "cat-file"].includes(args[0])) { + const command = args[0] === "fetch" ? "fetch" : "presence"; + require("node:fs").appendFileSync(fixture.queueCalls, JSON.stringify(command) + "\\n"); + Bun.sleepSync(fixture.queue.delays?.[command] ?? 0); + if (command === "fetch") process.exit(fixture.queue.fetchFails ? 1 : 0); +} if (args[0] === "cat-file" && ${options.probeDelayMs !== undefined}) { require("node:fs").writeFileSync(${JSON.stringify(join(directory, "probe-called"))}, "called"); Bun.sleepSync(${options.probeDelayMs ?? 0}); @@ -309,6 +332,16 @@ process.exit(result.exitCode); return {}; } expect(result.exitCode).toBe(0); + if (options.queue) { + const calls = existsSync(join(directory, "queue-calls.jsonl")) + ? readFileSync(join(directory, "queue-calls.jsonl"), "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)) + : []; + expect(calls).toEqual(options.queue.calls); + expect(result.stdout.toString()).toContain(options.queue.reason); + } if (options.historyBudgetMs === 0) expect(existsSync(join(directory, "history-called"))).toBe(false); if (options.probeDelayMs !== undefined) @@ -1868,6 +1901,133 @@ describe("a merge group", () => { expect(running(decision)).toEqual(everyJob); }); + for (const stall of ["api", "fetch", "presence"] as const) { + test(`the real merge-group CLI drops stalled queued-PR ${stall} within its shared budget`, () => { + const started = performance.now(); + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 600, + commits: [{ "server/src/main.ts": "changed" }], + queue: { + delays: { [stall]: 1_800 }, + calls: + stall === "api" + ? ["api"] + : stall === "fetch" + ? ["api", "fetch"] + : ["api", "fetch", "presence"], + reason: + stall === "api" + ? "pull request could not be read" + : stall === "fetch" + ? "passed on main." + : "labelled full-ci", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: stall === "presence" ? [{ name: "full-ci" }] : [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(performance.now() - started).toBeLessThan(1_500); + expect(result.suite).toBe("true"); + }); + } + + test("queued API and fetch share one deadline rather than starting a timer per command", () => { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 600, + commits: [{ "server/src/main.ts": "changed" }], + queue: { + delays: { api: 350, fetch: 350 }, + calls: ["api", "fetch"], + reason: "passed on main.", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("a readable same-repository queued head still supplies PR history", () => { + const result = actionsDecision({ + event: "merge_group", + commits: [{ "server/src/main.ts": "changed" }], + queue: { + calls: ["api", "fetch", "presence"], + reason: "passed on main or on the pull request", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("zero queued-PR budget avoids even its API call and falls back safely", () => { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 0, + commits: [{ "server/src/main.ts": "changed" }], + queue: { calls: [], reason: "pull request could not be read" }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("queued-PR lookup retains labels after fetch failure and never fetches a fork", () => { + for (const fork of [false, true]) { + const result = actionsDecision({ + event: "merge_group", + commits: [{ "README.md": "docs" }], + queue: { + fetchFails: true, + calls: fork ? ["api"] : ["api", "fetch"], + reason: "labelled full-ci", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "README.md" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [{ name: "full-ci" }], + head: { + sha, + repo: { full_name: fork ? "Other/Fork" : "CopilotKit/OpenBot" }, + }, + }, + }), + }); + expect(result.suite).toBe("true"); + } + }); + test("reads the queued pull request from the group's ref", () => { const sha = "bff854d1ab9cc25580bd3efa3308a7f954069c5c"; expect( diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 6be6eaea89..75c4222dc9 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -43,7 +43,8 @@ * Env: GITHUB_EVENT_PATH, GITHUB_EVENT_NAME, GITHUB_REF, GITHUB_SHA, GITHUB_REPOSITORY, * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). * CI_HISTORY_BUDGET_MS can shorten the 45000 ms historical-proof deadline (0..45000); each remote - * history call is limited to the remaining time or 5000 ms, whichever is less. Writes one + * history call is limited to the remaining time or 5000 ms, whichever is less. The optional queued + * PR lookup shares a separate 5000 ms deadline, shortened by the same override (0 skips it). Writes one * output per job (`true` to run it), the changed tests as JSON arrays, and `queue_run` (the merge * queue's run that stands in for this one, or empty) to $GITHUB_OUTPUT, and what it decided and why * to $GITHUB_STEP_SUMMARY. @@ -1339,6 +1340,25 @@ export function testedCheckout( return undefined; } +/** One monotonic deadline for optional remote proof commands, with a shorter test override. */ +function historyCommands(maximumMs: number) { + const requested = process.env.CI_HISTORY_BUDGET_MS; + const budgetMs = + requested !== undefined && /^\d+$/.test(requested) + ? Math.min(maximumMs, Number(requested)) + : maximumMs; + const deadline = performance.now() + budgetMs; + const remaining = () => Math.max(0, Math.floor(deadline - performance.now())); + return { + remaining, + run: (cmd: string[]) => { + const timeout = Math.min(5_000, remaining()); + if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); + return exec(cmd, undefined, timeout); + }, + }; +} + function liveDeps( workflow: Workflow, repository: string, @@ -1346,19 +1366,7 @@ function liveDeps( trustedRepositories: string[], ): Deps { const trusted = trustedRepositories.map((name) => name.toLowerCase()); - // Test overrides can shorten this deadline, never extend it beyond the production bound. - const requestedBudget = process.env.CI_HISTORY_BUDGET_MS; - const budgetMs = - requestedBudget !== undefined && /^\d+$/.test(requestedBudget) - ? Math.min(45_000, Number(requestedBudget)) - : 45_000; - const deadline = performance.now() + budgetMs; - const remaining = () => Math.max(0, Math.floor(deadline - performance.now())); - const historyCommand = (cmd: string[]) => { - const timeout = Math.min(5_000, remaining()); - if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); - return exec(cmd, undefined, timeout); - }; + const { remaining, run: historyCommand } = historyCommands(45_000); const browserChecks = new Set( CI_RULES.filter((rule) => ["app_browser", "app_browser_webkit"].includes(rule.output), @@ -1596,9 +1604,10 @@ function queuedPull( ): MergeGroup["pr"] | undefined { const number = queuedPullRequest(headRef); if (number === undefined) return undefined; + const { run } = historyCommands(5_000); try { const pull = JSON.parse( - exec(["gh", "api", `repos/${repository}/pulls/${number}`]), + run(["gh", "api", `repos/${repository}/pulls/${number}`]), ) as { labels?: { name: string }[]; head: { sha: string; repo?: { full_name?: string } | null }; @@ -1607,20 +1616,21 @@ function queuedPull( const ours = pull.head.repo?.full_name?.toLowerCase() === repository.toLowerCase(); if (!ours || !/^[0-9a-f]{40}$/.test(pull.head.sha)) return { labels }; - // Its commits and trees, as the pull request's own `changes` job fetches them. - const fetched = Bun.spawnSync([ - "git", - "fetch", - "--no-tags", - "--filter=blob:none", - "origin", - `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`, - ]); - const has = - fetched.exitCode === 0 && - Bun.spawnSync(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]) - .exitCode === 0; - return has ? { labels, head: pull.head.sha } : { labels }; + // Its commits and trees share the API call's deadline; failed lookups retain readable labels. + try { + run([ + "git", + "fetch", + "--no-tags", + "--filter=blob:none", + "origin", + `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`, + ]); + run(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]); + return { labels, head: pull.head.sha }; + } catch { + return { labels }; + } } catch { return undefined; } From 8e320be7e59dc8eedfbf0c52e4e1a0d9dabdae54 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:20:18 -0800 Subject: [PATCH 15/17] CI: require readable queue labels before skipping docs checks --- scripts/ci-changes.test.ts | 56 ++++++++++++++++++++++++++++++++++++-- scripts/ci-changes.ts | 10 +++---- 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 6268522e94..e3f96fbfcd 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1593,8 +1593,54 @@ describe("a merge group", () => { expect(result.suite).toBe("false"); }); + test("docs require readable queued-PR metadata before they can skip full checks", () => { + const minimal = { mentions: () => [], read: () => "" }; + for (const group of [ + undefined, + { head: "merge" }, + { head: "merge", pr: { labels: ["full-ci"] } }, + ]) { + const result = decideMergeGroup("ci", ["README.md"], minimal, group); + expect(result.ignoredOnly).toBe(false); + expect(running(result)).toEqual(everyJob); + } + const readable = decideMergeGroup("ci", ["README.md"], minimal, { + head: "merge", + pr: { labels: [] }, + }); + expect(readable.ignoredOnly).toBe(true); + expect(running(readable)).toEqual([]); + }); + + test("the real docs-only merge-group CLI runs full checks when its full-ci label cannot be read", () => { + for (const budget of [0, 600]) { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: budget, + commits: [{ "README.md": "docs" }], + queue: { + delays: { api: 1_800 }, + calls: budget === 0 ? [] : ["api"], + reason: "pull request could not be read", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "README.md" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [{ name: "full-ci" }], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.ignored_only).toBe("false"); + expect(result.suite).toBe("true"); + expect(result.build).toBe("true"); + } + }); + test("that changes only CHANGELOG.md runs nothing, not even the tests that name it", () => { - const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL); + const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL, GROUP); expect(running(decision)).toEqual([]); expect(decision.ignoredOnly).toBe(true); expect(decision.reasons[0]).toContain("CHANGELOG.md"); @@ -1605,6 +1651,7 @@ describe("a merge group", () => { "ci", [...UNREAD_DOCS, "CHANGELOG.md"], REAL, + GROUP, ); expect(running(decision)).toEqual( decision.tests.length > 0 ? ["partial"] : [], @@ -1618,7 +1665,12 @@ describe("a merge group", () => { }); test("a doc a test reads runs that test, and no job", () => { - const decision = decideMergeGroup("ci", ["docs/agent-frameworks.md"], REAL); + const decision = decideMergeGroup( + "ci", + ["docs/agent-frameworks.md"], + REAL, + GROUP, + ); expect(running(decision)).toEqual(["partial"]); expect(decision.tests).toContain( "tests/agent-frameworks-receivers.test.ts", diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 75c4222dc9..36547ce981 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -1170,6 +1170,11 @@ export function decideMergeGroup( ...fullDecision(workflow, why, deps, currentChanges), ignoredOnly: false, }); + if (!group?.pr) { + return full( + "A merge group whose pull request could not be read: everything runs.", + ); + } // The explicit override applies even when every changed file is a document. if (group?.pr?.labels.includes("full-ci")) { return full( @@ -1227,11 +1232,6 @@ export function decideMergeGroup( if (!group || !ancestors || !passed || !diff || !releaseViolations) { return full("A merge group: everything runs."); } - if (!group.pr) { - return full( - "A merge group whose pull request could not be read: everything runs.", - ); - } if (group.pr.labels.includes("full-ci")) { return full( "A merge group of a pull request labelled full-ci: everything runs.", From 8b7f93ff2b368512f08669e5313e95dc3659587f Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 05:33:12 -0800 Subject: [PATCH 16/17] Tests: await company sign-in socket before holding out the page --- app/tests/company-sign-in.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/tests/company-sign-in.test.tsx b/app/tests/company-sign-in.test.tsx index c51c97d5de..ce2e9710ad 100644 --- a/app/tests/company-sign-in.test.tsx +++ b/app/tests/company-sign-in.test.tsx @@ -424,6 +424,8 @@ test("Harbor begins to hold her out while the app is open: the first request ref heldOut = false; const { view } = openApp(); await view.findByText("The app"); + // Home can draw before its socket opens: hold out an established page, not a pending handshake. + await waitFor(() => expect(sockets).toHaveLength(1)); heldOut = true; // Anything the page asks next, as it would on its next read. From e5d6d368f5cb8dd3875a657e1b073bf7b47afae1 Mon Sep 17 00:00:00 2001 From: Dusty Date: Wed, 2 Dec 2026 14:01:59 -0800 Subject: [PATCH 17/17] CI: no browser test runs twice, and only full-ci replaces a run - Only the full-ci label cancels and replaces a pull request's CI run. Any other label waits for the run in progress, then finds its checks passed on the same commit and skips them. A label run cannot skip everything up front: a skipped verify counts as passing. - 14 files in the cross-browser list ignored the engine selection and ran in full in both the Chromium and the WebKit leg, artifacts-screens (about 11 minutes) among them. They now run where Chromium is selected (ownBrowsersAsked), once. sidebar-window-buttons launches through launchBrowserEngines. A test holds every listed file to the selection. - A full browser job that runs covers the changed files in its list, so they no longer run a second time in tests (changed files). The desktop setup window's step names its file in a list the planner can read. - The queued pull request's head is fetched on a deadline of its own, and a merge group that has to go without its history says why. - The budget test builds matrix legs as GitHub does: include and exclude are lists of legs, not axes. - Comments and docs/releasing.md name the engine and shard checks. --- .github/workflows/ci.yml | 27 +++++-- app/tests/artifact-bridge-browser.test.ts | 4 +- app/tests/artifact-collab-browser.test.tsx | 4 +- .../artifact-error-notice-layout.test.tsx | 4 +- app/tests/artifact-events-socket.test.ts | 4 +- app/tests/artifact-kinds-browser.test.tsx | 4 +- app/tests/artifacts-kit.test.ts | 4 +- app/tests/artifacts-screens.test.tsx | 4 +- app/tests/board-row-layout.test.tsx | 4 +- app/tests/browser-engines.test.ts | 49 +++++++++++- app/tests/browser-engines.ts | 38 +++++++-- app/tests/plan-notices-layout.test.tsx | 4 +- app/tests/renderer-crash.test.ts | 4 +- app/tests/select-scrolls-layout.test.tsx | 4 +- app/tests/sidebar-current-row.test.tsx | 4 +- app/tests/sidebar-window-buttons.test.tsx | 17 ++-- app/tests/trusted-types-build.test.ts | 4 +- app/tests/workspace-snapshots-layout.test.tsx | 4 +- docs/releasing.md | 2 +- scripts/ci-budgets.test.ts | 79 ++++++++++++++++--- scripts/ci-changes.test.ts | 49 ++++++++++-- scripts/ci-changes.ts | 65 ++++++++++++--- scripts/release-publish-order.test.ts | 3 +- scripts/workflow-concurrency.test.ts | 12 ++- 24 files changed, 326 insertions(+), 71 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49d111acc1..344710af26 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,12 +36,15 @@ permissions: # GitHub drops from the group's one pending slot is re-run later by Contributor CI # (scripts/contributor-ci.ts), which also pauses fork runs while CopilotKit's are waiting. # -# A pull request's newer push or label starts a replacement run. The release's call runs with the release -# push's context, a push to main or to a release branch, and is never cancelled by the next one -# (scripts/workflow-concurrency.test.ts). +# A pull request's newer push, or the `full-ci` label, starts a replacement run. Any other label waits +# for the run in progress instead of cancelling it: once that run is done, the waiting run finds every +# check it passed on the same commit, skips them, and takes a minute. A label run cannot simply skip +# everything up front: a skipped `verify` counts as passing, and could turn a failing pull request +# green. The release's call runs with the release push's context, a push to main or to a release +# branch, and is never cancelled by the next one (scripts/workflow-concurrency.test.ts). concurrency: group: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && format('ci-{0}-forks', github.workflow) || format('ci-{0}-{1}', github.workflow, github.ref == 'refs/heads/main' && github.sha || github.ref) }} - cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }} + cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') }} # Runners. The checks run on the 16-core larger runners (org runner group openbot-larger, billed per # minute) for main, releases and pull requests from this repository: the standard runners are shared @@ -607,8 +610,12 @@ jobs: # link, the page, a reload, and the bare address an older tab kept. In the image, as above: # WebKit's system packages are about 94 MB, which took nine minutes from the mirror on a slow day. # + # Each shard runs twice, once per engine: OPENBOT_APP_ENGINES names one, and every file opens only + # the engines it names (app/tests/browser-engines.ts). A file that only ever runs in Chromium skips + # itself in the WebKit leg, so no file runs the same browser twice (scripts/ci-changes.test.ts). + # # The files run side by side, like the Chromium list's, but eight at a time rather than a worker - # per core: each file opens Chromium and WebKit, and sixteen workers' 32 browsers on 16 cores + # per core: each file used to open Chromium and WebKit, and sixteen workers' 32 browsers on 16 cores # starved the tests that wait on a clock (a hold's Retry-After, a menu's load). This job began # with one file and ran its list one file after another; by 24 November it held 30 files in two # engines each, took 35 minutes and was the whole length of a run. Add a new file to this one @@ -631,7 +638,8 @@ jobs: name: app (real browser, ${{ matrix.engine }}) (shard ${{ matrix.shard }} of 3) needs: changes strategy: - # Each engine/shard keeps its own runner and result; failures leave the other legs running. + # Each engine and shard has its own runner and result, so a failed leg can be re-run on its + # own. A failure still stops the whole run at once (.github/actions/stop-on-failure). fail-fast: false matrix: engine: [Chromium, WebKit] @@ -813,13 +821,18 @@ jobs: - run: bun install --frozen-lockfile - run: bun install --frozen-lockfile working-directory: desktop + # A list, as in the jobs above, so scripts/ci-changes.ts can tell this job covers the file and a + # change to it does not run it a second time in `tests (changed files)`. Paths from desktop/. - run: | + files=( + src/setupLayout.browser.test.ts + ) docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE/desktop" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 \ "$PLAYWRIGHT_IMAGE" \ - bun test src/setupLayout.browser.test.ts + bun test "${files[@]}" # Connect your AI's key field and tab row, in WebKit, the engine the Mac window draws with. # Only those tests: the rest of the file runs in Chromium in the step above. - run: | diff --git a/app/tests/artifact-bridge-browser.test.ts b/app/tests/artifact-bridge-browser.test.ts index 38a00b90ee..40dd88aedb 100644 --- a/app/tests/artifact-bridge-browser.test.ts +++ b/app/tests/artifact-bridge-browser.test.ts @@ -2,6 +2,7 @@ import { afterAll, describe, expect } from "bun:test"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import type { Browser, Frame, Page } from "playwright-core"; +import { ownBrowsersAsked } from "./browser-engines"; import { test } from "./renderer-crash"; /** @@ -20,7 +21,8 @@ import { test } from "./renderer-crash"; * Why it is worth a browser: an opaque origin, the sandbox, CSP and MessageChannel transfer are the * browser's, and a test without them proves nothing about them. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const APP = join(import.meta.dir, ".."); diff --git a/app/tests/artifact-collab-browser.test.tsx b/app/tests/artifact-collab-browser.test.tsx index e34987b75c..385eb5a02d 100644 --- a/app/tests/artifact-collab-browser.test.tsx +++ b/app/tests/artifact-collab-browser.test.tsx @@ -13,6 +13,7 @@ import { fakeArtifactServer, type Person, } from "./artifact-pages-api"; +import { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; /** @@ -30,7 +31,8 @@ import { still } from "./page-still"; * * With OPENBOT_APP_SHOTS= each screen is saved in light and dark, at 400 and 1280 wide. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/artifact-error-notice-layout.test.tsx b/app/tests/artifact-error-notice-layout.test.tsx index b943619362..63049fe1d4 100644 --- a/app/tests/artifact-error-notice-layout.test.tsx +++ b/app/tests/artifact-error-notice-layout.test.tsx @@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; import { test } from "./renderer-crash"; @@ -18,7 +19,8 @@ import { test } from "./renderer-crash"; * * With OPENBOT_APP_SHOTS= it saves each as artifact-error-notice--.png. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/artifact-events-socket.test.ts b/app/tests/artifact-events-socket.test.ts index eb8d230f5e..9a64e91bef 100644 --- a/app/tests/artifact-events-socket.test.ts +++ b/app/tests/artifact-events-socket.test.ts @@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { join } from "node:path"; import type { Server, ServerWebSocket } from "bun"; import type { Browser } from "playwright-core"; +import { ownBrowsersAsked } from "./browser-engines"; import { marksPlugin } from "./marks-plugin"; /** @@ -18,7 +19,8 @@ import { marksPlugin } from "./marks-plugin"; * * OPENBOT_APP_BROWSER=1 bun test app/tests/artifact-events-socket.test.ts */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const EVENTS = /\/api\/v2\/organizations\/[^/]+\/artifacts\/[^/]+\/events$/; type Behaviour = "not-here" | "drops"; diff --git a/app/tests/artifact-kinds-browser.test.tsx b/app/tests/artifact-kinds-browser.test.tsx index b409294b66..e09153a2de 100644 --- a/app/tests/artifact-kinds-browser.test.tsx +++ b/app/tests/artifact-kinds-browser.test.tsx @@ -9,6 +9,7 @@ import { import { basename, dirname, join } from "node:path"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; import { marksPlugin } from "./marks-plugin"; import { test } from "./renderer-crash"; @@ -21,7 +22,8 @@ import { test } from "./renderer-crash"; * With OPENBOT_APP_SHOTS= every page is saved as kinds---.png, beside the * app's own gallery cards (kinds-reference-…), to look at side by side. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/artifacts-kit.test.ts b/app/tests/artifacts-kit.test.ts index 4f66e689b0..c9e1cb77a6 100644 --- a/app/tests/artifacts-kit.test.ts +++ b/app/tests/artifacts-kit.test.ts @@ -15,6 +15,7 @@ import { build } from "esbuild"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { scheme, TOKENS } from "../../tokens/src/scheme"; +import { ownBrowsersAsked } from "./browser-engines"; /** * The artifacts kit: what a Bot's page is compiled against (app/scripts/build-artifacts-kit.ts). @@ -34,7 +35,8 @@ const APP = join(import.meta.dir, ".."); const ROOT = join(APP, ".."); const SCRIPT = join(APP, "scripts", "build-artifacts-kit.ts"); const RUNTIME_SOURCE = join(APP, "src/lib/artifacts/bridge/page-runtime.ts"); -const browserAsked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens Chromium itself, so it runs where Chromium is selected (browser-engines.ts). +const browserAsked = ownBrowsersAsked(); const shots = process.env.OPENBOT_SHOTS; let scratch: string; diff --git a/app/tests/artifacts-screens.test.tsx b/app/tests/artifacts-screens.test.tsx index 75ca747e3d..487e5e9451 100644 --- a/app/tests/artifacts-screens.test.tsx +++ b/app/tests/artifacts-screens.test.tsx @@ -20,6 +20,7 @@ import { THUMBNAIL_DARK_SHA, THUMBNAIL_LIGHT_SHA, } from "./artifacts-api"; +import { ownBrowsersAsked } from "./browser-engines"; import { marksPlugin } from "./marks-plugin"; import { still } from "./page-still"; @@ -43,7 +44,8 @@ import { still } from "./page-still"; * --.png, in light and dark, wide (1440), narrow (700, the panel a sheet) and * at a phone's width (390), beside one of the app's own pages (Teams) to compare them with. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/board-row-layout.test.tsx b/app/tests/board-row-layout.test.tsx index bc691e4efd..10b75bfe13 100644 --- a/app/tests/board-row-layout.test.tsx +++ b/app/tests/board-row-layout.test.tsx @@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Browser, BrowserType, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; /** * A Needs you board row keeps its words readable at every width the board is drawn at. @@ -20,7 +21,8 @@ import { compile } from "tailwindcss"; * With OPENBOT_APP_SHOTS= it also saves the rows at each width, light and dark, in each * browser, as board-row---.png. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/browser-engines.test.ts b/app/tests/browser-engines.test.ts index a68423fef3..f105354fd8 100644 --- a/app/tests/browser-engines.test.ts +++ b/app/tests/browser-engines.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from "bun:test"; -import { launchBrowserEngines } from "./browser-engines"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { launchBrowserEngines, ownBrowsersAsked } from "./browser-engines"; describe("browser engine selection", () => { for (const [selection, expected] of [ @@ -78,3 +80,48 @@ describe("browser engine selection", () => { expect(launched).toBe(false); }); }); + +/** Built, not written out: a file naming the variable outright is taken for a real-browser test. */ +const ASK = ["OPENBOT", "APP", "BROWSER"].join("_"); + +describe("a file that opens its own browsers", () => { + test("runs where Chromium is selected, and only when real-browser tests are asked for", () => { + for (const [env, runs] of [ + [{}, false], + [{ [ASK]: "1" }, true], + [{ [ASK]: "1", OPENBOT_APP_ENGINES: "chromium" }, true], + [{ [ASK]: "1", OPENBOT_APP_ENGINES: "chromium,webkit" }, true], + [{ [ASK]: "1", OPENBOT_APP_ENGINES: "webkit" }, false], + ] as const) { + expect({ env, runs: ownBrowsersAsked(env) }).toEqual({ env, runs }); + } + expect(() => + ownBrowsersAsked({ + [ASK]: "1", + OPENBOT_APP_ENGINES: "firefox", + }), + ).toThrow("Unsupported browser engine: firefox"); + }); + + test("CI's cross-browser list: every file opens only the engine its run selects, or runs once", () => { + // The list runs once per engine. A file that ignored the selection ran in full in both runs: + // artifacts-screens, the slowest file, twice. Each file must read OPENBOT_APP_ENGINES, launch + // through launchBrowserEngines, or gate on ownBrowsersAsked. + const root = join(import.meta.dir, "..", ".."); + const ci = Bun.YAML.parse( + readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"), + ) as { jobs: Record }; + const listed = (ci.jobs["app-browser-webkit"]?.steps ?? []).flatMap( + (step) => + (step.run ?? "").match(/app\/tests\/[\w.-]+\.test\.tsx?/g) ?? [], + ); + expect(listed.length).toBeGreaterThan(50); + const ignoring = [...new Set(listed)].filter( + (file) => + !/OPENBOT_APP_ENGINES|launchBrowserEngines|ownBrowsersAsked/.test( + readFileSync(join(root, file), "utf8"), + ), + ); + expect(ignoring).toEqual([]); + }); +}); diff --git a/app/tests/browser-engines.ts b/app/tests/browser-engines.ts index 95cfa526b4..d34ae22b62 100644 --- a/app/tests/browser-engines.ts +++ b/app/tests/browser-engines.ts @@ -2,19 +2,43 @@ type BrowserFactory = { launch(options?: { channel?: string }): Promise; }; +/** The engines OPENBOT_APP_ENGINES names, Chromium when it names none. */ +export function selectedEngines( + selection: string | undefined, +): Set<"chromium" | "webkit"> { + const selected = new Set<"chromium" | "webkit">(); + for (const engine of (selection?.trim() || "chromium").split(",")) { + const name = engine.trim(); + if (name !== "chromium" && name !== "webkit") { + throw new Error(`Unsupported browser engine: ${name}`); + } + selected.add(name); + } + return selected; +} + +/** + * Whether a real-browser test file that opens its own browsers, rather than the engines + * OPENBOT_APP_ENGINES selects, runs: real-browser tests are asked for and Chromium is selected, + * as it is by default. Such a file opens Chromium alone, or both engines itself. CI's cross-browser + * list runs once per engine, so it runs there once, in the Chromium run, not twice. + */ +export function ownBrowsersAsked( + env: Record = process.env, +): boolean { + return ( + env.OPENBOT_APP_BROWSER === "1" && + selectedEngines(env.OPENBOT_APP_ENGINES).has("chromium") + ); +} + /** Launch only the selected engines. The caller retains cleanup ownership, including on failure. */ export async function launchBrowserEngines( factories: Record<"chromium" | "webkit", BrowserFactory>, selection: string | undefined, opened: [string, T][], ): Promise { - const selected = new Set( - (selection?.trim() || "chromium").split(",").map((engine) => engine.trim()), - ); - for (const engine of selected) { - if (engine !== "chromium" && engine !== "webkit") { - throw new Error(`Unsupported browser engine: ${engine}`); - } + for (const engine of selectedEngines(selection)) { // CI installs full Chromium without the headless shell. const browser = engine === "chromium" diff --git a/app/tests/plan-notices-layout.test.tsx b/app/tests/plan-notices-layout.test.tsx index cb1a399fee..c4f30827f1 100644 --- a/app/tests/plan-notices-layout.test.tsx +++ b/app/tests/plan-notices-layout.test.tsx @@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; /** @@ -17,7 +18,8 @@ import { still } from "./page-still"; * With OPENBOT_APP_SHOTS= it also saves each scene and state as plan--.png, and * the trial's screens in light and dark, wide and on a phone, beside one of the app's own dialogs. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/renderer-crash.test.ts b/app/tests/renderer-crash.test.ts index 61e7c0b57b..10902c10d1 100644 --- a/app/tests/renderer-crash.test.ts +++ b/app/tests/renderer-crash.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "bun:test"; import { join } from "node:path"; +import { ownBrowsersAsked } from "./browser-engines"; /** * A real-browser test the browser's renderer crashed in runs again, up to twice, and so does one where @@ -14,7 +15,8 @@ import { join } from "node:path"; * * OPENBOT_APP_BROWSER=1 bun test app/tests/renderer-crash.test.ts */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); describe.skipIf(!asked)("a renderer crash in a real-browser test", () => { test("is run again, up to twice; any other failure is not", async () => { diff --git a/app/tests/select-scrolls-layout.test.tsx b/app/tests/select-scrolls-layout.test.tsx index 0c5c780111..651e6b217f 100644 --- a/app/tests/select-scrolls-layout.test.tsx +++ b/app/tests/select-scrolls-layout.test.tsx @@ -10,6 +10,7 @@ import { existsSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; /** @@ -31,7 +32,8 @@ import { still } from "./page-still"; * * With OPENBOT_APP_SHOTS= each open select is saved as select-scrolls-arrow-.png. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); // A browser opens a page per case, and the arrow scrolls only while it is hovered. setDefaultTimeout(20_000); const shots = process.env.OPENBOT_APP_SHOTS; diff --git a/app/tests/sidebar-current-row.test.tsx b/app/tests/sidebar-current-row.test.tsx index e0e94cdda7..fd20757b87 100644 --- a/app/tests/sidebar-current-row.test.tsx +++ b/app/tests/sidebar-current-row.test.tsx @@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; /** @@ -29,7 +30,8 @@ import { still } from "./page-still"; * * With OPENBOT_APP_SHOTS= it also saves the strip on /invitations in each case. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/app/tests/sidebar-window-buttons.test.tsx b/app/tests/sidebar-window-buttons.test.tsx index bef8dd2c79..7333c38475 100644 --- a/app/tests/sidebar-window-buttons.test.tsx +++ b/app/tests/sidebar-window-buttons.test.tsx @@ -1,13 +1,14 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import type { Browser, BrowserType, Page } from "playwright-core"; +import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { ListConnectionsResponse } from "@/lib/api/generated/connections/connections.zod"; import { ListImportsResponse } from "@/lib/api/generated/moving-to-openbot-cloud/moving-to-openbot-cloud.zod"; import { GetPreferencesResponse } from "@/lib/api/generated/people/people.zod"; import { personBody } from "./accounts-api"; import { type AppsFixture, answerAppsApi } from "./apps-api"; +import { launchBrowserEngines } from "./browser-engines"; import { conversationPage } from "./conversations-api"; import { still } from "./page-still"; @@ -30,8 +31,8 @@ import { still } from "./page-still"; * * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/sidebar-window-buttons.test.tsx * - * Chromium always, WebKit too (the engine OpenBot Desktop's Mac window draws with) when - * `OPENBOT_APP_ENGINES` names it. With OPENBOT_APP_SHOTS= it saves each case's corner, with + * Chromium by default; `OPENBOT_APP_ENGINES` selects Chromium, WebKit (the engine OpenBot Desktop's + * Mac window draws with) or both. With OPENBOT_APP_SHOTS= it saves each case's corner, with * the buttons' area outlined, as sidebar-window-buttons--.png. */ const asked = process.env.OPENBOT_APP_BROWSER === "1"; @@ -372,11 +373,11 @@ beforeAll(async () => { readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`]+/), ); css = await stylesheet([...new Set(sources)].sort()); - const { chromium, webkit } = await import("playwright-core"); - // The CI job installs full Chromium without the headless shell. - engines.push(["chromium", await chromium.launch({ channel: "chromium" })]); - if ((process.env.OPENBOT_APP_ENGINES ?? "").includes("webkit")) - engines.push(["webkit", await (webkit as BrowserType).launch()]); + await launchBrowserEngines( + await import("playwright-core"), + process.env.OPENBOT_APP_ENGINES, + engines, + ); }); afterAll(async () => { diff --git a/app/tests/trusted-types-build.test.ts b/app/tests/trusted-types-build.test.ts index a2ede4dadb..074d5e8772 100644 --- a/app/tests/trusted-types-build.test.ts +++ b/app/tests/trusted-types-build.test.ts @@ -14,6 +14,7 @@ import { getGetArtifactResponseMock, getGetArtifactVersionResponseMock, } from "@/lib/api/generated/artifacts/artifacts.msw"; +import { ownBrowsersAsked } from "./browser-engines"; /** * THE BUILT APP LOADS WITH NO TRUSTED TYPES VIOLATION, AND DRAWS MERMAID UNDER THEM. @@ -37,7 +38,8 @@ import { * It runs `vite build` first (about a minute); OPENBOT_APP_DIST= uses a build already made. * With OPENBOT_APP_SHOTS= each diagram is saved as tt-build--.png. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); const ORGANIZATION = "/api/v2/organizations/default"; diff --git a/app/tests/workspace-snapshots-layout.test.tsx b/app/tests/workspace-snapshots-layout.test.tsx index 6d0348c906..5440e61261 100644 --- a/app/tests/workspace-snapshots-layout.test.tsx +++ b/app/tests/workspace-snapshots-layout.test.tsx @@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Browser, Page } from "playwright-core"; import { compile } from "tailwindcss"; +import { ownBrowsersAsked } from "./browser-engines"; import { still } from "./page-still"; /** @@ -16,7 +17,8 @@ import { still } from "./page-still"; * * With OPENBOT_APP_SHOTS= it also saves each as copies---.png. */ -const asked = process.env.OPENBOT_APP_BROWSER === "1"; +// Opens its own browsers, so it runs where Chromium is selected (browser-engines.ts). +const asked = ownBrowsersAsked(); const shots = process.env.OPENBOT_APP_SHOTS; const APP = join(import.meta.dir, ".."); diff --git a/docs/releasing.md b/docs/releasing.md index 83271dfdb5..1d0de93fe1 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1126,7 +1126,7 @@ A job added to `ci.yml` is covered by it without anybody updating a list. | `format, lint, types` | the ordinary things, across every workspace, and a desktop version that has left the release version | | `API spec` | a bundled spec that is not what its sources bundle to, a broken API convention, a generated client that is not the committed one, or, on a pull request, a breaking change to the API or the live channels | | `native types` | a type error in the `mobile` app, which installs from its own npm lockfile | -| `app (real browser)`, `app (real browser, WebKit)`, `app (real browser, desktop setup window)` | the app and desktop setup window behavior only a real Chromium shows, such as layout, and following the system's light or dark, and dictation's languages in WebKit, the engine the Mac window draws with | +| `app (real browser)`, `app (real browser, Chromium) (shard N of 3)`, `app (real browser, WebKit) (shard N of 3)`, `app (real browser, desktop setup window)` | the app and desktop setup window behavior only a real browser shows, such as layout, and following the system's light or dark, in Chromium and in WebKit, the engine the Mac window draws with: the cross-browser list runs in three shards for each engine, and all six must pass | | `tests` | a decision made wrongly, in isolation | | `python harness (agent-crewai)` and one per harness | a provider-boundary regression in that Python Bot harness | | `compose config` | a Compose file an older Compose cannot read | diff --git a/scripts/ci-budgets.test.ts b/scripts/ci-budgets.test.ts index 11a5c8732d..82def9dbff 100644 --- a/scripts/ci-budgets.test.ts +++ b/scripts/ci-budgets.test.ts @@ -51,6 +51,47 @@ const watch = Bun.YAML.parse( readFileSync(join(WORKFLOWS, "ci-watch.yml"), "utf8"), ) as { on: { workflow_run: { workflows: string[] } } }; +type Leg = Record; + +/** + * A matrix's legs as GitHub builds them: every combination of its arrays, less the `exclude` + * entries, then each `include` entry added to every leg whose values it keeps, or as a leg of its + * own when it keeps none. `include` and `exclude` are lists of legs, not axes. + */ +function legs(matrix: Record | undefined): Leg[] { + const axes = Object.entries(matrix ?? {}).filter( + (entry): entry is [string, unknown[]] => + entry[0] !== "include" && + entry[0] !== "exclude" && + Array.isArray(entry[1]), + ); + const keys = new Set(axes.map(([key]) => key)); + let built: Leg[] = + axes.length === 0 + ? [] + : axes.reduce( + (legsSoFar, [key, values]) => + legsSoFar.flatMap((leg) => + values.map((value) => ({ ...leg, [key]: value })), + ), + [{}], + ); + const matches = (leg: Leg, entry: Leg) => + Object.entries(entry).every(([key, value]) => leg[key] === value); + const excluded = (matrix?.exclude ?? []) as Leg[]; + built = built.filter((leg) => !excluded.some((entry) => matches(leg, entry))); + for (const entry of (matrix?.include ?? []) as Leg[]) { + const kept = built.filter((leg) => + Object.entries(entry).every( + ([key, value]) => !keys.has(key) || leg[key] === value, + ), + ); + if (kept.length > 0) for (const leg of kept) Object.assign(leg, entry); + else built.push({ ...entry }); + } + return built.length > 0 ? built : [{}]; +} + /** * The budget names a job reports under: its matrix expanded where the name uses it, and where a * part of the name is known only once the run starts, the wildcard every leg shares. @@ -58,19 +99,15 @@ const watch = Bun.YAML.parse( function names(id: string, job: Job): string[] { const name = job.name ?? id; if (!name.includes(EXPRESSION)) return [name]; - let expanded = [name]; - let total = 1; - for (const [key, values] of Object.entries(job.strategy?.matrix ?? {})) { - if (!Array.isArray(values)) continue; - total *= values.length; - expanded = expanded.flatMap((value) => - values.map((choice) => - value.replaceAll(`${EXPRESSION} matrix.${key} }}`, String(choice)), - ), - ); - } - expanded = expanded.map((value) => - value.replaceAll(`${EXPRESSION} strategy.job-total }}`, String(total)), + const all = legs(job.strategy?.matrix as Record); + const expanded = all.map((leg) => + Object.entries(leg) + .reduce( + (value, [key, choice]) => + value.replaceAll(`${EXPRESSION} matrix.${key} }}`, String(choice)), + name, + ) + .replaceAll(`${EXPRESSION} strategy.job-total }}`, String(all.length)), ); return [ ...new Set( @@ -79,6 +116,22 @@ function names(id: string, job: Job): string[] { ]; } +describe("a job's matrix legs", () => { + test("include and exclude are lists of legs, not axes", () => { + expect(legs({ shard: [1, 2] })).toEqual([{ shard: 1 }, { shard: 2 }]); + expect( + legs({ os: ["a", "b"], shard: [1, 2], exclude: [{ os: "b", shard: 2 }] }), + ).toHaveLength(3); + // An entry keeping a leg's values extends it; one keeping none is a leg of its own. + expect( + legs({ + shard: [1, 2], + include: [{ shard: 1, big: true }, { shard: 3 }], + }), + ).toEqual([{ shard: 1, big: true }, { shard: 2 }, { shard: 3 }]); + }); +}); + describe("every job has a time limit", () => { for (const file of files) { test(file, () => { diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index e3f96fbfcd..cb5aaef190 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -4,8 +4,8 @@ import { existsSync, mkdirSync, mkdtempSync, - readFileSync, readdirSync, + readFileSync, rmSync, writeFileSync, } from "node:fs"; @@ -21,8 +21,8 @@ import { decideDesktopMainPush, decideMainPush, decideMergeGroup, - isBunTest, isBrowserTest, + isBunTest, isCode, isDocs, isIgnored, @@ -613,7 +613,9 @@ describe("a pull request push", () => { expect(result.run.app_browser_webkit).toBe(true); expect(result.browserTests).toEqual(extra ? [unlisted] : []); expect(result.webkitTests).toEqual(extra ? [unlisted] : []); - expect(result.desktopBrowserTests).toEqual(extra ? [desktop] : []); + // The app changed, so the desktop setup window's job runs its whole file: no second run. + expect(result.run.app_browser).toBe(true); + expect(result.desktopBrowserTests).toEqual([]); expect(result.run.partial).toBe(extra); } }); @@ -1926,6 +1928,19 @@ describe("a merge group", () => { // Without the pull request's run, the WebKit list reads the app change since main's run. expect(decision.run.app_browser_webkit).toBe(true); expect(decision.run.python_harness).toBe(false); + // The summary says why, so a slow fetch is never a silent rerun of what the pull request passed. + const slow = decideMergeGroup( + "ci", + ["app/src/lib/marks.ts"], + groupDeps(APP_PR_HARNESS_MAIN), + { + head: "g", + pr: { labels: [], noHead: "its head could not be fetched: timed out" }, + }, + ); + expect(slow.reasons[0]).toContain( + "The pull request's own runs are not used: its head could not be fetched: timed out.", + ); }); test("runs everything for a pull request labelled full-ci, or one that could not be read", () => { @@ -1990,15 +2005,39 @@ describe("a merge group", () => { }); } - test("queued API and fetch share one deadline rather than starting a timer per command", () => { + test("the queued head's fetch has its own deadline, not what the API call left", () => { const result = actionsDecision({ event: "merge_group", historyBudgetMs: 600, commits: [{ "server/src/main.ts": "changed" }], queue: { delays: { api: 350, fetch: 350 }, + calls: ["api", "fetch", "presence"], + reason: "passed on main or on the pull request", + }, + responses: (sha, commits) => ({ + [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { + files: [{ filename: "server/src/main.ts" }], + }, + "repos/CopilotKit/OpenBot/pulls/7": { + labels: [], + head: { sha, repo: { full_name: "CopilotKit/OpenBot" } }, + }, + }), + }); + expect(result.suite).toBe("true"); + }); + + test("a fetch that runs out of its own deadline falls back to main and says so", () => { + const result = actionsDecision({ + event: "merge_group", + historyBudgetMs: 600, + commits: [{ "server/src/main.ts": "changed" }], + queue: { + delays: { fetch: 900 }, calls: ["api", "fetch"], - reason: "passed on main.", + reason: + "The pull request's own runs are not used: its head could not be fetched", }, responses: (sha, commits) => ({ [`repos/CopilotKit/OpenBot/compare/${commits[0]}...${sha}`]: { diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 36547ce981..6339a61d4b 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -44,7 +44,9 @@ * GITHUB_RUN_ID and GH_TOKEN, as Actions sets them, and WORKFLOW_NAME (`github.workflow`). * CI_HISTORY_BUDGET_MS can shorten the 45000 ms historical-proof deadline (0..45000); each remote * history call is limited to the remaining time or 5000 ms, whichever is less. The optional queued - * PR lookup shares a separate 5000 ms deadline, shortened by the same override (0 skips it). Writes one + * PR lookup's API call has a separate 5000 ms deadline and the fetch of its head 15000 ms, both + * shortened by the same override (0 skips them); a fetch that fails or runs out is named in the + * summary. Writes one * output per job (`true` to run it), the changed tests as JSON arrays, and `queue_run` (the merge * queue's run that stands in for this one, or empty) to $GITHUB_OUTPUT, and what it decided and why * to $GITHUB_STEP_SUMMARY. @@ -755,6 +757,16 @@ function decideSuite( }; if (!run.suite) add(suiteChanges, false); let current: Change[] | undefined; + // A job that runs its full list covers the changed files in that list, whichever rule's changes + // name them: running them again in `tests (changed files)` repeats work (the desktop setup + // window's file alone is 12 minutes). + const runningJobs = Object.entries(BROWSER_JOBS) + .filter(([output]) => run[output]) + .flatMap(([, jobs]) => jobs); + const coveredByRunning = + runningJobs.length > 0 + ? fullBrowserFiles(deps, runningJobs) + : new Set(); for (const output of ["app_browser", "app_browser_webkit"]) { // Without a historical pass, full jobs still cannot cover edited files outside their lists. // Only then fall back to this PR/group's diff; an old PR edit may already have passed later. @@ -767,7 +779,13 @@ function decideSuite( ); changes = current; } - add(changes, true, run[output], output === "app_browser_webkit"); + add( + changes, + true, + run[output], + output === "app_browser_webkit", + coveredByRunning, + ); } // Passing fixed lists prove nothing about files outside them, even when an older passing tree // is restored exactly. Keep those files owed by this PR/group's own diff until they join a list. @@ -814,6 +832,12 @@ function decideSuite( } } +/** The real-browser jobs each browser rule's output runs, by job id in ci.yml. */ +const BROWSER_JOBS: Record = { + app_browser: ["app-browser", "app-browser-desktop"], + app_browser_webkit: ["app-browser-webkit"], +}; + /** Only literal full arrays in the current browser jobs prove file coverage. Unknown is no proof. */ function fullBrowserFiles( deps: Pick, @@ -905,7 +929,10 @@ function fullBrowserFiles( ) ) continue; - for (const path of paths) files.add(path); + // The desktop setup window's job runs from desktop/ (docker's --workdir), so its paths are + // desktop's; the decision names files from the repository root. + const root = id === "app-browser-desktop" ? "desktop/" : ""; + for (const path of paths) files.add(`${root}${path}`); } } return files; @@ -1124,6 +1151,8 @@ export type MergeGroup = { labels: string[]; /** Its head commit when that commit's history was fetched, from this repository only. */ head?: string; + /** Why there is no head, said in the run's summary: a fork, or a fetch that failed or ran out. */ + noHead?: string; }; }; @@ -1257,7 +1286,7 @@ export function decideMergeGroup( decision.reasons.unshift( group.pr?.head ? "A merge group: each job runs unless nothing it reads changed since it passed on main or on the pull request." - : "A merge group: each job runs unless nothing it reads changed since it passed on main.", + : `A merge group: each job runs unless nothing it reads changed since it passed on main. The pull request's own runs are not used${group.pr?.noHead ? `: ${group.pr.noHead}` : ""}.`, ); return { ...decision, ignoredOnly: false }; } @@ -1340,8 +1369,11 @@ export function testedCheckout( return undefined; } -/** One monotonic deadline for optional remote proof commands, with a shorter test override. */ -function historyCommands(maximumMs: number) { +/** + * One monotonic deadline for optional remote proof commands, with a shorter test override. Each + * command gets the remaining time or `perCommandMs`, whichever is less. + */ +function historyCommands(maximumMs: number, perCommandMs = 5_000) { const requested = process.env.CI_HISTORY_BUDGET_MS; const budgetMs = requested !== undefined && /^\d+$/.test(requested) @@ -1352,7 +1384,7 @@ function historyCommands(maximumMs: number) { return { remaining, run: (cmd: string[]) => { - const timeout = Math.min(5_000, remaining()); + const timeout = Math.min(perCommandMs, remaining()); if (timeout <= 0) throw new Error("Historical CI proof budget exhausted"); return exec(cmd, undefined, timeout); }, @@ -1615,10 +1647,14 @@ function queuedPull( const labels = (pull.labels ?? []).map((label) => label.name); const ours = pull.head.repo?.full_name?.toLowerCase() === repository.toLowerCase(); - if (!ours || !/^[0-9a-f]{40}$/.test(pull.head.sha)) return { labels }; - // Its commits and trees share the API call's deadline; failed lookups retain readable labels. + if (!ours || !/^[0-9a-f]{40}$/.test(pull.head.sha)) + return { labels, noHead: "it comes from another repository" }; + // Its commits and trees, on a deadline of their own: a fetch slower than the API call's five + // seconds used to drop the pull request's history without a word, and every job it had passed + // ran again in the queue. Failed lookups keep the labels already read. + const { run: fetchCommand } = historyCommands(15_000, 15_000); try { - run([ + fetchCommand([ "git", "fetch", "--no-tags", @@ -1626,10 +1662,13 @@ function queuedPull( "origin", `+refs/pull/${number}/head:refs/remotes/origin/queued-pr`, ]); - run(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]); + fetchCommand(["git", "cat-file", "-e", `${pull.head.sha}^{commit}`]); return { labels, head: pull.head.sha }; - } catch { - return { labels }; + } catch (error) { + return { + labels, + noHead: `its head could not be fetched: ${error instanceof Error ? error.message : String(error)}`, + }; } } catch { return undefined; diff --git a/scripts/release-publish-order.test.ts b/scripts/release-publish-order.test.ts index 81ac3c3bf0..50d7e9febf 100644 --- a/scripts/release-publish-order.test.ts +++ b/scripts/release-publish-order.test.ts @@ -238,8 +238,9 @@ test("CI keeps a run for every commit on main, and the release's own checks out `${fork} && format('ci-{0}-forks', github.workflow) || ` + "format('ci-{0}-{1}', github.workflow, github.ref == 'refs/heads/main' && github.sha || github.ref)", ), + // A label other than full-ci waits for the run in progress instead of cancelling it. "cancel-in-progress": expression( - "github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository", + "github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')", ), }); }); diff --git a/scripts/workflow-concurrency.test.ts b/scripts/workflow-concurrency.test.ts index 5ae8a243db..ccf1e4e0c7 100644 --- a/scripts/workflow-concurrency.test.ts +++ b/scripts/workflow-concurrency.test.ts @@ -276,7 +276,7 @@ describe("main, a release branch, a tag, a schedule and a manual run are never c }); }); -describe("a label preserves the active run or starts its complete CI replacement", () => { +describe("only full-ci starts a CI replacement; any other label preserves the active run", () => { const labelled = pullRequestWorkflows.filter((file) => triggers(file).pull_request?.types?.includes("labeled"), ); @@ -295,6 +295,16 @@ describe("a label preserves the active run or starts its complete CI replacement concurrency(file, pullRequest(file, 101, "same-push"))?.group, ); expect(concurrency(file, label)?.cancel).toBe(true); + // Any other label (a reviewer's `windows-signing`, a release PR's `release`) waits for the + // run in progress in the same group instead of cancelling it, then finds its checks passed. + const other = pullRequest(file, 101, "same-push", { + action: "labeled", + label: "windows-signing", + }); + expect(concurrency(file, other)?.group).toBe( + concurrency(file, pullRequest(file, 101, "same-push"))?.group, + ); + expect(concurrency(file, other)?.cancel).toBe(false); } else { expect(concurrency(file, label)?.cancel).toBe(false); }