diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1029fc5034..1bb163e30f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -764,6 +764,7 @@ jobs: app/tests/roster-working.test.tsx app/tests/routine-run-now-layout.test.tsx app/tests/run-ended-unheard-layout.test.tsx + app/tests/run-refused-browser.test.tsx app/tests/section-strip-routines.test.tsx app/tests/select-long-names-layout.test.tsx app/tests/select-scrolls-layout.test.tsx diff --git a/app/src/lib/agents/queries.ts b/app/src/lib/agents/queries.ts index e17eeb54a0..2cf962b3aa 100644 --- a/app/src/lib/agents/queries.ts +++ b/app/src/lib/agents/queries.ts @@ -13,7 +13,7 @@ import type { } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { ClientError } from "@/lib/client"; -import { type Failure, failureOf, isHeld } from "@/lib/load-failure"; +import { type Failure, failureOf } from "@/lib/load-failure"; export type AgentVisibility = BotVisibility; @@ -136,20 +136,19 @@ export function agentQueryOptions(agentId: string) { /** * Whether a Bot is, right now, not one this person can use: the read of it answers "not found". * - * A verdict about this moment, asked when a message to the Bot was refused, so it is not cached and - * it fails closed: only the API's own 404 says the Bot is gone. A read that could not be made, or a - * server that broke, says nothing about the Bot, and answers false. - * - * Except OpenBot holding off (a move, or the organization's database briefly out of reach): that - * refusal is thrown as it came, so the caller can say the server's sentence calmly (`failedRunReason`). + * A verdict about this moment, asked when a message to the Bot was refused, so it is not cached: + * only the API's own 404 says the Bot is gone, and only a read that answered says it is still there. + * A read that could not be made, or a server that broke, says nothing about the Bot, and is thrown + * as it came, so the caller claims neither (`failedRunReason`). OpenBot holding off (a move, or the + * organization's database briefly out of reach) is thrown the same way, and said calmly. */ export async function botNoLongerUsable(agentId: string): Promise { try { await getBot(organizationId(), agentId); return false; } catch (error) { - if (isHeld(error)) throw error; - return error instanceof ClientError && error.status === 404; + if (error instanceof ClientError && error.status === 404) return true; + throw error; } } diff --git a/app/src/lib/copilot/stopped-turn.ts b/app/src/lib/copilot/stopped-turn.ts index 9ed82a3b02..82e113cf69 100644 --- a/app/src/lib/copilot/stopped-turn.ts +++ b/app/src/lib/copilot/stopped-turn.ts @@ -46,6 +46,8 @@ export function stoppedReason(reported: unknown): string { if (busy) return busy.message; const refused = refusalForPerson(said); if (refused) return refused; + const notStarted = backEndRefused(said); + if (notStarted) return notStarted; const unreachable = backEndUnreachable(said); if (unreachable) return unreachable; if (RUNNER_DROPPED.test(said.trim())) return TURN_INTERRUPTED; @@ -108,6 +110,37 @@ export const UNREADABLE_REPLY = export const TURN_CUT_OFF = "The Bot stopped before it finished because OpenBot's backend stopped answering. What it saved is shown here."; +/** + * Said under a turn whose later run the backend answered and refused, with no sentence of its own + * for the person. It was answering, so it is not said to have stopped. Its work stands. + */ +export const TURN_REFUSED = + "OpenBot's backend couldn't carry on this turn, so the Bot stopped before it finished. What it saved is shown here."; + +/** + * Said when the backend answered a first run, or a join, and refused it with no sentence of its own + * for the person: the runtime's own `{ "error": … }`, or a fault on the server. The backend was + * reached, so "couldn't reach" would be false, and the raw body is nothing the person can act on. + */ +export const RUN_NOT_STARTED = + "OpenBot's backend couldn't start this turn, so your message wasn't sent. Try again, or ask an admin if it keeps happening."; +export const CONNECT_NOT_OPENED = + "OpenBot's backend couldn't open this conversation. Try again, or ask an admin if it keeps happening."; + +/** + * Said when the backend can't build the Bot a run names, though the Bot is still the person's: the + * runtime answers "Agent not found" for a Bot whose setup it can't run on (no instructions, or an + * address it can't use), while the API still lists the Bot and reads it back. + * + * FOUND ON OPENBOT CLOUD, 2026-12-03. A public Bot moved in from somebody's OpenBot Desktop had no + * instructions. Each run of it was answered 404 "Agent not found", and the person was told OpenBot + * couldn't reach its backend and to quit and reopen it, while the backend answered every time. + */ +export const BOT_CANNOT_RUN_MESSAGE_NOT_SENT = + "This Bot can't run because its setup isn't finished, so your message wasn't sent. Its owner or an admin can finish it in Setup."; +export const BOT_CANNOT_RUN = + "This Bot can't run because its setup isn't finished. Its owner or an admin can finish it in Setup."; + /** * Said under a turn whose run went away under it: the server running it stopped part way, and the * backend ended the run for it ("Runner connection dropped"). Its work stands, and Carry on picks it @@ -170,6 +203,11 @@ export function laterRunFailure(reported: unknown): string | null { : ""; if (refusalForPerson(said) || tooManyRuns(reported)) return stoppedReason(reported); + // Answered and refused: the backend was reached, so it is not said to have stopped answering. + if (backendAnswered(said)) { + console.warn("OpenBot's backend refused a later run of a turn.", said); + return TURN_REFUSED; + } // Thrown here, a cut connection is this browser's own, to OpenBot's backend: not the Bot's. if ( REST_REQUEST_FAILED.test(said.trim()) || @@ -186,12 +224,13 @@ export function laterRunFailure(reported: unknown): string | null { } /** - * The one reason that is NOT passed on in its own words: the browser couldn't reach the runtime. + * A request to the runtime that failed, NOT passed on in its own words. * * CopilotKit's Intelligence agent writes it as `REST request failed: `, * and what came back is the server's raw body, JSON included (`{"error":"Failed to resolve Learning - * Container"}`). Nothing in it is the person's to act on, so they are told what happened in their - * terms and the original goes to the console for whoever is debugging. + * Container"}`), or the fetch's own words when nothing came back. Nothing in it is the person's to + * act on, so they are told what happened in their terms (`backEndRefused` when the backend answered, + * `backEndUnreachable` when it didn't) and the original goes to the console for whoever is debugging. */ const REST_REQUEST_FAILED = /^REST (\w+) request failed\b:?\s*/; @@ -318,6 +357,41 @@ export function tooManyRuns(reported: unknown): ClientError | undefined { ); } +/** + * Whether a REST failure is the backend's own answer. + * + * The client throws what came back after its prefix: the body of the answer, else its status text, + * else the fetch's own words. The backend answers in JSON, its refusals and its faults alike. A + * fetch that failed ("Failed to fetch", Safari's "Load failed"), a proxy's page in front of a backend + * that is down, or a status text alone is the backend not answering. + */ +function backendAnswered(said: string): boolean { + const body = refusedBody(said); + return typeof body === "object" && body !== null && !Array.isArray(body); +} + +/** Whether a REST failure is the runtime's answer for a Bot it has not built for this person. */ +function agentNotFound(said: string): boolean { + const body = refusedBody(said); + return ( + typeof body === "object" && + body !== null && + (body as { error?: unknown }).error === "Agent not found" + ); +} + +/** + * A REST failure the backend answered, said in the person's terms: it was reached, and it could not + * start what was asked. The body goes to the console for whoever is debugging. Null when the backend + * did not answer, which `backEndUnreachable` says. + */ +function backEndRefused(said: string): string | null { + const match = REST_REQUEST_FAILED.exec(said.trim()); + if (!match || !backendAnswered(said)) return null; + console.warn("OpenBot's backend refused the request.", said); + return match[1] === "run" ? RUN_NOT_STARTED : CONNECT_NOT_OPENED; +} + function backEndUnreachable(said: string): string | null { const match = REST_REQUEST_FAILED.exec(said.trim()); if (!match) return null; @@ -394,11 +468,31 @@ export async function failedRunReason( if (!request) return said; const asked = await askAboutBot(botId, noLongerUsable); if (asked.held) return asked.held; - if (!asked.gone) return said; - return { - message: - request === "run" ? BOT_NOT_SHARED_MESSAGE_NOT_SENT : BOT_NOT_SHARED, - }; + if (asked.gone) + return { + message: + request === "run" ? BOT_NOT_SHARED_MESSAGE_NOT_SENT : BOT_NOT_SHARED, + }; + /* + * Still theirs, the server says, and the runtime has no such Bot to run: it can't build it from the + * setup it has. Said only when the server answered both, so a read that failed keeps the sentence + * it had. + */ + if (asked.known && agentNotFound(errorText(reported))) + return { + message: + request === "run" ? BOT_CANNOT_RUN_MESSAGE_NOT_SENT : BOT_CANNOT_RUN, + }; + return said; +} + +/** What a reported failure says, as `stoppedReason` reads it. */ +function errorText(reported: unknown): string { + return reported instanceof Error + ? reported.message + : typeof reported === "string" + ? reported + : ""; } /** @@ -433,11 +527,16 @@ export async function laterRunReason( async function askAboutBot( botId: string, noLongerUsable: (botId: string) => Promise, -): Promise<{ gone: boolean; held?: undefined } | { held: Failure }> { +): Promise< + | { gone: boolean; known: boolean; held?: undefined } + | { held: Failure; gone?: undefined; known?: undefined } +> { try { - return { gone: await noLongerUsable(botId) }; + return { gone: await noLongerUsable(botId), known: true }; } catch (error) { - return isHeld(error) ? { held: error as Failure } : { gone: false }; + return isHeld(error) + ? { held: error as Failure } + : { gone: false, known: false }; } } diff --git a/app/tests/channel-failed-run-restore.test.tsx b/app/tests/channel-failed-run-restore.test.tsx index 7ac592f19e..27861250ba 100644 --- a/app/tests/channel-failed-run-restore.test.tsx +++ b/app/tests/channel-failed-run-restore.test.tsx @@ -22,7 +22,9 @@ import { UNANSWERED_RETRY_MS, } from "@/lib/copilot/quiet-run"; import { + BOT_CANNOT_RUN_MESSAGE_NOT_SENT, CONNECTION_CUT_OFF, + RUN_NOT_STARTED, TURN_CUT_OFF, TURN_INTERRUPTED, UNREADABLE_REPLY, @@ -1055,21 +1057,49 @@ test.each(["intelligence", "sse"] as const)( }, ); +/* + * FOUND ON OPENBOT CLOUD, 2026-12-03 (Desktop 1.2.0-rc.5 connected to Cloud 1.2.9). A new + * conversation with a public Bot the runtime couldn't build: each run was answered 404 "Agent not + * found" while the Bot was still listed and read back, and the conversation said OpenBot couldn't + * reach its backend and to quit and reopen it. Only a backend that didn't answer is out of reach. + */ test.each([ - ["the back end cannot be reached at all", "unreachable", "found"], - ["the back end answers with a server error", "breaks", "breaks"], - ["the run is refused but the Bot is still theirs", "refused", "found"], - ["the run is refused and the Bot cannot be read", "refused", "breaks"], + [ + "the back end cannot be reached at all", + "unreachable", + "found", + UNREACHABLE, + ], + [ + "the back end answers with a server error", + "breaks", + "breaks", + RUN_NOT_STARTED, + ], + [ + "the run is refused but the Bot is still theirs", + "refused", + "found", + BOT_CANNOT_RUN_MESSAGE_NOT_SENT, + ], + [ + "the run is refused and the Bot cannot be read", + "refused", + "breaks", + RUN_NOT_STARTED, + ], ] as const)( - "a message that is not sent because %s still says the back end couldn't be reached", - async (_why, kind, read) => { + "a message that is not sent because %s says what happened", + async (_why, kind, read, sentence) => { transport = "intelligence"; plans = [{ kind }]; botRead = read; const live = open(); await send(live, "Summarise my inbox"); const shown = await live.findByTestId("transcript-stopped"); - expect(shown.textContent).toBe(UNREACHABLE); + expect(shown.textContent).toBe(sentence); + if (kind !== "unreachable") + expect(live.queryByText(/couldn't reach|quit and reopen/)).toBeNull(); }, ); diff --git a/app/tests/desktop-problems.test.ts b/app/tests/desktop-problems.test.ts index 992a9bd1f2..08573e3879 100644 --- a/app/tests/desktop-problems.test.ts +++ b/app/tests/desktop-problems.test.ts @@ -426,8 +426,9 @@ test("a run whose request the server refused is handed over with the request id await bot.runAgent().catch(() => undefined); await waitFor(() => expect(recorded()).toHaveLength(1)); stop(); + // The backend answered (a 500 problem): it was reached, and is not said to be out of reach. const sentence = - "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot."; + "OpenBot's backend couldn't start this turn, so your message wasn't sent. Try again, or ask an admin if it keeps happening."; expect(shown.at(-1)).toBe(sentence); expect(recorded()).toEqual([ { @@ -522,7 +523,7 @@ test("in a browser, the same failures are kept in the page for the troubleshooti { kind: "run", message: - "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", + "OpenBot's backend couldn't start this turn, so your message wasn't sent. Try again, or ask an admin if it keeps happening.", requestId: "req_run500", appVersion: VERSION, }, diff --git a/app/tests/organization-unavailable-chat.test.tsx b/app/tests/organization-unavailable-chat.test.tsx index 3b62847f6b..b6823eda91 100644 --- a/app/tests/organization-unavailable-chat.test.tsx +++ b/app/tests/organization-unavailable-chat.test.tsx @@ -46,8 +46,12 @@ afterAll(async () => { await stop(); }); -const BACKEND_UNREACHABLE = - "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot."; +/** + * A run the server answered with a fault (500): the backend was reached, so it says the backend + * couldn't start the turn, never that it couldn't be reached (stopped-turn.ts `RUN_NOT_STARTED`). + */ +const SERVER_FAULT = + "OpenBot's backend couldn't start this turn, so your message wasn't sent. Try again, or ask an admin if it keeps happening."; const CHOICES_FAILED = "Couldn't load the choices. Try again in a moment."; /** The server's sentence for a person over its limit (429). */ const TOO_MANY = "Too many call attempts. Try again in a moment."; @@ -471,7 +475,7 @@ describe.skipIf(!asked)( .getByTestId("transcript-stopped") .waitFor({ timeout: 15_000 }); await style(page); - seen.conversation = await drawn(page, BACKEND_UNREACHABLE); + seen.conversation = await drawn(page, SERVER_FAULT); } finally { await page.close(); } @@ -496,7 +500,7 @@ describe.skipIf(!asked)( .getByTestId("bot-chat-stopped") .waitFor({ timeout: 15_000 }); await style(page); - seen.botPage = await drawn(page, BACKEND_UNREACHABLE); + seen.botPage = await drawn(page, SERVER_FAULT); } finally { await page.close(); } diff --git a/app/tests/run-refused-browser.test.tsx b/app/tests/run-refused-browser.test.tsx new file mode 100644 index 0000000000..5d56021e00 --- /dev/null +++ b/app/tests/run-refused-browser.test.tsx @@ -0,0 +1,437 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Server } from "bun"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotDelegationResponseMock } from "@/lib/api/generated/agents/agents.msw"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { + BOT_CANNOT_RUN_MESSAGE_NOT_SENT, + RUN_NOT_STARTED, +} from "@/lib/copilot/stopped-turn"; +import { personBody } from "./accounts-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { still } from "./page-still"; +// A WebKit renderer crash under CI's load runs the test again (renderer-crash.ts). +import { test } from "./renderer-crash"; + +/** + * A first message the backend refuses says what happened, in a real browser: never that OpenBot + * couldn't reach its backend while the backend answered. + * + * FOUND ON OPENBOT CLOUD, 2026-12-03 (OpenBot Desktop 1.2.0-rc.5 connected to Cloud 1.2.9). A new + * conversation with a public Bot the runtime couldn't build (it had no instructions). Each run was + * answered 404 with the runtime's own body, `{"error":"Agent not found",…}`, while the API still + * listed the Bot and read it back. CopilotKit's Intelligence agent throws that as `REST run request + * failed: `, the status gone, and the conversation said "OpenBot couldn't reach its + * backend, so your message wasn't sent. Try again, or quit and reopen OpenBot." Three times. + * + * The real conversation in the app's frame (run-ended-unheard.fixture.tsx) with the runtime client + * the app uses, over the Intelligence transport as Cloud runs it, against a real HTTP server on this + * machine that answers at the API's and the runtime's addresses. The run is answered as Cloud + * answered it, refused as the run gate refuses, refused with no sentence for the person, or not + * answered at all (the browser's own fetch failure: "Failed to fetch" in Chromium, "Load failed" in + * WebKit). + * + * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/run-refused-browser.test.tsx + * + * Chromium by default. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With OPENBOT_APP_SHOTS= + * each is saved as run-refused---.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, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; +const BOT_ID = "general-assistant"; +const CONVERSATION = "launch-conversation"; +const BOT_PATH = `${ORGANIZATION}/bots/${BOT_ID}`; +const ASKED = "Summarise last week's customer meetings for Nicky."; + +const UNREACHABLE = + "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot."; +const MODEL_NOT_ALLOWED = + "This Bot uses openai/gpt-6.1-terra, which isn't an allowed model. Ask an admin to allow it."; + +const BOT = { + ...getGetBotResponseMock().bot, + id: BOT_ID, + name: "General Assistant", + mine: false, + canManage: false, + systemOwned: false, + visibility: "public" as const, +}; +const DELEGATION = { ...getGetBotDelegationResponseMock(), botId: BOT_ID }; + +type Refusal = "not-built" | "gate" | "no-sentence" | "no-answer"; + +/** How each case's run is answered, and what the person reads under their message. */ +const CASES: { refusal: Refusal; why: string; said: string }[] = [ + { + refusal: "not-built", + why: "the backend has no Bot to run for the setup it has", + said: BOT_CANNOT_RUN_MESSAGE_NOT_SENT, + }, + { + refusal: "gate", + why: "the run gate refuses it with its own sentence (403)", + said: MODEL_NOT_ALLOWED, + }, + { + refusal: "no-sentence", + why: "the backend refuses it with no sentence for the person (403)", + said: RUN_NOT_STARTED, + }, + { + refusal: "no-answer", + why: "nothing answers", + said: UNREACHABLE, + }, +]; + +let refusal: Refusal = "not-built"; +let runs = 0; + +const json = (body: unknown, status = 200, type = "application/json") => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": type, "cache-control": "private, no-store" }, + }); + +/** The run, answered as each case has it. */ +function run(): Response { + runs += 1; + if (refusal === "not-built") + // Word for word what Cloud's runtime answered each of the three runs (req_3cf242ca…). + return json( + { + error: "Agent not found", + message: `Agent '${BOT_ID}' does not exist`, + }, + 404, + ); + if (refusal === "gate") + return json( + { + type: "https://open.bot/errors/model-not-allowed", + title: "That model isn't allowed.", + status: 403, + detail: MODEL_NOT_ALLOWED, + code: "MODEL_NOT_ALLOWED", + category: "permission", + retryable: false, + requestId: "req_6f1c2a9e-0b7d-4e57-9a43-1d2f3c4b5a69", + traceId: "4bf92f3577b34da6a3ce929d0e0e4736", + error: MODEL_NOT_ALLOWED, + }, + 403, + "application/problem+json", + ); + return json({ error: "Forbidden" }, 403); +} + +/** What the server answers at the API's and the runtime's addresses. */ +async function answer(request: Request): Promise { + const path = new URL(request.url).pathname; + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { [BOT_ID]: { description: "Fixture", capabilities: {} } }, + mode: "intelligence", + intelligence: { wsUrl: "ws://127.0.0.1/client" }, + telemetryDisabled: true, + }); + // A conversation no Bot has run in yet has nothing to join. + if (path.endsWith("/connect")) return new Response(null, { status: 204 }); + if (path.endsWith("/run")) return run(); + if (path.startsWith(`${ORGANIZATION}/people/me/approval-modes/`)) + return json({ asksEveryStep: false }); + if (path === `${BOT_PATH}/delegation`) return json(DELEGATION); + // The Bot is still the person's: the API lists it and reads it back. + if (path === BOT_PATH) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (path === `${BOT_PATH}/grants`) return json(botGrantsBody()); + if (path === `${BOT_PATH}/components`) + return json({ components: [], nextCursor: null }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: "travis", + name: "Travis Murdock", + email: "travis@northwind.example", + role: "member", + }), + openbotVersion: "v1.2.9", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + if (/\/conversations\/[^/]+\/(activity|signal-busy)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/refused-turns$/.test(path)) + return json({ refusedTurns: [], nextCursor: null }); + // As Cloud answered Travis's: nothing to join in a conversation no Bot has run in yet. + if (path === `${ORGANIZATION}/conversations/${CONVERSATION}/join-tokens`) + return json( + { + type: "https://open.bot/errors/conflict", + title: "Conflict.", + status: 409, + detail: "No Bot has run in this conversation yet.", + code: "CONFLICT", + }, + 409, + "application/problem+json", + ); + if (/\/threads\/[^/]+\/messages$/.test(path)) return json({ messages: [] }); + return undefined; +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "run-ended-unheard.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let server: Server | undefined; +let origin = ""; + +beforeAll(async () => { + if (!asked) return; + const script = await bundle(); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 0, + async fetch(request) { + const path = new URL(request.url).pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return new Response(Bun.file(font)); + if (path.startsWith("/api/")) + return (await answer(request)) ?? json({ detail: "Not found." }, 404); + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); + }, + }); + origin = `http://127.0.0.1:${server.port}`; + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + await server?.stop(true); +}); + +/** Styled for everything now on the page. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); +} + +/** The notice under the message: its sentence, and whether it sits inside the window. */ +function noticeDrawn(page: Page) { + return page.evaluate(() => { + const row = document.querySelector('[data-testid="transcript-stopped"]'); + const box = row?.getBoundingClientRect(); + return { + said: row?.querySelector('[role="alert"]')?.textContent ?? null, + inside: !!box && box.left >= -0.5 && box.right <= innerWidth + 0.5, + sideways: document.documentElement.scrollWidth > innerWidth, + }; + }); +} + +/** At a phone's width too for the sentence Cloud's refusal reads as, the longest one. */ +function windowsFor(kind: Refusal) { + return kind === "not-built" + ? [ + { width: 1280, height: 800 }, + { width: 390, height: 844 }, + ] + : [{ width: 1280, height: 800 }]; +} + +describe.skipIf(!asked)("a first message the backend refuses", () => { + for (const engine of engines) + for (const { refusal: kind, why, said } of CASES) + for (const window of windowsFor(kind)) + test(`says what happened when ${why}, in ${engine}, ${window.width}px`, async () => { + refusal = kind; + runs = 0; + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: "light", + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + // Nothing answers: the browser's own fetch fails, in each engine's words. + if (kind === "no-answer") + await page.route("**/api/copilotkit/agent/*/run", (route) => + route.abort("failed"), + ); + try { + await page.goto(`${origin}/channel/${CONVERSATION}?quietMs=400`); + const box = page.getByRole("textbox", { name: "Message" }); + await box.waitFor({ timeout: 15_000 }); + await style(page); + await box.click(); + await page.keyboard.type(ASKED); + await page.getByRole("button", { name: "Send message" }).click(); + + const stopped = page.getByTestId("transcript-stopped"); + await stopped.waitFor({ timeout: 15_000 }); + // Said once the server has answered whether the Bot is still the person's. + await page + .waitForFunction( + (sentence) => + document.querySelector( + '[data-testid="transcript-stopped"] [role="alert"]', + )?.textContent === sentence, + said, + { timeout: 15_000 }, + ) + // Not said: what was is compared below, and the screen is kept to look at. + .catch(() => undefined); + await style(page); + await still(page); + if (shots) { + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join( + shots, + `run-refused-${kind}-${engine}-${window.width}.png`, + ), + }); + } + expect(await noticeDrawn(page)).toEqual({ + said, + inside: true, + sideways: false, + }); + if (kind !== "no-answer") { + expect(runs).toBe(1); + expect( + await page.getByText(/couldn't reach|quit and reopen/).count(), + ).toBe(0); + } + // Nothing of the raw body reaches the person. + expect( + await page + .getByText(/REST run request failed|Agent not found|\{"error"/) + .count(), + ).toBe(0); + } finally { + await page.close(); + } + }, 120_000); +}); diff --git a/app/tests/sidebar-current-row.test.tsx b/app/tests/sidebar-current-row.test.tsx index e0e94cdda7..a60d3836c7 100644 --- a/app/tests/sidebar-current-row.test.tsx +++ b/app/tests/sidebar-current-row.test.tsx @@ -1,9 +1,16 @@ -import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { afterAll, beforeAll, describe, expect } from "bun:test"; 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 { still } from "./page-still"; +/* + * A WebKit renderer crash under CI's load runs the test again (renderer-crash.ts). Found in CI on + * 2026-12-03: moved into another shard of the WebKit job by a file added before it, this file's + * first WebKit test failed twice running with "Target page, context or browser has been closed", + * for nothing it checks, and passed alone and on that shard at two workers. + */ +import { test } from "./renderer-crash"; /** * The sidebar's strip says which section is open, and on a page no section owns it says no page is. diff --git a/app/tests/stopped-turn.test.ts b/app/tests/stopped-turn.test.ts index 527a2edb79..4918b36aa5 100644 --- a/app/tests/stopped-turn.test.ts +++ b/app/tests/stopped-turn.test.ts @@ -1,11 +1,16 @@ import { describe, expect, test } from "bun:test"; import { + BOT_CANNOT_RUN, + BOT_CANNOT_RUN_MESSAGE_NOT_SENT, + CONNECT_NOT_OPENED, CONNECTION_CUT_OFF, failedRunReason, laterRunFailure, + RUN_NOT_STARTED, stoppedReason, TURN_CUT_OFF, TURN_INTERRUPTED, + TURN_REFUSED, } from "../src/lib/copilot/stopped-turn"; /** @@ -110,31 +115,85 @@ describe("the reason a turn ended", () => { ).toBe("The endpoint refused the connection"); }); - test("says OpenBot couldn't reach its backend, not the raw request failure", () => { - // The exact text a teammate saw on OpenBot 1.0.0, built by CopilotKit's Intelligence agent when - // the run request to the runtime fails. - const run = stoppedReason( - new Error( - 'REST run request failed: {"error":"Failed to resolve Learning Container"}', - ), - ); - expect(run).toBe( - "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", - ); - - // The same failure on joining a thread, which sends nothing. - const connect = stoppedReason( - "REST connect request failed: Failed to fetch", - ); - expect(connect).toBe( - "OpenBot couldn't reach its backend. Try again, or quit and reopen OpenBot.", - ); + test("says OpenBot couldn't reach its backend only when nothing answered, never the raw request failure", () => { + // What CopilotKit's Intelligence agent throws when the fetch itself fails: Chromium's words, + // WebKit's, Firefox's, and a proxy's page or status text in front of a backend that is down. + for (const failed of [ + "Failed to fetch", + "Load failed", + "NetworkError when attempting to fetch resource.", + "Bad Gateway", + "502 Bad Gateway", + ]) { + expect([ + failed, + stoppedReason(`REST run request failed: ${failed}`), + ]).toEqual([ + failed, + "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", + ]); + // The same failure on joining a thread, which sends nothing. + expect([ + failed, + stoppedReason(`REST connect request failed: ${failed}`), + ]).toEqual([ + failed, + "OpenBot couldn't reach its backend. Try again, or quit and reopen OpenBot.", + ]); + } + }); - for (const shown of [run, connect]) { - expect(shown).not.toContain("REST"); - expect(shown).not.toContain("{"); - expect(shown).not.toContain("Learning Container"); + /* + * FOUND ON OPENBOT CLOUD, 2026-12-03 (Desktop 1.2.0-rc.5 connected to Cloud 1.2.9). The backend + * answered each run with its own body, and the person was told it couldn't be reached and to quit + * and reopen OpenBot. A backend that answered is never said to be out of reach. + */ + test("a run the backend answered and refused never says the backend couldn't be reached", () => { + for (const body of [ + // The runtime's own refusal, a fault behind it, and a 403 and a 409 that are no OpenBot problem. + '{"error":"Failed to resolve Learning Container"}', + '{"error":"Forbidden"}', + '{"error":{"code":"THREAD_LOCK_FAILED","message":"Thread is already locked by another runner.","category":"conflict","retryable":true}}', + '{"type":"about:blank","title":"Forbidden","status":403,"detail":"Failed to resolve Learning Container"}', + '{"type":"https://open.bot/errors/internal-server-error","title":"Unexpected server error.","status":500,"detail":"Unexpected server error.","code":"INTERNAL_SERVER_ERROR"}', + ]) { + const run = stoppedReason(new Error(`REST run request failed: ${body}`)); + expect([body, run]).toEqual([body, RUN_NOT_STARTED]); + const connect = stoppedReason(`REST connect request failed: ${body}`); + expect([body, connect]).toEqual([body, CONNECT_NOT_OPENED]); + for (const shown of [run, connect]) { + expect(shown).not.toContain("couldn't reach"); + expect(shown).not.toContain("{"); + expect(shown).not.toContain("Learning Container"); + } + // Part way through a turn, the Bot's work stands, and the backend is not said to have stopped. + expect([ + body, + laterRunFailure(new Error(`REST run request failed: ${body}`)), + ]).toEqual([body, TURN_REFUSED]); } + expect(RUN_NOT_STARTED).toContain("wasn't sent"); + expect(CONNECT_NOT_OPENED).not.toContain("wasn't sent"); + expect(TURN_REFUSED).not.toContain("wasn't sent"); + }); + + test("a 403 and a 409 the server refused for the person say the server's own sentence", () => { + // The run gate's refusals (server/src/admin/gate.ts `refusal`): an OpenBot problem with its + // detail, and `error` beside it, as CopilotKit's Intelligence agent throws them. + const forbidden = + "This Bot uses openai/gpt-6.1-terra, which isn't an allowed model. Ask an admin to allow it."; + expect( + stoppedReason( + `REST run request failed: {"type":"https://open.bot/errors/model-not-allowed","title":"That model isn't allowed.","status":403,"detail":"${forbidden}","code":"MODEL_NOT_ALLOWED","category":"permission","retryable":false,"requestId":"req_1","traceId":"t1","error":"${forbidden}"}`, + ), + ).toBe(forbidden); + const conflict = + "The AI connection for this conversation changed while the Bot was starting. Send your message again."; + expect( + stoppedReason( + `REST run request failed: {"type":"https://open.bot/errors/conflict","title":"Conflict.","status":409,"detail":"${conflict}","code":"CONFLICT","category":"conflict","retryable":true,"requestId":"req_2","traceId":"t2","error":"${conflict}"}`, + ), + ).toBe(conflict); }); test("a refused request says the Bot isn't shared any more only when the server says the Bot is gone", async () => { @@ -163,13 +222,26 @@ describe("the reason a turn ended", () => { ).toBe( "This Bot isn't shared with you any more. Its owner or an admin can share it again.", ); - // Still theirs, or nobody could say: the back end is what failed, as before. - for (const answer of [here, unknown]) - expect( - (await failedRunReason(refused, "pipeline-bot", answer)).message, - ).toBe( - "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", - ); + // Still theirs: the backend has no Bot to run from the setup it has, and says so. Nobody could + // say: the backend answered and refused, and nothing more is claimed. + expect((await failedRunReason(refused, "pipeline-bot", here)).message).toBe( + BOT_CANNOT_RUN_MESSAGE_NOT_SENT, + ); + expect( + (await failedRunReason(refused, "pipeline-bot", unknown)).message, + ).toBe(RUN_NOT_STARTED); + // A backend that didn't answer at all is still called what it is. + expect( + ( + await failedRunReason( + new Error("REST run request failed: Failed to fetch"), + "pipeline-bot", + here, + ) + ).message, + ).toBe( + "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", + ); // A Bot's own words are never second-guessed, whatever the server would say of the Bot. expect( (await failedRunReason("invalid x-api-key", "pipeline-bot", gone)) @@ -208,17 +280,51 @@ describe("the reason a turn ended", () => { ), ).toBe(capability); - // Anything else in a REST failure is still the backend failing, said in the person's terms: a - // raw body, a problem that is not OpenBot's own, and a problem about a server fault. + // Anything else the backend answered is said in the person's terms (a raw body, a problem that is + // not OpenBot's own, a server fault), and only what is no answer at all is "couldn't reach". for (const body of [ '{"error":"Failed to resolve Learning Container"}', '{"type":"about:blank","title":"Forbidden","status":403,"detail":"Failed to resolve Learning Container"}', '{"type":"https://open.bot/errors/internal-server-error","title":"Unexpected server error.","status":500,"detail":"Unexpected server error.","code":"INTERNAL_SERVER_ERROR"}', - "not json at all", ]) expect(stoppedReason(`REST run request failed: ${body}`)).toBe( - "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", + RUN_NOT_STARTED, ); + expect(stoppedReason("REST run request failed: not json at all")).toBe( + "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot.", + ); + }); + + /* + * FOUND ON OPENBOT CLOUD, 2026-12-03. Travis opened a conversation with a public Bot moved in from + * a colleague's OpenBot Desktop, and every run was answered 404 with exactly this body: the Bot had + * no instructions, so the runtime built nothing for it. The API still listed it, and read it back. + * He was told OpenBot couldn't reach its backend, and to quit and reopen it. + */ + test("a run of a Bot the backend can't build says the Bot can't run, not that the backend is out of reach", async () => { + const answered = new Error( + `REST run request failed: {"error":"Agent not found","message":"Agent 'picked-9d4618b6-8828-4a01-abfe-7c7d24247044' does not exist"}`, + ); + const stillHis = async () => false; + const reason = await failedRunReason( + answered, + "picked-9d4618b6-8828-4a01-abfe-7c7d24247044", + stillHis, + ); + expect(reason.message).toBe(BOT_CANNOT_RUN_MESSAGE_NOT_SENT); + expect(reason.message).not.toContain("couldn't reach"); + expect(reason.message).not.toContain("quit and reopen"); + expect(reason.message).not.toContain("picked-"); + // Joining its conversation sends nothing, so nothing is said about a message. + expect( + ( + await failedRunReason( + `REST connect request failed: {"error":"Agent not found","message":"Agent 'x' does not exist"}`, + "x", + stillHis, + ) + ).message, + ).toBe(BOT_CANNOT_RUN); }); test("says so plainly when nothing was reported, rather than inventing a cause", () => {