diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6bd5bd0497..5a8b3adedf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -758,6 +758,7 @@ jobs: 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/older-safari-build.test.ts app/tests/one-press-connect-layout.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-held-recovery.test.tsx diff --git a/app/package.json b/app/package.json index ffbb91308b..962891b1f3 100644 --- a/app/package.json +++ b/app/package.json @@ -60,6 +60,7 @@ "zod": "^4.4.3" }, "devDependencies": { + "@eslint-community/regexpp": "4.12.3", "@happy-dom/global-registrator": "^20.11.2", "@tailwindcss/vite": "^4.3.3", "@tanstack/router-plugin": "^1.168.30", @@ -69,6 +70,7 @@ "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitejs/plugin-react": "^5.0.4", + "acorn": "8.19.0", "happy-dom": "^20.11.2", "msw": "2.15.0", "tailwindcss": "^4.3.3", diff --git a/app/src/components/audit/audit-cells.tsx b/app/src/components/audit/audit-cells.tsx index cd17366980..0398d73e82 100644 --- a/app/src/components/audit/audit-cells.tsx +++ b/app/src/components/audit/audit-cells.tsx @@ -115,13 +115,21 @@ export function WhenCell({ event }: { event: AuditEvent }) { ); } +/** + * `text` cut after each `.`, `/`, `_` and `-`, each part keeping the seam it ends on. Matched rather + * than split with a lookbehind, which Safari reads only from 16.4 (app/tests/older-safari-build.test.ts). + */ +export function seamsOf(text: string): string[] { + return text.match(/[^./_-]*[./_-]|[^./_-]+/g) ?? [""]; +} + /** * An identifier with a break allowed after each `.`, `/`, `_` and `-`, so `mcp.tools_discovered` or * a file path wraps at its own seams when the column is narrow, and is never cut mid-word. */ function breakable(text: string): ReactNode { let at = 0; - return text.split(/(?<=[./_-])/).map((part) => { + return seamsOf(text).map((part) => { const start = at; at += part.length; return ( diff --git a/app/src/lib/boundaries/rules.ts b/app/src/lib/boundaries/rules.ts index 0475cf9d48..b61cca4e58 100644 --- a/app/src/lib/boundaries/rules.ts +++ b/app/src/lib/boundaries/rules.ts @@ -207,6 +207,25 @@ function asTitle(name: string): string { return /[^.]\.$/.test(trimmed) ? trimmed.slice(0, -1) : trimmed; } +/** A sentence's end: ".", "!" or "?", the spaces after it, and a capital to come. */ +const SENTENCE_END = /[.!?]\s+(?=[A-Z])/g; + +/** + * `text` cut into sentences at each {@link SENTENCE_END}, each keeping its stop and losing the spaces + * after it. Found by matching the stop rather than looking behind for it, which Safari reads only + * from 16.4 (app/tests/older-safari-build.test.ts). + */ +export function sentencesOf(text: string): string[] { + const sentences: string[] = []; + let from = 0; + for (const end of text.matchAll(SENTENCE_END)) { + sentences.push(text.slice(from, end.index + 1)); + from = end.index + end[0].length; + } + sentences.push(text.slice(from)); + return sentences; +} + function wordsOf(rule: BoundaryRule): RuleLabel & { code: string | null } { if (rule.name) return { @@ -227,9 +246,7 @@ function wordsOf(rule: BoundaryRule): RuleLabel & { code: string | null } { // OpenBot's own reading of a rule nobody described: its first sentence, which says what it // stops, is the row's name, and the rest is said under it. if (rule.english && rule.englishFrom === "reading") { - const [first, ...rest] = rule.english - .trim() - .split(/(?<=[.!?])\s+(?=[A-Z])/); + const [first, ...rest] = sentencesOf(rule.english.trim()); return { name: first ?? rule.english, description: rest.join(" ") || rule.description || "", diff --git a/app/src/lib/markdown-email-links.ts b/app/src/lib/markdown-email-links.ts new file mode 100644 index 0000000000..29abe2d8ce --- /dev/null +++ b/app/src/lib/markdown-email-links.ts @@ -0,0 +1,66 @@ +/* + * THE EMAIL ADDRESSES IN A BOT'S WORDS, FOUND WITHOUT A LOOKBEHIND. + * + * GitHub-flavoured Markdown links an address it finds in text (`dana@northwind.test`). Its + * mdast-util-gfm-autolink-literal finds one with + * + * /(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu + * + * on every reply, and Safari reads a lookbehind only from 16.4: in Safari 16.0 to 16.3, and in + * OpenBot Desktop on macOS before 13.3, every reply in Markdown and every document failed to draw. + * Its newer releases use more lookbehinds, not fewer. So the build gives it this instead + * (`lookbehindFreeEmailLinks` in app/vite.config.ts): a regular expression whose `exec` finds the same + * match from the same `lastIndex`, which is all mdast-util-find-and-replace asks of it. Leaving the + * lookbehind out alone would find the same addresses, but try every character of a long word + * (a key, a hash) to the word's end: seconds on a long one. This tries only where the lookbehind + * would, the start or after a space, punctuation or a symbol, as quickly. + * + * app/tests/older-safari-same-words.test.ts holds it to the original's matches. + */ + +/** An address from where it starts, as the original matches it after its lookbehind. */ +const ADDRESS = /([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/uy; +/** What an address may start after: the original's lookbehind, one character. */ +const BOUNDARY = /^(?:\s|\p{P}|\p{S})$/u; +/** What an address starts with. */ +const FIRST = /[-.\w+]/; + +/** Whether the original's lookbehind holds at `at`: the start, or after a space, punctuation or a symbol. */ +function boundaryBefore(text: string, at: number): boolean { + if (at === 0) return true; + // The character before, a whole code point, as a lookbehind in `u` mode reads it. + const low = text.charCodeAt(at - 1); + const pair = + at >= 2 && + low >= 0xdc00 && + low <= 0xdfff && + text.charCodeAt(at - 2) >= 0xd800 && + text.charCodeAt(at - 2) <= 0xdbff; + return BOUNDARY.test(text.slice(pair ? at - 2 : at - 1, at)); +} + +export class EmailAfterBoundary extends RegExp { + constructor() { + super(ADDRESS.source, "gu"); + } + + override exec(input: string): RegExpExecArray | null { + const text = String(input); + for (let at = this.lastIndex; at < text.length; at++) { + if (!FIRST.test(text.charAt(at)) || !boundaryBefore(text, at)) continue; + ADDRESS.lastIndex = at; + const match = ADDRESS.exec(text); + if (match) { + this.lastIndex = at + match[0].length; + return match; + } + } + this.lastIndex = 0; + return null; + } +} + +/** The finder mdast-util-gfm-autolink-literal is built with in place of its lookbehind. */ +export function emailAfterBoundary(): RegExp { + return new EmailAfterBoundary(); +} diff --git a/app/src/lib/maths.ts b/app/src/lib/maths.ts index d9799186b6..20662b551d 100644 --- a/app/src/lib/maths.ts +++ b/app/src/lib/maths.ts @@ -62,8 +62,12 @@ function lineAfter(text: string, index: number): string { * A dollar sign inside a formula, as KaTeX reads one. Models write "\\(P=$25,000\\)" for a price * in a formula; a bare `$` there would end the `$$` early or reach KaTeX as an error. */ -function escapeDollars(formula: string): string { - return formula.replace(/(? + formula[at - 1] === "\\" ? dollar : "\\$", + ); } /** @@ -150,10 +154,18 @@ function rewriteProse(text: string): string { return out; } +/** + * `markdown`'s lines, each with its line ending. Matched rather than split after each "\n" with a + * lookbehind, which Safari reads only from 16.4 (app/tests/older-safari-build.test.ts). + */ +export function linesOf(markdown: string): string[] { + return markdown.match(/[^\n]*\n|[^\n]+/g) ?? [""]; +} + /** `markdown` with `\( \)` and `\[ \]` maths written in the `$$` the maths plugin reads. */ export function withMathDelimiters(markdown: string): string { if (!markdown.includes("\\(") && !markdown.includes("\\[")) return markdown; - const lines = markdown.split(/(?<=\n)/); + const lines = linesOf(markdown); let out = ""; let prose = ""; let fence: string | null = null; diff --git a/app/src/lib/plugins/tool-words.ts b/app/src/lib/plugins/tool-words.ts index db2df65f20..cb85068e3a 100644 --- a/app/src/lib/plugins/tool-words.ts +++ b/app/src/lib/plugins/tool-words.ts @@ -38,16 +38,33 @@ export function toolName(serverId: string, name: string): string { * id is not shown at all: a row with the tool's words and no sentence says less, but nothing wrong. */ export function toolSummary(description: string): string | null { - const first = description - .trim() - .split(/(?<=[.!?])\s+(?=[A-Z])|;\s/)[0] - ?.trim(); + const first = firstClause(description.trim()).trim(); if (!first || NAMES_AN_ID.test(first)) return null; const plain = inPlainWords(first); if (!plain) return null; return /[.!?]$/.test(plain) ? plain : `${plain}.`; } +/* + * NO LOOKBEHIND IN THIS FILE, NOR ANYWHERE THE APP SHIPS. Safari reads `(?<=` and `(? { const bare = word.slice(0, word.length - label.length); if (!shouted(bare)) return word; @@ -156,10 +172,44 @@ function saysIt(verb: string): string { /** * How a tool finds a thing by its ID: "by ID", "by its ID", "by thread ID", "using its ID", "by * message and attachment IDs", and "identified by its ID" or "specified by its ID", with the commas - * around it. Never where it orders or filters rather than finds ("sorted by ID"). + * around it. Never where it orders or filters rather than finds ("sorted by ID": {@link ORDERS_BY}). + * The spaces before "by" are a group of their own, so where "by" starts is known. */ const BY_ITS_ID = - /(,?\s+(?:identified|specified))?\s+(? cell.trim()) .filter(Boolean); if (cells.length === 0 || cells.every((cell) => TABLE_RULE.test(cell))) @@ -56,6 +71,13 @@ function tableRow(line: string): string | null { return rest.length ? `${first}: ${rest.join(", ")}` : (first ?? ""); } +/** + * Underscores that close emphasis: after a character that is not a space, before the end or a + * character that is not a letter or a number. The character before is matched and put back, rather + * than looked behind at, which Safari reads only from 16.4 (app/tests/older-safari-build.test.ts). + */ +export const CLOSING_UNDERSCORES = /(\S)_+(?=$|[^\p{L}\p{N}])/gu; + /** Markdown's marks taken off one line, leaving the words. */ function withoutMarks(line: string): string { return ( @@ -78,7 +100,7 @@ function withoutMarks(line: string): string { .replace(/`+/g, "") .replace(/\*+|~~/g, "") .replace(/(^|[^\p{L}\p{N}])_+(?=\S)/gu, "$1") - .replace(/(?<=\S)_+(?=$|[^\p{L}\p{N}])/gu, "") + .replace(CLOSING_UNDERSCORES, "$1") .replace(/\\([\\`*_{}[\]()#+\-.!|>~])/g, "$1") .replace(/\s+/g, " ") .trim() diff --git a/app/tests/older-safari-build.test.ts b/app/tests/older-safari-build.test.ts new file mode 100644 index 0000000000..49b11952b1 --- /dev/null +++ b/app/tests/older-safari-build.test.ts @@ -0,0 +1,456 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { RegExpParser, visitRegExpAST } from "@eslint-community/regexpp"; +import * as acorn from "acorn"; +import type { Server } from "bun"; +import { getResponse, HttpResponse, http, type RequestHandler } from "msw"; +import type { Browser, Page } from "playwright-core"; +import { + getGetArtifactResponseMock, + getGetArtifactVersionResponseMock, +} from "@/lib/api/generated/artifacts/artifacts.msw"; +import { pickAggregators } from "../workbench/api/handlers"; +import { DEFAULT_SESSION, sessionApi } from "../workbench/session"; +import { test } from "./renderer-crash"; + +/** + * THE BUILT APP WORKS IN SAFARI 16.0, THE OLDEST BROWSER IT IS BUILT FOR. + * + * FOUND IN POSTHOG. On OpenBot Cloud 1.2.11, every Admin page and most of the app's pages drew + * "This page couldn't be shown" in Safari 16.0 to 16.3, and in OpenBot Desktop on macOS before 13.3, whose + * window is that Safari's engine. A regular expression with a lookbehind (`(?<=` or `(? uses a build already made. + * With OPENBOT_APP_SHOTS= each page is saved as older-safari--.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; +const APP = join(import.meta.dir, ".."); + +/** A regular expression in a built chunk that Safari 16.0 can't compile, and why. */ +type Refused = { chunk: string; regex: string; needs: string[] }; + +/** What in `pattern` (with `flags`) an engine newer than Safari 16.0's must read. */ +export function newerThanSafari16(pattern: string, flags: string): string[] { + const needs = new Set(); + if (flags.includes("v")) needs.add("the v flag (Safari 17)"); + const parser = new RegExpParser({ ecmaVersion: 2025 }); + const parsedFlags = parser.parseFlags(flags); + const ast = parser.parsePattern(pattern, 0, pattern.length, { + unicode: parsedFlags.unicode, + unicodeSets: parsedFlags.unicodeSets, + }); + const names = new Set(); + visitRegExpAST(ast, { + onAssertionEnter(node) { + if (node.kind === "lookbehind") needs.add("a lookbehind (Safari 16.4)"); + }, + onCapturingGroupEnter(node) { + if (!node.name) return; + if (names.has(node.name)) + needs.add("a group name used twice (Safari 17)"); + names.add(node.name); + }, + onModifiersEnter() { + needs.add("modifiers, (?i:…) (Safari 18)"); + }, + }); + return [...needs]; +} + +type Node = { type: string; [key: string]: unknown }; + +function isNode(value: unknown): value is Node { + return ( + typeof value === "object" && + value !== null && + typeof (value as Node).type === "string" + ); +} + +/** A string the code spells out whole: a literal, or a template with nothing in it. */ +function spelled(node: unknown): string | null { + if (!isNode(node)) return null; + if (node.type === "Literal" && typeof node.value === "string") + return node.value; + if ( + node.type === "TemplateLiteral" && + (node.expressions as unknown[]).length === 0 + ) { + const [quasi] = node.quasis as { value: { cooked: string | null } }[]; + return quasi?.value.cooked ?? null; + } + return null; +} + +/** Every regular expression `code` compiles from text it spells out, and whether inside a `try`. */ +function regexesIn( + code: string, +): { pattern: string; flags: string; probe: boolean }[] { + const found: { pattern: string; flags: string; probe: boolean }[] = []; + const program = acorn.parse(code, { + ecmaVersion: "latest", + sourceType: "module", + }) as unknown as Node; + const walk = (node: Node, probe: boolean) => { + if (node.type === "Literal" && node.regex) { + const { pattern, flags } = node.regex as { + pattern: string; + flags: string; + }; + found.push({ pattern, flags, probe }); + } + if ( + (node.type === "NewExpression" || node.type === "CallExpression") && + isNode(node.callee) && + node.callee.type === "Identifier" && + node.callee.name === "RegExp" + ) { + const [source, flags] = node.arguments as unknown[]; + const pattern = spelled(source); + if (pattern !== null) + found.push({ + pattern, + flags: flags === undefined ? "" : (spelled(flags) ?? ""), + probe, + }); + } + for (const [key, value] of Object.entries(node)) { + // A `try` block's own statements are a feature test; its handler and finalizer are not. + const inside = probe || (node.type === "TryStatement" && key === "block"); + if (Array.isArray(value)) { + for (const child of value) if (isNode(child)) walk(child, inside); + } else if (isNode(value)) walk(value, inside); + } + }; + walk(program, false); + return found; +} + +/** Every regular expression in the built app that Safari 16.0 can't compile. */ +export function refusedInBuild(dist: string): Refused[] { + const refused: Refused[] = []; + const assets = join(dist, "assets"); + for (const chunk of readdirSync(assets).filter((name) => + name.endsWith(".js"), + )) { + const code = readFileSync(join(assets, chunk), "utf8"); + for (const { pattern, flags, probe } of regexesIn(code)) { + if (probe) continue; + const needs = newerThanSafari16(pattern, flags); + if (needs.length > 0) + refused.push({ chunk, regex: `/${pattern}/${flags}`, needs }); + } + } + return refused; +} + +/* + * SAFARI 16.0'S REGULAR EXPRESSIONS, IN A CURRENT ENGINE. Before 16.4, WebKit refused a lookbehind + * with "Invalid regular expression: invalid group specifier name", and before 17 the `v` flag. The + * build makes every such literal `new RegExp("…")`, so refusing them in the constructor, as this does + * before any of the page's code runs, is what Safari 16.0 does with the built app. Kept as a string: + * it runs in the page, not here. + */ +const SAFARI_16_REGEXP = `(() => { + const Native = RegExp; + const refuse = (source, flags) => { + if (String(flags ?? "").includes("v")) + throw new SyntaxError("Invalid flags supplied to RegExp constructor '" + flags + "'"); + let inClass = false; + for (let at = 0; at < source.length; at++) { + const char = source[at]; + if (char === "\\\\") { at++; continue; } + if (inClass) { if (char === "]") inClass = false; continue; } + if (char === "[") { inClass = true; continue; } + if (char === "(" && source[at + 1] === "?" && source[at + 2] === "<" && + (source[at + 3] === "=" || source[at + 3] === "!")) + throw new SyntaxError("Invalid regular expression: invalid group specifier name"); + } + }; + const check = (args) => { + const [pattern, flags] = args; + const source = pattern instanceof Native ? pattern.source : String(pattern ?? ""); + refuse(source, flags === undefined && pattern instanceof Native ? pattern.flags : flags); + }; + const Older = new Proxy(Native, { + construct(target, args, newTarget) { + check(args); + return Reflect.construct(target, args, newTarget === Older ? target : newTarget); + }, + apply(target, self, args) { + check(args); + return Reflect.apply(target, self, args); + }, + }); + globalThis.RegExp = Older; +})();`; + +const ORGANIZATION = "/api/v2/organizations/default"; +const DOCUMENT_ID = "OlderSafariDoc0000001"; +const EMAIL = "dana@northwind.test"; +const DOCUMENT = [ + "# Launch notes", + "", + `Questions go to ${EMAIL}, and the plan's numbers are below.`, + "", + "The growth rate is \\(r = 0.12\\) a month, so after a year it is \\[1.12^{12}\\]", +].join("\n"); + +let dist: string; +let made: string | undefined; +let server: Server; +let handlers: RequestHandler[]; +const browsers = new Map<"chromium" | "webkit", Browser>(); + +/** An admin of the default organization, as the workbench answers one, then the spec's answers. */ +async function apiHandlers(): Promise { + // Signed in, every one of them is a value: GET routes. + const session = Object.entries(sessionApi(DEFAULT_SESSION, "admin")).map( + ([route, answer]) => + http.get(`*${route.slice(route.indexOf(" ") + 1)}`, () => + HttpResponse.json( + (answer?.mode === "value" ? answer.body : {}) as object, + ), + ), + ); + const modules: Record> = {}; + const generated = join(APP, "src", "lib", "api", "generated"); + for (const tag of readdirSync(generated)) { + const file = join(generated, tag, `${tag}.msw.ts`); + if (existsSync(file)) modules[file] = await import(file); + } + return [...session, ...pickAggregators(modules)]; +} + +/** A public document on the artifacts host, as the API answers it. */ +function documentAnswer(path: string): Response | null { + const base = `${ORGANIZATION}/artifacts/${DOCUMENT_ID}`; + if (path === base) { + const { artifact } = getGetArtifactResponseMock(); + return Response.json({ + artifact: { + ...artifact, + id: DOCUMENT_ID, + title: "Launch notes", + kind: "document", + visibility: "public", + currentVersion: 1, + canEdit: false, + canDelete: false, + canShare: false, + }, + }); + } + if (path === `${base}/versions/1` || path === `${base}/content`) { + const content = getGetArtifactVersionResponseMock(); + return Response.json({ + ...content, + artifactId: DOCUMENT_ID, + kind: "document", + version: { ...content.version, number: 1 }, + content: { markdown: DOCUMENT }, + }); + } + return null; +} + +async function answer(request: Request): Promise { + const path = new URL(request.url).pathname; + if (path.startsWith("/api/")) { + const document = documentAnswer(path); + if (document) return document; + const found = await getResponse(handlers, request); + return found ?? Response.json({ detail: "No answer." }, { status: 404 }); + } + const file = join(dist, path); + if (path !== "/" && !path.endsWith("/") && existsSync(file)) + return new Response(Bun.file(file)); + let html = readFileSync(join(dist, "index.html"), "utf8"); + // The artifacts host answers an artifact's address with this same page and its mark. + if (path === `/${DOCUMENT_ID}`) + html = html.replace( + "", + '', + ); + return new Response(html, { headers: { "content-type": "text/html" } }); +} + +beforeAll(async () => { + if (!asked) return; + dist = process.env.OPENBOT_APP_DIST ?? ""; + if (!dist) { + made = mkdtempSync(join(tmpdir(), "openbot-older-safari-")); + dist = made; + const build = Bun.spawn( + [ + "bun", + "--bun", + "node_modules/vite/bin/vite.js", + "build", + "--outDir", + dist, + "--emptyOutDir", + "--logLevel", + "error", + ], + { cwd: APP, stdout: "inherit", stderr: "inherit" }, + ); + if ((await build.exited) !== 0) throw new Error("vite build failed"); + } + handlers = await apiHandlers(); + server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: answer }); + const playwright = await import("playwright-core"); + for (const engine of engines) + browsers.set( + engine, + await playwright[engine].launch( + engine === "chromium" ? { channel: "chromium" } : {}, + ), + ); +}, 600_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + server?.stop(true); + if (made) rmSync(made, { recursive: true, force: true }); +}); + +type Opened = { page: Page; errors: string[] }; + +/** A page of the built app in `engine`, with Safari 16.0's regular expressions. */ +async function open( + engine: "chromium" | "webkit", + path: string, +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const context = await browser.newContext({ + viewport: { width: 1200, height: 850 }, + reducedMotion: "reduce", + }); + const page = await context.newPage(); + const errors: string[] = []; + await page.addInitScript({ content: SAFARI_16_REGEXP }); + page.on("pageerror", (error) => errors.push(`pageerror: ${error.message}`)); + page.on("console", (message) => { + const text = message.text(); + if ( + message.type() === "error" && + /Invalid regular expression|invalid group specifier|uninitialized variable/i.test( + text, + ) + ) + errors.push(`console: ${text}`); + }); + await page.goto(`http://127.0.0.1:${server.port}${path}`); + return { page, errors }; +} + +/** Wait for `shows`, then check the page drew without the error screen or a regex error. */ +async function drawn( + { page, errors }: Opened, + shows: string, + name: string, + engine: string, +) { + await page + .getByText(shows, { exact: false }) + .first() + .waitFor({ timeout: 30_000 }) + .catch(() => {}); + await page.waitForLoadState("networkidle"); + if (shots) { + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join(shots, `older-safari-${name}-${engine}.png`), + }); + } + const text = await page.locator("body").innerText(); + // The app's error screens: a page's, and an artifact's. + expect(text).not.toContain("couldn't be shown"); + expect(text).not.toContain("Something went wrong"); + expect(errors).toEqual([]); + expect(text).toContain(shows); +} + +describe.skipIf(!asked)("the built app in Safari 16.0", () => { + test("no regular expression in the build needs an engine newer than Safari 16.0's", () => { + expect(refusedInBuild(dist)).toEqual([]); + }, 120_000); + + for (const engine of engines) { + test(`an Admin page draws with Safari 16.0's regular expressions, ${engine}`, async () => { + const opened = await open(engine, "/admin/people"); + try { + await drawn(opened, "People", "admin-people", engine); + } finally { + await opened.page.context().close(); + } + }, 90_000); + + test(`an app page draws with Safari 16.0's regular expressions, ${engine}`, async () => { + const opened = await open(engine, "/connections"); + try { + await drawn(opened, "Apps", "connections", engine); + } finally { + await opened.page.context().close(); + } + }, 90_000); + + test(`a document links its email address and draws its maths with Safari 16.0's regular expressions, ${engine}`, async () => { + const opened = await open(engine, `/${DOCUMENT_ID}`); + try { + await drawn(opened, "Questions go to", "document", engine); + await expect( + opened.page.locator(`a[href="mailto:${EMAIL}"]`).count(), + ).resolves.toBe(1); + await opened.page + .locator(".katex") + .first() + .waitFor({ timeout: 30_000 }); + expect(await opened.page.locator(".katex").count()).toBe(2); + expect(opened.errors).toEqual([]); + } finally { + await opened.page.context().close(); + } + }, 90_000); + } +}); diff --git a/app/tests/older-safari-same-words.test.ts b/app/tests/older-safari-same-words.test.ts new file mode 100644 index 0000000000..9ff9f2771d --- /dev/null +++ b/app/tests/older-safari-same-words.test.ts @@ -0,0 +1,290 @@ +import { describe, expect, test } from "bun:test"; +import { seamsOf } from "@/components/audit/audit-cells"; +import { sentencesOf } from "@/lib/boundaries/rules"; +import { EmailAfterBoundary } from "@/lib/markdown-email-links"; +import { escapeDollars, linesOf } from "@/lib/maths"; +import { + firstClause, + toolSummary, + withoutFindingById, + withoutFindingByIdIn, +} from "@/lib/plugins/tool-words"; +import { CLOSING_UNDERSCORES, cellsOf } from "@/lib/tasks/line"; + +/** + * THE SAME WORDS WITHOUT A LOOKBEHIND. Safari reads `(?<=` and `(? { + state = (state * 1_103_515_245 + 12_345) % 2_147_483_648; + return state / 2_147_483_648; + }; + const made: string[] = []; + for (let one = 0; one < count; one++) { + let text = ""; + const length = Math.floor(next() * longest); + for (let at = 0; at < length; at++) + text += pieces[Math.floor(next() * pieces.length)]; + made.push(text); + } + return made; +} + +/** Real tool descriptions, as Composio publishes them for Gmail, GitHub, HubSpot, Slack and Notion. */ +const DESCRIPTIONS = [ + "Tool to abort a repository migration that is queued or in progress.", + "Retrieves metadata for a SINGLE specific calendar from the user's calendar list by its calendar ID.", + "Deletes a specific deployment branch or tag policy, identified by its ID, from a given environment within a repository.", + "Updates the title, join URL, or desktop app join URL for an existing Slack call identified by its ID.", + "Retrieves detailed information for an existing Slack reminder specified by its ID.", + "Retrieves a Gmail message attachment by message and attachment IDs and returns a downloadable file using the supplied filename.", + "Lists the repositories of the authenticated user, sorted by ID, with pagination.", + "Returns contacts filterable by ID, email or name.", + "Fetches a message by its ID or by thread ID; use GMAIL_LIST_THREADS first.", + "Gets a page by ID. Use the `page_id` returned by NOTION_SEARCH.", + "Retrieves a HubSpot deal by its ID, email, name, or other unique property.", + "Removes a label from a message by ID and removes it from messages in the thread.", + "Returns the list of events ordered by ID, then by start time.", + "Archives a batch of contacts by their IDs (or a specified unique property).", + "Fetch a channel by its channel ID and timestamp! Then post a reply? Maybe; or not.", + "Use this tool to get a user, specified by the user ID, from the workspace.", + "Searches files using their IDs, sorted by name.", + "Permanently DELETES a filter. Cannot be undone.", + "", +]; + +describe("an app's tool descriptions", () => { + const BY_ITS_ID = + /(,?\s+(?:identified|specified))?\s+(? text.replace(BY_ITS_ID, withoutFindingById); + const fuzz = strings(1, [ + " ", + " ", + "\t", + ",", + ".", + "by", + "using", + "its ", + "the ", + "message ", + "and ", + "ID", + "IDs", + "sorted", + "unsorted", + "ordered", + "filtering", + "identified", + "specified", + "or", + "x", + "(", + ]); + + test("finding a thing by its ID is taken out exactly where the lookbehind took it out", () => { + for (const text of [...DESCRIPTIONS, ...fuzz]) + expect(withoutFindingByIdIn(text)).toBe(before(text)); + }); + + test("sorting or filtering by ID is left as it is, and finding by ID still goes", () => { + expect(toolSummary("Lists issues sorted by ID.")).toBe( + "Lists issues sorted by ID.", + ); + expect(toolSummary("Returns contacts filterable by ID.")).toBe( + "Returns contacts filterable by ID.", + ); + expect(toolSummary("Gets an issue by its ID.")).toBe("Gets an issue."); + expect(withoutFindingByIdIn("sorted by using ID")).toBe( + before("sorted by using ID"), + ); + expect(withoutFindingByIdIn("sorted by the by ID now")).toBe( + before("sorted by the by ID now"), + ); + }); + + test("a description's first clause ends where the lookbehind ended it", () => { + const fuzzed = strings(2, [ + " ", + " ", + ".", + "!", + "?", + ";", + "; ", + "A", + "a", + "B ", + "\n", + "x", + ]); + for (const text of [...DESCRIPTIONS, ...fuzzed]) + expect(firstClause(text)).toBe( + text.split(/(?<=[.!?])\s+(?=[A-Z])|;\s/)[0] ?? "", + ); + }); +}); + +describe("a rule's sentences", () => { + test("are cut where the lookbehind cut them", () => { + const real = [ + "Stops the Bot from sending email outside the company. It can still draft one.", + "Never deletes a file! Asks first? Yes.", + "Blocks payments over $500.Except refunds. And credits.", + "One sentence only", + "", + ]; + const fuzzed = strings(3, [" ", " ", ".", "!", "?", "A", "a", "\n", "x"]); + for (const text of [...real, ...fuzzed]) + expect(sentencesOf(text)).toEqual(text.split(/(?<=[.!?])\s+(?=[A-Z])/)); + }); +}); + +describe("maths in a reply", () => { + test("a dollar sign is escaped where the lookbehind escaped it", () => { + const real = [ + "P=$25,000", + "\\$5 + $5", + "$$x$$", + "a\\\\$b", + "$", + "", + "r = 0.12", + ]; + const fuzzed = strings(4, ["$", "\\", "x", "$$", " "]); + for (const formula of [...real, ...fuzzed]) + expect(escapeDollars(formula)).toBe( + formula.replace(/(? { + const real = [ + "The rate is \\(r\\).\nAfter a year:\n\\[1.12^{12}\\]\n", + "```\ncode\n```\n\nText \\(x\\)", + "\n\n", + "no newline", + "", + ]; + const fuzzed = strings(5, ["\n", "\r\n", "a", "\\(", " "]); + for (const markdown of [...real, ...fuzzed]) + expect(linesOf(markdown)).toEqual(markdown.split(/(?<=\n)/)); + }); +}); + +describe("a task's line", () => { + test("a table row is cut at the pipes the lookbehind cut it at", () => { + const real = [ + "| Begins | Columbia Lake |", + "| a \\| b | c |", + "| --- | :--: |", + "||", + "\\||x", + "", + ]; + const fuzzed = strings(6, ["|", "\\", "a", " ", "\\|"]); + for (const row of [...real, ...fuzzed]) + expect(cellsOf(row)).toEqual(row.split(/(? { + const real = [ + "_Done_ for today", + "the snake_case name_", + "___", + "a__b", + "a___b", + "x_._ y", + "emphasis_ end", + "é_ then 日本_", + ]; + const fuzzed = strings(7, ["_", "__", " ", "a", "1", ".", "é", "😀"]); + for (const line of [...real, ...fuzzed]) + expect(line.replace(CLOSING_UNDERSCORES, "$1")).toBe( + line.replace(/(?<=\S)_+(?=$|[^\p{L}\p{N}])/gu, ""), + ); + }); +}); + +describe("an audit row's identifiers", () => { + test("are cut after the seams the lookbehind cut them after", () => { + const real = [ + "mcp.tools_discovered", + "/home/sam/report-2026.pdf", + "plain", + "a..b", + "-", + "", + ]; + const fuzzed = strings(8, [".", "/", "_", "-", "a", " "]); + for (const text of [...real, ...fuzzed]) + expect(seamsOf(text)).toEqual(text.split(/(?<=[./_-])/)); + }); +}); + +describe("email addresses in a reply", () => { + const LOOKBEHIND = /(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu; + + /** Every match from every `lastIndex`, as mdast-util-find-and-replace may ask for them. */ + function matches(finder: RegExp, text: string) { + const found: unknown[] = []; + for (let from = 0; from <= text.length + 1; from++) { + finder.lastIndex = from; + const match = finder.exec(text); + found.push( + match && { + index: match.index, + groups: [...match], + input: match.input, + lastIndex: finder.lastIndex, + }, + ); + if (!match) found.push(finder.lastIndex); + } + return found; + } + + test("are found where the lookbehind found them, from wherever the search starts", () => { + const real = [ + "Questions go to dana@northwind.test, and the numbers are below.", + "Write to sam.rivera+launch@example.co.uk (or ops@example.com).", + "mailto:ana@example.com and /sam@example.com and x:y@example.com", + "Not an address: user@localhost, or café@example.com, or 😀ana@example.com", + "a-b.c@d-e.f.g@h.i", + "@example.com", + ]; + const fuzzed = strings( + 9, + ["a", "1", ".", "-", "+", "_", "@", "b.c", " ", ":", "/", "é", "😀"], + 2000, + 14, + ); + for (const text of [...real, ...fuzzed]) + expect(matches(new EmailAfterBoundary(), text)).toEqual( + matches(new RegExp(LOOKBEHIND.source, "gu"), text), + ); + }); + + test("a long word with no address in it takes as long as with the lookbehind", () => { + const word = "a".repeat(100_000); + const finder = new EmailAfterBoundary(); + const start = performance.now(); + expect(finder.exec(word)).toBeNull(); + // Without the lookbehind's start, a regular expression tries every character to the word's + // end: about four seconds for this word. Tried only at the start, a few milliseconds. + expect(performance.now() - start).toBeLessThan(500); + }); +}); diff --git a/app/vite.config.ts b/app/vite.config.ts index e09e426d11..d54c68b43e 100644 --- a/app/vite.config.ts +++ b/app/vite.config.ts @@ -255,6 +255,46 @@ function sharedZodSettings(): Plugin { }; } +/** mdast-util-gfm-autolink-literal's email finder, a lookbehind Safari reads only from 16.4. */ +const LOOKBEHIND_EMAIL = + "/(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)/gu"; + +/* + * NO LOOKBEHIND IN THE EMAIL LINKS OF A BOT'S WORDS. GitHub-flavoured Markdown finds an email + * address with a lookbehind, on every reply and document, and Safari 16.0 to 16.3 refuse it: none of + * them drew. In the build it finds them with src/lib/markdown-email-links.ts, the same matches + * without one. A release of the package without this finder is left as it is, and + * app/tests/older-safari-build.test.ts fails on any lookbehind it brings. + */ +export function lookbehindFreeEmailLinks( + code: string, + id: string, +): string | null { + const file = normalizedModuleId(id).split("?")[0]; + if ( + !file.endsWith("/mdast-util-gfm-autolink-literal/lib/index.js") || + !code.includes(LOOKBEHIND_EMAIL) + ) + return null; + const finder = normalizedModuleId( + path.resolve(__dirname, "src/lib/markdown-email-links.ts"), + ); + return `import { emailAfterBoundary } from ${JSON.stringify(finder)};\n${code.replace( + LOOKBEHIND_EMAIL, + "emailAfterBoundary()", + )}`; +} + +function lookbehindFreeMarkdown(): Plugin { + return { + name: "openbot-lookbehind-free-markdown", + transform(code, id) { + const changed = lookbehindFreeEmailLinks(code, id); + return changed === null ? null : { code: changed, map: null }; + }, + }; +} + /** Vite's own modules, which it puts ahead of everything in a module that loads another. */ function isViteHelper(id: string): boolean { return ( @@ -348,6 +388,7 @@ export default defineConfig({ react(), tailwindcss(), sharedZodSettings(), + lookbehindFreeMarkdown(), ], resolve: { alias: { @@ -367,6 +408,13 @@ export default defineConfig({ server: serving, preview: serving, build: { + /* + * The oldest browsers OpenBot works in: Safari 16.0 (and OpenBot Desktop's window, which draws + * with the Mac's own Safari), Chrome and Edge 107, Firefox 104. Vite's own default, written out + * so the promise is ours: code + * that needs a newer browser fails app/tests/older-safari-build.test.ts rather than a person. + */ + target: ["chrome107", "edge107", "firefox104", "safari16"], rollupOptions: { input: buildPages, output: routeBuildRollupOutputOptions, diff --git a/bun.lock b/bun.lock index 69f9d4f78f..efb3239876 100644 --- a/bun.lock +++ b/bun.lock @@ -70,6 +70,7 @@ "zod": "^4.4.3", }, "devDependencies": { + "@eslint-community/regexpp": "4.12.3", "@happy-dom/global-registrator": "^20.11.2", "@tailwindcss/vite": "^4.3.3", "@tanstack/router-plugin": "^1.168.30", @@ -79,6 +80,7 @@ "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitejs/plugin-react": "^5.0.4", + "acorn": "8.19.0", "happy-dom": "^20.11.2", "msw": "2.15.0", "tailwindcss": "^4.3.3", @@ -435,6 +437,8 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + "@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.3", "", {}, "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ=="], + "@fastify/busboy": ["@fastify/busboy@2.1.1", "", {}, "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA=="], "@floating-ui/core": ["@floating-ui/core@1.8.0", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="],