Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335import type { ChatMessage, ChatThread, ThemePaletteTokens } from "@typbase/typing";
import { useSearch } from "~/composables/search";import { resolveAppTheme } from "~/composables/theme";import { useTypst } from "~/composables/typst";import { useWorkspace } from "~/composables/workspace";import { activeThreads, configureChat, messageToolRuns, onChatEvent, renderedError, renderedMessage, repairMessage, resetChat, resolveProviderSettings, sendChat, stopChat, type ChatEngineDeps,} from "~/lib/ai/engine";import { checkChatMessage, renderChatMessage, setChatRequestStore, setChatWorkerFonts, setChatWorkerStyle,} from "~/lib/chatWorker";import { customFontPayloads } from "~/lib/customFonts";import { fontPackPayloads, installedFontPackIds } from "~/lib/fontPacks";import { pageContextBinding } from "~/lib/pageContext";import { sanitizeHtml } from "~/lib/plugins/sanitize";import { publishPrelude } from "~/lib/publishPrelude";
/** * Vue binding for the chat runtime. The engine itself is framework-free. This * composable supplies the workspace store, the main-thread engine (for the * dialect card), the search index (for grounding), and the chat worker * (progressive render + acceptance check). */
export interface ChatSeed { threadId: string; pageId: string | null; selection: string | null;}
interface ChatNavigation { openChat: (threadId: string) => void; openPage: (pageId: string) => void;}
const navigation: ChatNavigation = { openChat: () => {}, openPage: () => {} };
/** The shell registers how the chat reaches app navigation. */export function setChatNavigation(hooks: Partial<ChatNavigation>): void { Object.assign(navigation, hooks);}
let pendingSeed: ChatSeed | null = null;
/** A selection the composer should pick up when the pane mounts. */export function takeChatSeed(): ChatSeed | null { const seed = pendingSeed; pendingSeed = null;
return seed;}
function useChatState() { const { workspace } = useWorkspace(); const { search, ensure } = useSearch();
/** Bumped whenever the engine reports progress. */ const chatRevision = ref(0); let styleKey = ""; let fontKey = "";
onChatEvent(() => { chatRevision.value += 1; });
function currentStore() { const store = workspace.value; if (!store) throw new Error("No workspace is open");
return store; }
/** Settings-derived worker style. Only pushed when it changes. */ function applyWorkerStyle( store: ReturnType<typeof currentStore>, palette?: ThemePaletteTokens, ): void { const settings = store.getSettings(); const style = { font: settings.font, mathFont: settings.mathFont, codeFont: settings.codeFont, textSize: settings.textSize, ligatures: settings.typography.ligatures, kerning: settings.typography.kerning, documentStyle: settings.documentStyle, palette: palette ?? resolveAppTheme(settings).palette, }; const key = JSON.stringify(style); if (key !== styleKey) { styleKey = key; setChatWorkerStyle(style); }
// The chat renders the same document the editor does, so it needs the // workspace's uploaded faces and the device's language packs. Key the // bytes separately: installing a pack must not wait for a style change. const nextFontKey = JSON.stringify({ custom: settings.customFonts.map((font) => [font.family, font.hashes]), packs: installedFontPackIds.value, }); if (nextFontKey === fontKey) return;
fontKey = nextFontKey; void Promise.all([customFontPayloads(store), fontPackPayloads()]).then(([custom, packs]) => setChatWorkerFonts([...custom, ...packs]), ); }
function installDeps(store: ReturnType<typeof currentStore>): void { const deps: ChatEngineDeps = { store, typst: () => useTypst(), prelude: async (pageId) => publishPrelude(currentStore().getSettings(), { theme: "workspace", paged: false, context: pageContextBinding(currentStore(), pageId ?? null), }), palette: () => resolveAppTheme(currentStore().getSettings()).palette, render: async ({ source, prelude, palette, spaceId }) => { applyWorkerStyle(currentStore(), palette); const result = await renderChatMessage({ source, prelude, spaceId });
return { html: result.html ?? "", diagnostics: result.diagnostics }; }, check: async ({ source, prelude, palette, spaceId }) => { // The check can run before the first progressive render. The worker's // world needs the palette's code-block theme either way. applyWorkerStyle(currentStore(), palette); const result = await checkChatMessage({ source, prelude, spaceId });
return { diagnostics: result.diagnostics }; }, };
// Search is optional and only used once the palette or chat started it. const manager = search.value; if (manager) { deps.search = async (query: string) => { const { items } = await manager.query(query, 8);
return items.map((hit) => ({ pageId: hit.docId, title: hit.title, text: hit.snippet.map((segment) => segment.text).join(""), })); }; }
configureChat(deps); setChatRequestStore(store); }
/** * Sanitized render for a message. The engine's HTML never reaches `v-html` * raw: Typst can emit arbitrary elements, so the plugin allowlist runs here * too. Results are memoized per message revision. */ const sanitized = new Map<string, { raw: string; html: string }>(); function renderedHtml(messageId: string): string | undefined { void chatRevision.value; const raw = renderedMessage(messageId); if (!raw) return undefined;
const cached = sanitized.get(messageId); if (cached?.raw === raw) return cached.html;
const result = sanitizeHtml(raw).html; sanitized.set(messageId, { raw, html: result });
return result; }
watch( workspace, (store) => { if (!store) return; resetChat(); sanitized.clear(); installDeps(store); }, { immediate: true }, );
// A started search index becomes available to the grounding layer. watch(search, (manager) => { if (!manager || !workspace.value) return; installDeps(workspace.value); void ensure(workspace.value).catch(() => { // Search is best-effort. Chat works without it. }); });
const threads = useWorkspaceValue( workspace, ["chats"], (store) => { void chatRevision.value;
return store.listChats(); }, [], );
function thread(id: string): ChatThread | undefined { return workspace.value?.getChat(id); }
async function startThread( input: { title?: string; pageId?: string | null; providerId?: string | null; model?: string | null; } = {}, ): Promise<ChatThread> { const store = currentStore(); const settings = store.getAiSettings(); const provider = settings.providers.find((entry) => entry.id === settings.defaultProviderId);
return store.createChat({ title: input.title, pageId: input.pageId ?? null, providerId: input.providerId ?? provider?.id ?? null, model: input.model ?? null, }); }
/** Opens a new thread seeded with the current page and/or selection. */ async function seedChat(input: { pageId?: string | null; selection?: string | null; prompt?: string; }): Promise<ChatThread> { const created = await startThread({ pageId: input.pageId ?? null }); pendingSeed = { threadId: created.id, pageId: input.pageId ?? null, selection: input.selection ?? null, }; navigation.openChat(created.id);
return created; }
async function deleteThread(id: string): Promise<void> { stopChat(id); await workspace.value?.deleteChat(id); }
async function readMessages(threadId: string): Promise<ChatMessage[]> { return (await workspace.value?.readChatMessages(threadId)) ?? []; }
function send( threadId: string, text: string, options: { pageId?: string | null; selection?: string | null } = {}, ): Promise<void> { return sendChat({ threadId, text, ...options }); }
return { threads, thread, chatRevision, startThread, seedChat, deleteThread, readMessages, send, stop: stopChat, repair: repairMessage, isStreaming: (threadId: string) => { void chatRevision.value;
return activeThreads().includes(threadId); }, rendered: (messageId: string) => { void chatRevision.value;
return renderedHtml(messageId); }, renderedError: (messageId: string) => { void chatRevision.value;
return renderedError(messageId); }, tools: (messageId: string) => { void chatRevision.value;
return messageToolRuns(messageId); }, providers: useWorkspaceValue( workspace, ["settings"], (store) => store.getAiSettings().providers, [], ), defaultProvider: useWorkspaceValue( workspace, ["settings"], (store) => { const settings = store.getAiSettings();
try { return resolveProviderSettings(settings); } catch { return null; } }, null, ), };}
export const useChat = createSharedComposable(useChatState);