diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json index f220da6538..aeeba8785e 100644 --- a/.github/ci-budgets.json +++ b/.github/ci-budgets.json @@ -7,7 +7,7 @@ "API spec": 3, "native types": 3, "app (real browser)": 8, - "app (real browser, WebKit)": 12, + "app (real browser, WebKit) (shard N of N)": 15, "app (real browser, desktop setup window)": 12, "tests (shard N of N)": 7, "tests": 2, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0367e0a9a9..dac8d475fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -600,9 +600,19 @@ jobs: # app. So on that runner the list runs two files at a time, each test gets 15 seconds by default # 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. + # + # In shards, one runner each, as the suite is: one job took 16 to 17 minutes before the browser tests + # no job had ever named were added, and every file is still named here once. `bun test --shard` + # deals the sorted list out in turn. A run is as long as its slowest shard, and a shard as long as + # its slowest file: artifacts-screens, about 11 minutes. app-browser-webkit: - name: app (real browser, WebKit) + name: app (real browser, WebKit) (shard ${{ matrix.shard }} of ${{ strategy.job-total }}) needs: changes + strategy: + # Every shard runs to the end, so one red run names every failing test, as the suite's do. + fail-fast: false + matrix: + shard: [1, 2, 3] # On a pull request, only when the app, what it imports or its tests change (scripts/ci-changes.ts, # app_browser_webkit). A merge group and main run it every time. if: needs.changes.outputs.app_browser_webkit == 'true' @@ -617,6 +627,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' }} + TEST_SHARD: ${{ matrix.shard }}/${{ strategy.job-total }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -629,22 +640,41 @@ jobs: - run: | # One file per line, sorted: pull requests that each add a file then merge cleanly. files=( + app/tests/access-requests-layout.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx + app/tests/admin-path-layout.test.tsx + app/tests/admin-request-notify-layout.test.tsx + app/tests/another-account-layout.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/approval-answered-layout.test.tsx app/tests/approval-left-carry-on-browser.test.tsx + app/tests/artifact-bridge-browser.test.ts + app/tests/artifact-collab-browser.test.tsx + app/tests/artifact-error-notice-layout.test.tsx + app/tests/artifact-events-socket.test.ts + app/tests/artifact-kinds-browser.test.tsx + app/tests/artifact-sharing-screens-layout.test.tsx app/tests/artifact-sign-in-refusal-browser.test.tsx + app/tests/artifact-tool-cards-browser.test.tsx + app/tests/artifacts-kit.test.ts + app/tests/artifacts-screens.test.tsx + app/tests/board-row-layout.test.tsx + app/tests/bot-file-links-browser.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/browse-apps-pages.test.tsx + app/tests/browse-steps-layout.test.tsx app/tests/chunk-recovery.test.tsx + app/tests/command-card-layout.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/composer-touch-return.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx + app/tests/connected-bot-mistakes-layout.test.tsx + app/tests/conversation-access-ended.test.tsx app/tests/conversation-kept-browser.test.tsx app/tests/conversation-reopen-end.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx @@ -662,7 +692,9 @@ jobs: app/tests/move-to-cloud-settings.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/moved-elsewhere.test.tsx + app/tests/name-the-admins-layout.test.tsx app/tests/new-conversation-picked-model.test.tsx + app/tests/offline-conversation-layout.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-held-recovery.test.tsx @@ -674,16 +706,23 @@ jobs: app/tests/organization-unavailable-chat.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/people-lists.test.tsx + app/tests/plan-notices-layout.test.tsx app/tests/question-answer-prompt-browser.test.tsx + app/tests/queue-send-now-layout.test.tsx app/tests/rejoin-fresh-token-browser.test.tsx app/tests/renderer-crash.test.ts app/tests/renewal-keeps-typing-browser.test.tsx app/tests/roster-working.test.tsx + app/tests/routine-run-now-layout.test.tsx + app/tests/run-ended-unheard-layout.test.tsx app/tests/section-strip-routines.test.tsx + app/tests/select-scrolls-layout.test.tsx app/tests/service-terms.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/settings-tool-cards-personal.test.tsx + app/tests/sidebar-current-row.test.tsx + app/tests/sidebar-window-buttons.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/sign-in-returns-there.test.tsx @@ -692,21 +731,27 @@ jobs: app/tests/step-rows-layout.test.tsx app/tests/stopped-command-layout.test.tsx app/tests/stopped-turn-dismiss-browser.test.tsx + app/tests/strip-version-layout.test.tsx app/tests/table-export-browser.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/too-many-follow-ups.test.tsx + app/tests/trusted-types-build.test.ts + app/tests/trusted-types.test.ts app/tests/web-push-browser.test.tsx app/tests/what-if-handle-browser.test.tsx + app/tests/work-folded-layout.test.tsx + app/tests/workspace-snapshots-layout.test.tsx ) 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 \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" "${files[@]}" + bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" --shard="$TEST_SHARD" "${files[@]}" # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. - # Only that test: the rest of the file runs in Chromium in the job above. - - run: | + # Only that test: the rest of the file runs in Chromium in the job above. Once, on the first shard. + - if: matrix.shard == 1 + 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/app/tests/admin-path-layout.test.tsx b/app/tests/admin-path-layout.test.tsx index ef1125e29e..ed71ccf790 100644 --- a/app/tests/admin-path-layout.test.tsx +++ b/app/tests/admin-path-layout.test.tsx @@ -179,12 +179,13 @@ async function open( reducedMotion: "reduce", }); page.on("pageerror", (error) => console.error(error)); - const inter = join(packageDir("@fontsource-variable/inter"), "files"); + // The app's own face (app/src/styles.css): the page is measured in the type it ships with. + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); await page.route(`${ORIGIN}/**`, (route) => { const at = new URL(route.request().url()).pathname; if (at === "/admin-path.js") return route.fulfill({ contentType: "text/javascript", body: script }); - const font = join(inter, at.split("/").pop() ?? ""); + const font = join(figtree, at.split("/").pop() ?? ""); if (at.startsWith("/files/") && existsSync(font)) return route.fulfill({ path: font }); // The fixture answers the API itself; anything that reaches the network has nowhere to go. diff --git a/app/tests/artifacts-screens.test.tsx b/app/tests/artifacts-screens.test.tsx index d5d7dd7c15..75ca747e3d 100644 --- a/app/tests/artifacts-screens.test.tsx +++ b/app/tests/artifacts-screens.test.tsx @@ -972,14 +972,16 @@ describe.skipIf(!asked)("the Artifacts page and full screen", () => { () => new URL(location.href).searchParams.get("artifact") === null, ); expect(await scroller()).toBe(scrolled); - expect( - await page.evaluate( - () => - document.activeElement - ?.closest("[data-slot=artifact-tile]") - ?.textContent?.includes("Launch countdown") ?? false, - ), - ).toBe(true); + // Focus moves once the list is drawn again, a moment after the address changes: read the + // moment the address changed, it was still on Back. + await page.waitForFunction( + () => + document.activeElement + ?.closest("[data-slot=artifact-tile]") + ?.textContent?.includes("Launch countdown") ?? false, + undefined, + { timeout: 5_000 }, + ); expect(await unanswered(page)).toEqual([]); } finally { await page.close(); diff --git a/app/tests/browse-steps-layout.test.tsx b/app/tests/browse-steps-layout.test.tsx index a7add94d60..b9fa874ec3 100644 --- a/app/tests/browse-steps-layout.test.tsx +++ b/app/tests/browse-steps-layout.test.tsx @@ -144,6 +144,15 @@ async function open( .getByRole("region", { name: "Conversation" }) .waitFor({ timeout: 15_000 }); await page.getByText("You're signed in.").waitFor({ timeout: 15_000 }); + await style(page); + return page; +} + +/** + * The app's stylesheet for every class now on the page, and its fonts loaded. Again once a line is + * opened: a folded line draws its rows only then (`useDrawnOnceOpened`, tool-line.tsx, #2782). + */ +async function style(page: Page) { const classes = await page.evaluate(() => [...document.querySelectorAll("[class]")].flatMap((element) => [ ...element.classList, @@ -153,7 +162,6 @@ async function open( content: await stylesheet([...new Set(classes)]), }); await page.evaluate(() => document.fonts.ready); - return page; } const WINDOWS: Window[] = [ @@ -170,13 +178,16 @@ describe.skipIf(!asked)("a Bot's browse steps, opened", () => { test(`name each field and button, never what was typed, in ${engine}, ${theme}, ${window.width}px`, async () => { const page = await open(engine, theme, window); try { + // The turn is over (the Bot said "You're signed in."), so its work is one line, + // "Worked through 6 steps", as a finished turn's completed tool work is in any + // conversation (`foldTurnWork`, chat-transcript.tsx), and a Bot's browser steps are rows + // of that line, not a line of their own. Opened, it lists them. await page - .locator("summary", { - hasText: "Browsed the-internet.herokuapp.com", - }) + .locator("summary", { hasText: "Worked through 6 steps" }) .click(); const rows = page.locator("details[open] ol > li"); await rows.first().waitFor({ timeout: 5_000 }); + await style(page); if (shots) { mkdirSync(shots, { recursive: true }); await page.screenshot({ diff --git a/app/tests/desktop-page-commands.test.ts b/app/tests/desktop-page-commands.test.ts new file mode 100644 index 0000000000..7539866469 --- /dev/null +++ b/app/tests/desktop-page-commands.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** + * EVERY CALL THE APP'S PAGE MAKES TO OPENBOT DESKTOP IS ONE THE REAL DESKTOP ANSWERS IT. + * + * In OpenBot Desktop the app's page asks the shell through Tauri: `invokeDesktop("status")` is the + * command `plugin:openbot-desktop|status`. Tauri answers it only when the shell registers the + * command (`generate_handler!` in desktop/src-tauri/src/desktop_page.rs) and grants the page its + * permission (`openbot-desktop:allow-status`, in `PERMISSIONS`, which `allow_app_page` in main.rs + * grants the page's own origin and nothing else). A call the app makes that the shell lacks is + * refused on a person's Mac or PC at the moment they use it, and nothing before then says so. + * + * Nothing in CI held the app's calls to the real shell. The Workbench's fake shell + * (desktop/src/fakeNative/pageRegistry.test.ts) checks them against its own list, which it holds + * to `generate_handler!`, but the Workbench's tests are a dev tool's and run in no CI. #2720 added a + * call in app/src and that test went red where nobody ran it. This reads the real shell's source + * instead, and runs in the suite, on every change to the app or the shell and in every merge group. + * + * The page's calls to Tauri's own plugins go through the same gate: each is granted to the page in + * `allow_app_page`, or is one the app makes knowing it may be refused and has a way round + * (`BEST_EFFORT`, each with where its way round is). + */ + +const ROOT = join(import.meta.dir, "..", ".."); +const APP_SRC = join(ROOT, "app", "src"); +const GENERATED = join(APP_SRC, "lib", "api", "generated"); +const PAGE_RS = join(ROOT, "desktop", "src-tauri", "src", "desktop_page.rs"); +const MAIN_RS = join(ROOT, "desktop", "src-tauri", "src", "main.rs"); +const PAGE_PLUGIN = "plugin:openbot-desktop"; + +/** + * Calls to Tauri's own plugins that the shell does not grant the page, on purpose, each with its way + * round when refused. `allow_app_page` grants the page window dragging, Settings' commands and + * notifications, "and nothing more": `core:event` would let the page hear every event the shell + * sends its window. + */ +const BEST_EFFORT: Record = { + // Whether the Desktop window is in front: the DOM's own focus and blur say the same. + "plugin:event|listen": "app/src/lib/desktop/window-attention.ts", + "plugin:event|unlisten": "app/src/lib/desktop/window-attention.ts", +}; + +function sources(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = join(dir, entry.name); + if (entry.isDirectory()) return path === GENERATED ? [] : sources(path); + return /\.tsx?$/.test(entry.name) && !/\.test\./.test(entry.name) + ? [path] + : []; + }); +} + +/** A call's name, with any type arguments between it and its first argument. */ +const GENERIC = String.raw`\s*(?:<[^>]*(?:<[^>]*>[^>]*)*>)?\s*\(\s*"([a-z_]+)"`; + +/** Every `plugin:|` the app's own code asks the shell for, with a file that asks. */ +function appCalls(): Map { + const calls = new Map(); + const add = (call: string, file: string) => { + if (!calls.has(call)) calls.set(call, file.slice(ROOT.length + 1)); + }; + for (const file of sources(APP_SRC)) { + const text = readFileSync(file, "utf8"); + for (const match of text.matchAll( + new RegExp(String.raw`\binvokeDesktop${GENERIC}`, "gs"), + )) + add(`${PAGE_PLUGIN}|${match[1]}`, file); + // The AI connection's own helper names the page's commands the same way. + if (file.endsWith(join("lib", "ai-connection", "desktop.ts"))) + for (const match of text.matchAll( + new RegExp(String.raw`\bdesktop${GENERIC}`, "gs"), + )) + add(`${PAGE_PLUGIN}|${match[1]}`, file); + // `${PLUGIN}|command`, where the file names the plugin in a constant. + const plugin = /const PLUGIN = "(plugin:[a-z-]+)"/.exec(text)?.[1]; + if (plugin) + for (const match of text.matchAll(/\$\{PLUGIN\}\|([a-z_]+)/g)) + add(`${plugin}|${match[1]}`, file); + for (const match of text.matchAll(/"(plugin:[a-z-]+\|[a-z_]+)"/g)) + add(match[1] as string, file); + } + return calls; +} + +const pageRs = readFileSync(PAGE_RS, "utf8"); +const mainRs = readFileSync(MAIN_RS, "utf8"); + +/** The commands the shell registers for the page: `generate_handler![…]` in desktop_page.rs. */ +function registered(): Set { + const start = pageRs.indexOf("generate_handler!["); + expect(start).toBeGreaterThanOrEqual(0); + const body = pageRs.slice( + start + "generate_handler![".length, + pageRs.indexOf("]", start), + ); + return new Set(body.split(/[\s,]+/).filter(Boolean)); +} + +/** The permissions the shell grants the page's own origin: `allow_app_page` and what it chains. */ +function granted(): Set { + const quoted = (text: string) => + [...text.matchAll(/"([a-z-]+:[a-z-]+)"/g)].map( + (match) => match[1] as string, + ); + const list = (source: string, name: string) => { + const start = source.indexOf(`const ${name}:`); + expect(start).toBeGreaterThanOrEqual(0); + return quoted(source.slice(start, source.indexOf("];", start))); + }; + const start = mainRs.indexOf("fn allow_app_page"); + expect(start).toBeGreaterThanOrEqual(0); + const body = mainRs.slice(start, mainRs.indexOf("\n}\n", start)); + // The chained lists, by name: the page's own commands and its notifications. + expect(body).toContain("desktop_page::PERMISSIONS"); + expect(body).toContain("APP_PAGE_NOTIFICATIONS"); + return new Set([ + ...[...body.matchAll(/\.permission\("([^"]+)"\)/g)].map( + (match) => match[1] as string, + ), + ...list(pageRs, "PERMISSIONS"), + ...list(mainRs, "APP_PAGE_NOTIFICATIONS"), + ]); +} + +/** The permission a call needs: Tauri's own plugins are `core::allow-`. */ +function permissionFor(call: string): string { + const [plugin, command] = call.replace(/^plugin:/, "").split("|") as [ + string, + string, + ]; + const core = ["event", "window", "webview", "app", "path", "menu", "tray"]; + return `${core.includes(plugin) ? `core:${plugin}` : plugin}:allow-${command.replaceAll("_", "-")}`; +} + +describe("the app's page asking OpenBot Desktop", () => { + const calls = appCalls(); + + test("finds the page's calls, the way the app makes them", () => { + // Settings' commands, the update banner, speech, sign-in and the AI connection, at the least. + expect( + [...calls.keys()].filter((call) => call.startsWith(`${PAGE_PLUGIN}|`)) + .length, + ).toBeGreaterThanOrEqual(20); + for (const call of [ + `${PAGE_PLUGIN}|status`, + `${PAGE_PLUGIN}|speech_start`, + "plugin:event|listen", + ]) + expect([...calls.keys()]).toContain(call); + }); + + test("every Settings command the page calls is one the shell registers and grants it", () => { + const commands = registered(); + const permissions = granted(); + const missing = [...calls] + .filter(([call]) => call.startsWith(`${PAGE_PLUGIN}|`)) + .flatMap(([call, file]) => { + const command = call.slice(PAGE_PLUGIN.length + 1); + const problems = [ + ...(commands.has(command) ? [] : ["not registered"]), + ...(permissions.has(permissionFor(call)) ? [] : ["not granted"]), + ]; + return problems.length + ? [`${call} (${file}): ${problems.join(", ")}`] + : []; + }); + expect(missing).toEqual([]); + }); + + test("every call to Tauri's own plugins is granted to the page, or made knowing it may be refused", () => { + const permissions = granted(); + const refused = [...calls] + .filter(([call]) => !call.startsWith(`${PAGE_PLUGIN}|`)) + .filter(([call]) => !permissions.has(permissionFor(call))) + .filter(([call, file]) => BEST_EFFORT[call] !== file) + .map(([call, file]) => `${call} (${file})`); + expect(refused).toEqual([]); + }); + + test("a call made knowing it may be refused is still made, and still refused", () => { + // So this list never outlives what it excuses: each is still asked for where it says, and the + // shell still does not grant it. Granted one day, it comes off the list. + const permissions = granted(); + for (const [call, file] of Object.entries(BEST_EFFORT)) { + expect({ call, file: calls.get(call) }).toEqual({ call, file }); + expect({ call, granted: permissions.has(permissionFor(call)) }).toEqual({ + call, + granted: false, + }); + } + }); +}); diff --git a/app/tests/plan-notices-layout.test.tsx b/app/tests/plan-notices-layout.test.tsx index 4be12a7e5c..cb1a399fee 100644 --- a/app/tests/plan-notices-layout.test.tsx +++ b/app/tests/plan-notices-layout.test.tsx @@ -384,8 +384,10 @@ describe.skipIf(!asked)( try { await shot(page, `dialog-${state.name}-${theme}-${width}`); const dialog = page.getByRole("dialog"); + // The dialog at the end says it in one sentence (#2692), as the suite's + // plan-free-trial.test.tsx reads it. await expect(dialog.textContent()).resolves.toContain( - "Your free trial was 500 Bot runs", + "All 500 Bot runs in your free trial are used.", ); const link = dialog.getByRole("link", { name: "Add a card" }); if (state.admin) diff --git a/app/tests/routine-run-now-layout.test.tsx b/app/tests/routine-run-now-layout.test.tsx index bf0d20a055..36431eef67 100644 --- a/app/tests/routine-run-now-layout.test.tsx +++ b/app/tests/routine-run-now-layout.test.tsx @@ -198,8 +198,9 @@ describe.skipIf(!asked)("Run now on a routine's page", () => { expect(await sideways(page)).toBe(false); await page.getByRole("button", { name: RUN_BUTTON }).click(); - // The run the server started shows in Runs, with or without the page saying so. - await page.getByText("Running", { exact: true }).waitFor(); + // The run the server started shows in Runs, with or without the page saying so, as + // "Running now" (#2704). + await page.getByText("Running now", { exact: true }).waitFor(); if (!before) await page .getByRole("status") diff --git a/app/tests/run-ended-unheard-layout.test.tsx b/app/tests/run-ended-unheard-layout.test.tsx index 786871e1e8..3434812463 100644 --- a/app/tests/run-ended-unheard-layout.test.tsx +++ b/app/tests/run-ended-unheard-layout.test.tsx @@ -615,6 +615,41 @@ async function shoot(page: Page, name: string) { await page.screenshot({ path: join(shots, `${name}.png`) }); } +/** + * Opens the closed lines on screen, a level at a time, as a person opens them, until `said` is + * drawn, and no further: the step whose own line says it stays closed, for the test to open. A Bot's + * steps are folded once the turn is over: into "Worked through N steps" (`foldTurnWork`, + * chat-transcript.tsx), or, with a command among them, into the line that names its commands, "Ran 2 + * commands" (#2432). Which one depends on the turn. A folded line draws what it holds only once it + * is opened (`useDrawnOnceOpened`, tool-line.tsx, #2782), so the steps are not on the page until then. + */ +async function openTo(page: Page, said: string) { + const found = page.getByText(said).first(); + for (let level = 0; level < 6; level += 1) { + if (await found.count()) return; + // The closed lines a person can see now, marked for this level's clicks. + const count = await page.evaluate((level) => { + const closed = [ + ...document.querySelectorAll("details:not([open]) > summary"), + ].filter((summary) => summary.getBoundingClientRect().height > 0); + closed.forEach((summary) => { + (summary as HTMLElement).dataset.openAt = String(level); + }); + return closed.length; + }, level); + for (let index = 0; index < count; index += 1) + await page.locator(`summary[data-open-at="${level}"]`).nth(index).click(); + // Nothing to open yet: the finished turn is still being drawn, so wait for its line or `said`. + if (count === 0) + await page + .locator("details:not([open]) > summary") + .or(found) + .first() + .waitFor({ state: "attached", timeout: 15_000 }); + } + await found.waitFor({ state: "attached", timeout: 15_000 }); +} + describe.skipIf(!asked)("a run whose end never reached this browser", () => { for (const engine of engines) for (const theme of ["light", "dark"] as const) @@ -662,6 +697,7 @@ describe.skipIf(!asked)("a run whose end never reached this browser", () => { // The command ran here once, and its step says what ran and what it printed. expect(scene.steps).toBe(1); expect(scene.runs).toBe(3); + await openTo(page, "Ran a command"); const step = page .locator("details") .filter({ @@ -683,10 +719,15 @@ describe.skipIf(!asked)("a run whose end never reached this browser", () => { expect( await page.getByRole("button", { name: "Carry on" }).count(), ).toBe(0); - // The command the phone never ran reads as not run, never as blocked. - expect(await page.getByText("Didn't run a command").count()).toBe( - 1, - ); + // The command the phone never ran reads as not run, never as blocked: as one row of a run + // of steps it is named by what was tried, "Run a command", never "Ran", with "Didn't + // work" beside it (`commandStepWords`, terminal-block.tsx). + expect( + await page + .locator("summary", { hasText: /^Run a command(?!, not done)/ }) + .filter({ hasText: "Didn't work" }) + .count(), + ).toBe(1); expect(await page.getByText(/Blocked/).count()).toBe(0); expect( await page.evaluate( @@ -707,6 +748,7 @@ describe.skipIf(!asked)("a run whose end never reached this browser", () => { .getByRole("button", { name: "Stop the Bot" }) .waitFor({ state: "detached", timeout: 15_000 }); // The file it saved, drawn from the server's result as a step this page took is. + await openTo(page, "Saved a file"); await page.getByText("Saved a file").first().waitFor(); // The build the server ran, with what it printed, in the same terminal block. const step = page diff --git a/app/tests/sidebar-current-row.test.tsx b/app/tests/sidebar-current-row.test.tsx index 38ce8081c1..e0e94cdda7 100644 --- a/app/tests/sidebar-current-row.test.tsx +++ b/app/tests/sidebar-current-row.test.tsx @@ -1,27 +1,33 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, 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 { still } from "./page-still"; /** - * On the invitations page no row of the sidebar looks like the page that is open. + * The sidebar's strip says which section is open, and on a page no section owns it says no page is. * - * Seen on Windows, in OpenBot Desktop and on the web: open the account menu on Bots, choose - * Invitations, and on /invitations the sidebar's Bots row was still drawn as if it were the open - * page. Nothing in the route tree marks it (this test checks that too, on the real tree); the menu - * opens upwards over the rows above the account row, Invitations sits right over Bots, and when the - * menu goes the pointer is left resting on Bots, whose hover fill is the same fill the open page - * gets. So a row under a pointer that has not moved since a menu closed over it is not filled. + * Seen on Windows, in OpenBot Desktop and on the web, when the sidebar was a list of rows: open the + * account menu on Bots, choose Invitations, and on /invitations the Bots row was still drawn as if it + * were the open page. The menu had opened over the rows, the pointer was left resting on Bots when + * it went, and a hover fill is the open page's fill. + * + * The sidebar is a strip of sections now (section-strip.tsx). The section that is open is pressed + * (a panel's, `aria-pressed`) and its square is filled (`data-active`); the section whose page is + * open says so (`aria-current="page"`); and a section kept open on a page none of them owns is + * "shown open, not said current". So: on Bots, Bots is the open section and no page is said current. + * Chosen from the account menu, /invitations is no section's page: no section says it is, and no + * square is filled but the open one's, whatever the pointer was left resting on. With the pointer + * moved onto a section afterwards, its square fills as hover always did. * * The whole app, as main.tsx mounts it on app/src/routeTree.gen.ts, against a stand-in server * (sidebar-current-row.fixture.tsx), in a real Chromium and WebKit, where hover is the browser's - * own. With the pointer moved afterwards, the row it is on fills as hover always did. + * own: light and dark, on a desktop and in a phone's sheet. * * OPENBOT_APP_BROWSER=1 bun test app/tests/sidebar-current-row.test.tsx * - * With OPENBOT_APP_SHOTS= it also saves the sidebar on /invitations in each browser. + * With OPENBOT_APP_SHOTS= it also saves the strip on /invitations in each case. */ const asked = process.env.OPENBOT_APP_BROWSER === "1"; const shots = process.env.OPENBOT_APP_SHOTS; @@ -130,15 +136,35 @@ async function style(page: Page) { await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); } -async function open(engine: BrowserType, path: string): Promise { - const browser = - engine.name() === "chromium" - ? // The CI job installs full Chromium without the headless shell. - await engine.launch({ channel: "chromium" }) - : await engine.launch(); - browsers.push(browser); - const page = await browser.newPage({ - viewport: { width: 1440, height: 900 }, +/** One browser per engine, kept for every case it draws. */ +const launched = new Map>(); + +type Theme = "light" | "dark"; +type Width = 1440 | 390; + +async function open( + engine: "chromium" | "webkit", + path: string, + theme: Theme, + width: Width, +): Promise { + const playwright = await import("playwright-core"); + let browser = launched.get(engine); + if (!browser) { + browser = ( + engine === "chromium" + ? // The CI job installs full Chromium without the headless shell. + playwright.chromium.launch({ channel: "chromium" }) + : playwright.webkit.launch() + ).then((launchedBrowser) => { + browsers.push(launchedBrowser); + return launchedBrowser; + }); + launched.set(engine, browser); + } + const page = await (await browser).newPage({ + viewport: { width, height: width < 768 ? 844 : 900 }, + colorScheme: theme, }); page.on("pageerror", (error) => console.error(error)); await page.route(`${ORIGIN}/**`, (route) => { @@ -149,107 +175,146 @@ async function open(engine: BrowserType, path: string): Promise { return route.fulfill({ status: 404, body: "" }); return route.fulfill({ contentType: "text/html", - body: `
`, + body: `
`, }); }); await page.goto(`${ORIGIN}${path}`, { waitUntil: "domcontentloaded" }); return page; } -/** What the sidebar's rows say about themselves, and the fill each is drawn with. */ -async function rows(page: Page) { - return page.evaluate(() => { - const footer = document.querySelector("[data-sidebar=footer]"); - const links = [ - ...(footer?.querySelectorAll("a[href]") ?? []), - ]; - return { - marked: links - .filter( - (link) => - link.dataset.status === "active" || - link.getAttribute("aria-current") === "page", - ) - .map((link) => link.textContent?.trim()), - filled: links - .filter((link) => { - const fill = getComputedStyle(link).backgroundColor; - return fill !== "rgba(0, 0, 0, 0)" && fill !== "transparent"; - }) - .map((link) => link.textContent?.trim()), - }; - }); +/** + * What each of the strip's sections says about itself, and whether its square is filled: the open + * section's fill, or a hover's. + */ +async function strip(page: Page) { + return page.evaluate(() => + [...document.querySelectorAll("[data-slot=strip-item]")] + .filter((item) => item.getBoundingClientRect().width > 0) + .map((item) => { + const square = item.querySelector("[data-slot=strip-icon]"); + const fill = square ? getComputedStyle(square).backgroundColor : ""; + return { + label: ( + item.querySelector("[data-slot=strip-label]")?.textContent ?? "" + ).trim(), + current: item.getAttribute("aria-current") === "page", + pressed: item.getAttribute("aria-pressed") === "true", + open: item.hasAttribute("data-active"), + // Transparent, in whichever colour syntax the engine writes it. + filled: !/^(transparent|rgba\(0, 0, 0, 0\)|oklab\([^)]*\/ 0\))$/.test( + fill.trim(), + ), + }; + }), + ); } -describe.skipIf(!asked)("the sidebar on the invitations page", () => { - for (const name of ["chromium", "webkit"] as const) { - test(`in ${name}, after choosing Invitations from the account menu on Bots, no row looks open`, async () => { - const playwright = await import("playwright-core"); - const page = await open(playwright[name], "/bots"); - const account = page.getByRole("button", { name: /Dana Fresh/ }); - await account.waitFor(); - await style(page); - await page.waitForFunction(() => - [...document.querySelectorAll("[data-sidebar=footer] a")].some( - (link) => (link as HTMLElement).dataset.status === "active", - ), - ); - expect((await rows(page)).marked).toEqual(["Bots"]); - - await account.click(); - const entry = page.getByRole("menuitem", { name: /Invitations/ }); - await entry.waitFor(); - await style(page); - const box = await entry.boundingBox(); - const bots = await page - .locator("[data-sidebar=footer] a", { hasText: "Bots" }) - .boundingBox(); - // The premise: the menu opens over the rows above it, and Invitations sits over Bots. - expect(box && bots).toBeTruthy(); - await entry.click(); - await page.waitForURL(`${ORIGIN}/invitations`); - await page.getByRole("menu").waitFor({ state: "detached" }); - // A few frames for the browser to work out what is under the pointer now. - await page.evaluate( - () => - new Promise((done) => - requestAnimationFrame(() => requestAnimationFrame(done)), - ), - ); - await page.waitForTimeout(300); - const pointerOn = await page.evaluate( - ([x, y]) => document.elementFromPoint(x, y)?.closest("a")?.textContent, - [ - (box?.x ?? 0) + (box?.width ?? 0) / 2, - (box?.y ?? 0) + (box?.height ?? 0) / 2, - ], - ); - if (shots) { - mkdirSync(shots, { recursive: true }); - await page.screenshot({ - path: join(shots, `sidebar-on-invitations-${name}.png`), - clip: { x: 0, y: 0, width: 360, height: 900 }, - }); - } - const unanswered = await page.evaluate( - () => (window as unknown as { unanswered: string[] }).unanswered, - ); - expect({ ...(await rows(page)), pointerOn, unanswered }).toMatchObject({ - marked: [], - filled: [], - }); - - // The pointer moves: the row it is on fills, as hover always did. - const botsNow = await page - .locator("[data-sidebar=footer] a", { hasText: "Bots" }) - .boundingBox(); - await page.mouse.move( - (botsNow?.x ?? 0) + 40, - (botsNow?.y ?? 0) + (botsNow?.height ?? 0) / 2, - { steps: 4 }, - ); - await still(page); - expect((await rows(page)).filled).toEqual(["Bots"]); - }, 120_000); +const named = ( + items: Awaited>, + key: "current" | "pressed" | "open" | "filled", +) => items.filter((item) => item[key]).map((item) => item.label); + +/** On a phone the strip is in the sidebar's sheet, opened from the page's own button. */ +async function showStrip(page: Page, width: Width) { + const account = page.getByRole("button", { name: /Dana Fresh/ }); + if (width < 768) { + await page.getByRole("button", { name: "Show sidebar" }).first().click(); } + await account.waitFor(); + await style(page); + await still(page); + return account; +} + +describe.skipIf(!asked)("the strip on a page no section owns", () => { + for (const engine of ["chromium", "webkit"] as const) + for (const theme of ["light", "dark"] as const) + for (const width of [1440, 390] as const) + test(`after choosing Invitations from the account menu on Bots, no section says it is the open page, in ${engine}, ${theme}, ${width}px`, async () => { + const page = await open(engine, "/bots", theme, width); + try { + const account = await showStrip(page, width); + // On Bots: Bots is the open section, and no page is said current (Bots is a panel's). + const onBots = await strip(page); + expect(named(onBots, "pressed")).toEqual(["Bots"]); + expect(named(onBots, "open")).toEqual(["Bots"]); + expect(named(onBots, "current")).toEqual([]); + + // Invitations is in the organization's switcher, the account menu's organization row + // (#2644): it lists the invitations waiting, and this person has one. + // Styled once the menu is open, before its row is pressed: styled after, the page moves + // under a pointer that has not, and the switcher closes. + await account.click(); + const switcher = page.locator( + '[data-slot="organization-switcher"]', + ); + await switcher.waitFor(); + await style(page); + await still(page); + await switcher.click(); + const entry = page.getByRole("menuitem", { name: /Invitations/ }); + await entry.waitFor(); + const box = await entry.boundingBox(); + await entry.click(); + await page.waitForURL(`${ORIGIN}/invitations`); + // The account menu and its switcher both gone. + await page.waitForFunction( + () => document.querySelector('[role="menu"]') === null, + ); + // A few frames for the browser to work out what is under the pointer now. + await page.evaluate( + () => + new Promise((done) => + requestAnimationFrame(() => requestAnimationFrame(done)), + ), + ); + await page.waitForTimeout(300); + if (width < 768) await showStrip(page, width); + await style(page); + await still(page); + if (shots) { + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join( + shots, + `strip-on-invitations-${engine}-${theme}-${width}.png`, + ), + }); + } + const onInvitations = await strip(page); + const unanswered = await page.evaluate( + () => (window as unknown as { unanswered: string[] }).unanswered, + ); + // No section's page: none says it is, and the only filled square is the open section's, + // whatever the pointer was left resting on when the menu went. + expect({ + current: named(onInvitations, "current"), + filledButNotOpen: onInvitations + .filter((item) => item.filled && !item.open) + .map((item) => item.label), + unanswered, + }).toMatchObject({ current: [], filledButNotOpen: [] }); + expect(box).toBeTruthy(); + + // The pointer moves onto a section: its square fills, as hover always did. + if (width >= 768) { + const routines = page.locator("[data-slot=strip-item]", { + hasText: "Routines", + }); + const at = await routines.boundingBox(); + await page.mouse.move( + (at?.x ?? 0) + (at?.width ?? 0) / 2, + (at?.y ?? 0) + (at?.height ?? 0) / 2, + { steps: 4 }, + ); + await still(page); + const hovered = await strip(page); + expect( + hovered.find((item) => item.label === "Routines")?.filled, + ).toBe(true); + } + } finally { + await page.close(); + } + }, 120_000); }); diff --git a/app/tests/sidebar-window-buttons.test.tsx b/app/tests/sidebar-window-buttons.test.tsx index 17199873e4..bef8dd2c79 100644 --- a/app/tests/sidebar-window-buttons.test.tsx +++ b/app/tests/sidebar-window-buttons.test.tsx @@ -832,7 +832,8 @@ async function corner(page: Page) { return { x: Math.round(box.left), y: Math.round(box.top) }; }; return { - orb: at('[data-slot="strip"] .bot-orb-still'), + // OpenBot's own orb, the strip's home link (`HomeOrb`, section-strip.tsx): an `AgentOrb`. + orb: at('[data-slot="strip"] .agent-orb'), firstSection: at('[data-slot="strip"] nav > *'), heading: at('[data-slot="section-panel"]:not([hidden]) h2'), back: at('[data-slot="sidebar-header"] a'), @@ -982,12 +983,14 @@ describe.skipIf(!asked)("the sidebar and the window's buttons", () => { test("without the mark, on Windows or in a browser, every corner is where it has always been", async () => { // Measured on main without the mark, so a sidebar that moves outside the desktop fails. Measured - // again after the strip was redrawn wider (#2124), which moved its pieces on purpose. + // again after the strip was redrawn wider (#2124), which moved its pieces on purpose, and again + // when this test first ran in CI: the strip's orb is an `AgentOrb` now, whose sphere sits a pixel + // inside its box, and the panel's heading had come to sit a pixel higher on main by then. const before: Record>> = { "app-conversations": { - orb: { x: 22, y: 22 }, + orb: { x: 23, y: 23 }, firstSection: { x: 8, y: 64 }, - heading: { x: 80, y: 21 }, + heading: { x: 80, y: 20 }, back: null, }, admin: { diff --git a/app/tests/sign-in-returns-there.test.tsx b/app/tests/sign-in-returns-there.test.tsx index 74ed701709..14baaccddf 100644 --- a/app/tests/sign-in-returns-there.test.tsx +++ b/app/tests/sign-in-returns-there.test.tsx @@ -172,7 +172,9 @@ class FakeServers { }); if (path.startsWith("/files/")) { const font = join( - packageDir("@fontsource-variable/inter"), + // The app's own face (app/src/styles.css); Inter is no longer installed, so this served + // no font at all and the page was measured in the browser's fallback. + packageDir("@fontsource-variable/figtree"), "files", path.split("/").pop() ?? "", ); diff --git a/app/tests/work-folded-layout.test.tsx b/app/tests/work-folded-layout.test.tsx index e7fbf8cfa4..ffefe0d5a0 100644 --- a/app/tests/work-folded-layout.test.tsx +++ b/app/tests/work-folded-layout.test.tsx @@ -148,15 +148,27 @@ async function open( await page .getByRole("region", { name: "Conversation" }) .waitFor({ timeout: 15_000 }); - // The commands' cards are drawn, folded or not. + // The work's one line, and beside it the side rail's commands. What the line holds is drawn only + // once it is opened (`useDrawnOnceOpened`, tool-line.tsx, #2782). await page - .locator('section[aria-label="Ran a command"]') + .locator("summary", { + hasText: state === "done" ? WORK_LINE : "Running a command…", + }) + .waitFor({ timeout: 15_000 }); + await page + .locator('aside[aria-label="Computer activity"] section[aria-label="Ran"]') .first() .waitFor({ state: "attached", timeout: 15_000 }); if (state === "done") await page .getByRole("region", { name: "Waiting for your approval" }) .waitFor({ timeout: 15_000 }); + await style(page); + return page; +} + +/** The app's stylesheet for every class now on the page, again once a line is opened, and its fonts. */ +async function style(page: Page) { const classes = await page.evaluate(() => [...document.querySelectorAll("[class]")].flatMap((element) => [ ...element.classList, @@ -166,7 +178,6 @@ async function open( content: await stylesheet([...new Set(classes)]), }); await page.evaluate(() => document.fonts.ready); - return page; } async function shoot(page: Page, name: string) { @@ -221,17 +232,20 @@ describe.skipIf(!asked)("a Bot's work in a conversation", () => { }); expect(await work.count()).toBe(1); expect(await work.isVisible()).toBe(true); + // Folded, the line draws none of what it holds (`useDrawnOnceOpened`, #2782): no command's + // card is out of a fold. expect( - await foldOf( - page, - 'section[aria-label="Conversation"] section[aria-label="Ran a command"]', - ), - ).toEqual(["folded", "folded", "folded"]); + ( + await foldOf( + page, + 'section[aria-label="Conversation"] section[aria-label="Ran a command"]', + ) + ).filter((fold) => fold !== "folded"), + ).toEqual([]); // No step has a line of its own: each is a row of that line, and folded with it. const rows = conversation.getByText("Ran a command", { exact: true, }); - expect(await rows.count()).toBeGreaterThanOrEqual(3); for (const row of await rows.all()) expect(await row.isVisible()).toBe(false); // Nor is anything a command printed. @@ -240,7 +254,6 @@ describe.skipIf(!asked)("a Bot's work in a conversation", () => { "6 top-articles.csv", ]) { const output = conversation.getByText(printed); - expect(await output.count()).toBeGreaterThan(0); for (const shown of await output.all()) expect(await shown.isVisible()).toBe(false); } @@ -295,6 +308,8 @@ describe.skipIf(!asked)("a Bot's work in a conversation", () => { const commands = conversation.locator("summary", { hasText: "Ran a command", }); + await commands.first().waitFor({ timeout: 5_000 }); + await style(page); expect(await commands.count()).toBe(3); for (const row of await commands.all()) expect(await row.isVisible()).toBe(true); @@ -310,6 +325,8 @@ describe.skipIf(!asked)("a Bot's work in a conversation", () => { const blocks = conversation.getByRole("region", { name: "Ran a command", }); + await blocks.first().waitFor({ timeout: 5_000 }); + await style(page); const block = blocks.first(); expect(await block.isVisible()).toBe(true); expect(await block.textContent()).toContain("Exit 0"); @@ -393,11 +410,13 @@ describe.skipIf(!asked)("a Bot's work in a conversation", () => { ).toBe(true); // What the commands printed stays behind the fold in the conversation. expect( - await foldOf( - page, - 'section[aria-label="Conversation"] section[aria-label="Ran a command"]', - ), - ).toEqual(["folded", "folded"]); + ( + await foldOf( + page, + 'section[aria-label="Conversation"] section[aria-label="Ran a command"]', + ) + ).filter((fold) => fold !== "folded"), + ).toEqual([]); expect( await conversation .getByText("debug: fetched page 20") diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index f8c893b1eb..eab225d564 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -1416,40 +1416,8 @@ describe("the rules name the jobs the workflows run", () => { // this list as each is made to pass and named. A name left here once its file is named, or // gone, fails too, so the list only shrinks. const NOT_YET_IN_CI = [ - "app/tests/access-requests-layout.test.tsx", - "app/tests/admin-path-layout.test.tsx", - "app/tests/admin-request-notify-layout.test.tsx", - "app/tests/another-account-layout.test.tsx", - "app/tests/artifact-bridge-browser.test.ts", - "app/tests/artifact-collab-browser.test.tsx", - "app/tests/artifact-error-notice-layout.test.tsx", - "app/tests/artifact-events-socket.test.ts", - "app/tests/artifact-kinds-browser.test.tsx", + // Loads the built print page the export worker serves: it waits for a build step in its job. "app/tests/artifact-print-browser.test.ts", - "app/tests/artifact-sharing-screens-layout.test.tsx", - "app/tests/artifact-tool-cards-browser.test.tsx", - "app/tests/artifacts-kit.test.ts", - "app/tests/artifacts-screens.test.tsx", - "app/tests/board-row-layout.test.tsx", - "app/tests/bot-file-links-browser.test.tsx", - "app/tests/browse-steps-layout.test.tsx", - "app/tests/command-card-layout.test.tsx", - "app/tests/connected-bot-mistakes-layout.test.tsx", - "app/tests/conversation-access-ended.test.tsx", - "app/tests/name-the-admins-layout.test.tsx", - "app/tests/offline-conversation-layout.test.tsx", - "app/tests/plan-notices-layout.test.tsx", - "app/tests/queue-send-now-layout.test.tsx", - "app/tests/routine-run-now-layout.test.tsx", - "app/tests/run-ended-unheard-layout.test.tsx", - "app/tests/select-scrolls-layout.test.tsx", - "app/tests/sidebar-current-row.test.tsx", - "app/tests/sidebar-window-buttons.test.tsx", - "app/tests/strip-version-layout.test.tsx", - "app/tests/trusted-types-build.test.ts", - "app/tests/trusted-types.test.ts", - "app/tests/work-folded-layout.test.tsx", - "app/tests/workspace-snapshots-layout.test.tsx", ]; const ci = readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"); const browserTests = ["app/tests", "extension/tests"].flatMap((dir) => diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index a311ff90d1..b1d6fa669f 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -62,6 +62,9 @@ export const MAX_ANCESTORS = 50; /** The number of shards ci.yml's `test` job runs the suite in. */ export const SHARDS = 5; +/** The number of shards ci.yml's `app-browser-webkit` job runs its list in. */ +export const WEBKIT_SHARDS = 3; + const matcher = (...patterns: string[]) => { const globs = patterns.map((pattern) => new Bun.Glob(pattern)); return (path: string) => globs.some((glob) => glob.match(path)); @@ -258,7 +261,12 @@ 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)"], + // Every shard, as the suite's: the list passed only once all of them did. + checks: Array.from( + { length: WEBKIT_SHARDS }, + (_, index) => + `app (real browser, WebKit) (shard ${index + 1} of ${WEBKIT_SHARDS})`, + ), reads: (path) => (isCode(path) && appInputs(path)) || ciInputs(path), }, {