Add bot graphics

Bots can now show a concept as a visual: create_graphic (with
update_graphic, read_graphic and list_graphics, on every run, no computer
needed) stores one HTML document in bot_graphics, per user like the
conversation, and the chat renders its [graphic:ID] ref as an inline card
sized to fit, with a large view and a page of its own (no rail).

Graphic HTML is treated as hostile: it is only served at /graphics/<id>
with a CSP sandbox allowing scripts under an origin of its own and no
network, loading only the vendored Chart.js and Mermaid from
/graphics-lib/. The document carries the app's theme vars and scrollbars,
reports its height to the thread, and a frame that navigates away is
closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-27 08:11:15 +01:00
co-authored by Claude Opus 5.5
parent 51fd4d5538
commit bea656ade8
65 changed files with 1959 additions and 21 deletions
@@ -0,0 +1,23 @@
import fs from "fs";
import path from "path";
import parseThemeVars, { type ThemeVars } from "@/src/utils/parse-theme-vars";
let cached: ThemeVars | null = null;
/**
* The app's theme colours and fonts for graphics, read once from
* `src/styles/main.css` so a theme change there reaches them too.
*/
export default function grabGraphicThemeVars(): ThemeVars {
if (cached) return cached;
try {
cached = parseThemeVars({
css: fs.readFileSync(path.join(process.cwd(), "src/styles/main.css"), "utf-8"),
});
} catch {
cached = { light: {}, dark: {}, fonts: {} };
}
return cached;
}
@@ -0,0 +1,82 @@
import path from "node:path";
import { GraphicsLibPrefix, GraphicsLibs, GraphicsPrefix } from "@/src/dict/graphics-dict";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabBotGraphic from "@/src/functions/backend/db/bot-graphics/grab-bot-graphic";
import graphicDocument from "@/src/utils/graphic-document";
import graphicHeaders from "@/src/utils/graphic-headers";
import isSecureRequest from "@/src/utils/is-secure-request";
import grabGraphicThemeVars from "./grab-graphic-theme-vars";
type Params = {
req: Request;
url: URL;
};
/**
* Serves bot graphics and the libraries they may load:
*
* - `/graphics/<id>[?theme=dark]`: the graphic, for the user it was made
* for only (anyone else, signed in or not, gets the same 404), themed
* and sandboxed (`graphicHeaders`).
* - `/graphics-lib/<file>`: a library from `GraphicsLibs`, public (a
* sandboxed graphic sends no cookie of the app's) and cached for a day.
*
* Null for any other path.
*/
export default async function handleGraphicsRequest({ req, url }: Params): Promise<Response | null> {
if (url.pathname.startsWith(`${GraphicsLibPrefix}/`)) {
return await serveLib({ file: url.pathname.slice(GraphicsLibPrefix.length + 1) });
}
if (!url.pathname.startsWith(`${GraphicsPrefix}/`)) return null;
const id = url.pathname.slice(GraphicsPrefix.length + 1).replace(/\/$/, "");
if (req.method != "GET" || !/^\d+$/.test(id)) return notFound();
const { user } = await userAuth({ req });
if (!user?.id) return notFound();
const graphic = await grabBotGraphic({ graphic_id: id, user_id: user.id });
if (!graphic?.html) return notFound();
const origin = `${isSecureRequest({ req }) ? "https" : "http"}://${req.headers.get("host") || url.host}`;
return new Response(
graphicDocument({
html: graphic.html,
title: graphic.title || `Graphic ${graphic.id}`,
dark: url.searchParams.get("theme") == "dark",
vars: grabGraphicThemeVars(),
}),
{ headers: graphicHeaders({ origin }) },
);
}
async function serveLib({ file }: { file: string }) {
const lib = GraphicsLibs.find((it) => it.file == file);
if (!lib) return notFound();
const source = Bun.file(path.join(process.cwd(), lib.source));
if (!(await source.exists())) return notFound();
const response = new Response(source, {
headers: {
"Content-Type": "text/javascript; charset=utf-8",
"Cache-Control": "public, max-age=86400",
"X-Content-Type-Options": "nosniff",
},
});
response.headers.delete("content-disposition");
return response;
}
function notFound() {
return new Response("Not Found", { status: 404, headers: { "Cache-Control": "no-store" } });
}