Files
loki/widget/chat-loader.ts
CatoandClaude 58ee6e8c78 feat(widget): the conversation drawn by the shared chat (chatkit), on Loki's own widget first (#1162)
The widget's chat was the fleet's own hand-rolled chat; with
data-fc-chat="kit" it is now drawn by @bitbaum/chatkit, the thread and
composer Loki's own chat renders, over the same conversation model.

- widget/chat/: a separate lazy chunk (public/widget-chat.js, ~24 KB
  gzipped, Preact standing in for React), fetched on first open, carrying
  the tag's nonce. chatkit's CSS is rewritten for the shadow root (:root ->
  :host, rem -> px) and coloured from the boot theme.
- widget/conversation-kit.ts maps the model's snapshot to what chatkit
  draws; Fix this, the changes, the confirmation card, the About chips and
  Continue in Loki go into chatkit's slots as the widget's own nodes.
- A chunk that cannot load leaves the panel's own view: no dead end.
- /widget-chat.js is public in the auth proxy, like /widget.js.
- Tests: widget-kit-browser (34 checks: ask, card, screenshot, fallback,
  phone width, host hotkeys, weight budget), widget-chat-css, and
  widget-self-contained now guards the chunk/panel seam.


Claude-Session: https://claude.ai/code/session_01BWXjqiHm8jFta4FXuc7Tck

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 05:13:25 -07:00

38 lines
1.5 KiB
TypeScript

/**
* Loads the chat chunk (public/widget-chat.js, widget/chat/) — the shared chat
* the panel draws its conversation with — once, on demand.
*
* Never a dead end: if the chunk cannot load (blocked by a site's CSP, offline,
* slow), the promise resolves to null and the panel keeps the conversation it
* draws itself (conversation.ts). The script tag carries the widget tag's
* nonce, so a site whose CSP allows the widget by nonce allows this too.
*/
import { KIT_GLOBAL, type KitModule } from "./chat/contract";
const LOAD_TIMEOUT_MS = 8000;
let loading: Promise<KitModule | null> | null = null;
export function loadChat(apiBase: string, nonce?: string): Promise<KitModule | null> {
if (loading) return loading;
loading = new Promise((resolve) => {
const w = window as unknown as Record<string, unknown>;
const ready = () => (w[KIT_GLOBAL] as KitModule | undefined) ?? null;
if (ready()) return resolve(ready());
const done = (mod: KitModule | null) => {
clearTimeout(timer);
window.removeEventListener(KIT_GLOBAL, onReady);
resolve(mod);
};
const onReady = () => done(ready());
const timer = setTimeout(() => done(ready()), LOAD_TIMEOUT_MS);
window.addEventListener(KIT_GLOBAL, onReady);
const s = document.createElement("script");
s.src = `${apiBase}/widget-chat.js`;
s.async = true;
if (nonce) s.nonce = nonce;
s.onerror = () => done(null);
document.head.appendChild(s);
});
return loading;
}