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,57 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useEffect, useState } from "react";
import type { BotGraphicView } from "@/src/types";
type Params = {
graphic_id: number;
};
/**
* Graphics read lately, by id, so a thread naming one twice asks once. An
* entry is read again after `FreshMs`, since a bot may have changed it.
*/
const loaded = new Map<number, { at: number; view: Promise<BotGraphicView | null> }>();
const FreshMs = 10_000;
function loadGraphic({ graphic_id }: Params) {
const cached = loaded.get(graphic_id);
if (cached && Date.now() - cached.at < FreshMs) return cached.view;
const view = fetchApi<{}, APIResponseObject<BotGraphicView>>(
`/api/admin/graphics/get-graphic?graphic_id=${graphic_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(graphic_id, { at: Date.now(), view });
return view;
}
/**
* A graphic a bot named (`[graphic:ID]`), for its card: its title, bot and
* version. Only the user it was made for reads it; anyone else gets null.
*/
export default function useBotGraphic({ graphic_id }: Params) {
const [view, setView] = useState<BotGraphicView | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let live = true;
loadGraphic({ graphic_id }).then((result) => {
if (!live) return;
setView(result);
setLoading(false);
});
return () => {
live = false;
};
}, [graphic_id]);
return { view, loading };
}