Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631import type { PluginAction, PluginActionResult, PluginCapability, PluginContext, PluginInstance, PluginManifest, PluginPatch, PluginPatchOp, PluginState, PluginSurface, PluginSurfaceKind,} from "@typbase/typing";
import { createPluginBundle, parsePluginBundle } from "@typbase/plugin-sdk";import { publishPlugin, resolvePlugin } from "@typbase/spaces";import { PLUGIN_API } from "@typbase/typing";
import type { PluginSurfacePackage } from "~/lib/plugins/protocol";
import { useChat } from "~/composables/chat";import { resolveAppTheme } from "~/composables/theme";import { pushToast } from "~/composables/toasts";import { useTypst } from "~/composables/typst";import { useWorkspace } from "~/composables/workspace";import { completeForPlugin } from "~/lib/ai/engine";import { engineAvailable } from "~/lib/engineHealth";import { sectionsOf } from "~/lib/engineSyntax";import { todayISO } from "~/lib/format";import { specString } from "~/lib/packages";import { installPluginBundle } from "~/lib/plugins/bundle";import { loadBundledCatalog, loadLocalCatalog, type CatalogPlugin, UI_LIBRARY_PATH, uiLibrarySource,} from "~/lib/plugins/catalog";import { compilePluginSurface, pluginEngine, resetPluginEngine } from "~/lib/plugins/engine";import { importPluginFolder } from "~/lib/plugins/folderImport";import { parseManifest, pluginSlug, validatePatch } from "~/lib/plugins/manifest";import { bumpPluginsRevision, pluginsRevision, registerPluginSources,} from "~/lib/plugins/registry";import { sanitizeHtml } from "~/lib/plugins/sanitize";import { refreshSections, toSections } from "~/lib/sections";import { resolveRequestPayloads } from "~/lib/typstRequests";
export interface PluginError { at: number; pluginId: string; instanceId?: string; surface?: PluginSurfaceKind; message: string; /** Virtual path when a compile diagnostic points into a plugin file. */ file?: string; /** 1-based line in `file`. */ line?: number;}
export type PluginLogKind = "info" | "error" | "action" | "render" | "patch";
export interface PluginLogEntry { at: number; kind: PluginLogKind; pluginId?: string; instanceId?: string; message: string;}
/** What a surface shows: sanitized HTML, plugin styles, or an error. */export interface PluginSurfaceState { status: "ok" | "error"; html: string; styles: string[]; error?: string;}
/** Device-local floating-window geometry, keyed by instance id. */export interface PluginWindowPlacement { open: boolean; x: number; y: number; width: number; height: number; z: number;}
interface NavigationHooks { openPage: (pageId: string) => void; openPlugin: (instanceId: string) => void;}
const navigation: NavigationHooks = { openPage: () => {}, openPlugin: () => {},};
/** The shell registers how plugin actions reach app navigation. */export function setPluginNavigation(hooks: Partial<NavigationHooks>): void { Object.assign(navigation, hooks);}
let pluginCurrentPageId: string | null = null;
/** The shell reports the open page so plugin context can include it. */export function setPluginCurrentPage(id: string | null): void { if (pluginCurrentPageId === id) return; pluginCurrentPageId = id; // Surfaces read `ctx.page`. A page switch has to rebuild them or a window // keeps offering actions against the page that was open when it rendered. bumpPluginsRevision();}
function parseConfig(instance: PluginInstance): Record<string, unknown> { try { const value = JSON.parse(instance.config) as unknown; return value && typeof value === "object" ? (value as Record<string, unknown>) : {}; } catch { return {}; }}
export const DEFAULT_WINDOW_SIZE = { width: 620, height: 480 };
export function usePluginHost() { const { workspace, backend, localState, dataRevision, pluginFilesRevision, atproto } = useWorkspace(); const { t, locale } = useI18n(); const { confirm } = useConfirm(); const openExternalLink = useExternalLink(); // Plugin AI actions go through the chat runtime. Instantiate it so the // engine deps exist even when no chat pane is open (for example /debug). useChat();
const catalog = shallowRef<CatalogPlugin[]>(loadBundledCatalog()); const errors = ref<PluginError[]>([]); const logs = ref<PluginLogEntry[]>([]); const renderStates = new Map<string, PluginSurfaceState>(); const listeners = new Map<string, Set<(state: PluginSurfaceState) => void>>(); const docUnsubscribes = new Map<string, () => void>(); const renderQueues = new Map<string, Promise<void>>(); /** One in-flight `ai.stream` per plugin instance. A new one aborts the old. */ const aiStreams = new Map<string, AbortController>(); const views = shallowRef<Record<string, Record<string, unknown>>>({}); const windows = ref<Record<string, PluginWindowPlacement>>({}); let viewsLoaded = false; let windowsLoaded = false; let fallbackLogged = false; let windowZ = 1; let windowSaveTimer: ReturnType<typeof setTimeout> | undefined;
const keyOf = (instanceId: string, kind: PluginSurfaceKind): string => `${instanceId}:${kind}`;
/** Diagnostics for the plugin studio. Newest first, capped. */ function log(entry: Omit<PluginLogEntry, "at">): void { logs.value = [{ at: Date.now(), ...entry }, ...logs.value].slice(0, 200); }
function clearLogs(): void { logs.value = []; }
/** * postMessage uses structured clone, which rejects Vue reactive proxies. * Every payload crossing to the plugin worker goes through this. */ function plain<T>(value: T): T { return JSON.parse(JSON.stringify(value)) as T; }
function manifestOf(pluginId: string): PluginManifest | undefined { const entry = catalog.value.find((candidate) => candidate.manifest.id === pluginId); if (entry) return entry.manifest;
const record = workspace.value?.getPluginInstall(pluginId); if (!record) return undefined; try { return JSON.parse(record.manifest) as PluginManifest; } catch { return undefined; } }
/** Local copies win: forking a bundled plugin is how it becomes editable. */ async function refreshCatalog(): Promise<void> { const bundled = loadBundledCatalog(); const local = await loadLocalCatalog(backend.value); const localIds = new Set(local.map((entry) => entry.manifest.id)); catalog.value = [...local, ...bundled.filter((entry) => !localIds.has(entry.manifest.id))];
// Notes import plugin modules through the request channel. Keep the // served copy in sync with what surfaces compile against. registerPluginSources([ { path: UI_LIBRARY_PATH, text: uiLibrarySource }, ...catalog.value.flatMap((entry) => entry.sources), ]); bumpPluginsRevision();
await dropLegacyInstalls(); await adoptSourceChanges();
log({ kind: "info", message: `catalog refreshed: ${catalog.value.length} plugin(s), ${local.length} local`, }); }
/** * Brings an install record up to date when the plugin's sources moved on. */ async function adoptSourceChanges(): Promise<void> { const store = workspace.value; if (!store) return;
for (const record of store.listPluginInstalls()) { const entry = catalog.value.find((candidate) => candidate.manifest.id === record.id); if (!entry) continue;
const changed = entry.manifest.version !== record.version; // The manifest is cached in the install record so the UI works before the // sources load, so a capability or surface edit shows up as a change too. const manifestChanged = JSON.stringify(entry.manifest) !== record.manifest; if (!changed && !manifestChanged) continue;
store.setPluginInstall({ ...record, version: entry.manifest.version, manifest: JSON.stringify(entry.manifest), });
log({ kind: "info", pluginId: record.id, message: `${record.version || "unknown"} -> ${entry.manifest.version}`, }); } }
/** * v1 installs (one instance per surface, `api: typbase.host.v1`) are not * readable by this runtime. Removing them also removes their orphaned * instance docs. */ async function dropLegacyInstalls(): Promise<void> { const store = workspace.value; if (!store) return;
for (const record of store.listPluginInstalls()) { if (!catalog.value.some((entry) => entry.manifest.id === record.id)) continue; let api = ""; try { api = (JSON.parse(record.manifest) as { api?: string }).api ?? ""; } catch { api = ""; } if (api && api !== PLUGIN_API) { log({ kind: "info", message: `removed v1 install ${record.id}` }); await store.uninstallPlugin(record.id); } } }
watch(backend, () => void refreshCatalog(), { immediate: true });
// External edits under `plugins/` (an editor outside the app) reload the // catalog. Saves from the studio call refreshCatalog directly. watch(pluginFilesRevision, () => void refreshCatalog());
// Plugin source or data changes rebuild every mounted surface. watch(pluginsRevision, () => { for (const key of [...listeners.keys()]) { const separator = key.lastIndexOf(":"); void renderInstance(key.slice(0, separator), key.slice(separator + 1) as PluginSurfaceKind); } });
const installs = useWorkspaceValue( workspace, ["plugins"], (store) => store.listPluginInstalls(), [], );
const instances = useWorkspaceValue( workspace, ["instances"], (store) => store.listPluginInstances(), [], );
function surfacesOf(instanceId: string): PluginSurface[] { const instance = workspace.value?.getPluginInstance(instanceId); if (!instance) return [];
return manifestOf(instance.pluginId)?.surfaces ?? []; }
function surfaceOf(instanceId: string, kind: PluginSurfaceKind): PluginSurface | undefined { return surfacesOf(instanceId).find((surface) => surface.kind === kind); }
/** Instances of enabled plugins that declare a surface of this kind. */ function instancesWithSurface(kind: PluginSurfaceKind): PluginInstance[] { return instances.value.filter((instance) => { const enabled = installs.value.find((record) => record.id === instance.pluginId)?.enabled; return enabled && surfacesOf(instance.id).some((surface) => surface.kind === kind); }); }
/** Manifest-declared host components for one instance. */ function hostComponentsOf(instanceId: string): string[] { const instance = workspace.value?.getPluginInstance(instanceId); if (!instance) return [];
return manifestOf(instance.pluginId)?.hostComponents ?? []; }
function pushError(error: Omit<PluginError, "at">): void { errors.value = [{ at: Date.now(), ...error }, ...errors.value].slice(0, 50); log({ kind: "error", instanceId: error.instanceId, pluginId: error.pluginId, message: error.message, }); console.warn(`[plugins] ${error.message}`); }
function clearErrors(pluginId?: string): void { errors.value = pluginId ? errors.value.filter((error) => error.pluginId !== pluginId) : []; }
function errorsFor(pluginId: string): PluginError[] { return errors.value.filter((error) => error.pluginId === pluginId); }
interface InstallOptions { source?: string; origin?: string; release?: string; sha256?: string; }
async function install(pluginId: string, options: InstallOptions = {}): Promise<void> { const store = workspace.value; const entry = catalog.value.find((candidate) => candidate.manifest.id === pluginId); if (!store || !entry || store.getPluginInstall(pluginId)) return;
store.setPluginInstall({ id: entry.manifest.id, version: entry.manifest.version, enabled: true, source: options.source ?? entry.source, installedAt: Date.now(), manifest: JSON.stringify(entry.manifest), ...(options.origin ? { origin: options.origin } : {}), ...(options.release ? { release: options.release } : {}), ...(options.sha256 ? { sha256: options.sha256 } : {}), });
await store.createPluginInstance({ pluginId: entry.manifest.id, title: entry.manifest.name, icon: entry.manifest.icon, }); }
/** Adds an independent instance, with its own data doc, for a plugin. */ async function addInstance(pluginId: string): Promise<void> { const store = workspace.value; const manifest = manifestOf(pluginId); if (!store || !manifest) return;
const count = store.listPluginInstances().filter((i) => i.pluginId === pluginId).length;
await store.createPluginInstance({ pluginId: manifest.id, title: count === 0 ? manifest.name : `${manifest.name} ${count + 1}`, icon: manifest.icon, }); }
async function uninstall(pluginId: string): Promise<void> { const store = workspace.value; if (!store) return;
for (const instance of store.listPluginInstances()) { if (instance.pluginId === pluginId) releaseInstance(instance.id); }
await store.uninstallPlugin(pluginId); }
/** Copies a picked folder into workspace storage, then installs it. */ async function installFromFolder(): Promise<void> { const active = backend.value; if (!active) return;
try { const manifest = await importPluginFolder(active); if (!manifest) return; await refreshCatalog(); await install(manifest.id); } catch (error) { pushError({ pluginId: "import", message: error instanceof Error ? error.message : String(error), }); } }
/** * Resolves a plugin listing from the publisher's PDS, verifies the artifact, * and installs the release as a local plugin. A catalog is not involved. */ async function installFromUri(uri: string): Promise<void> { const store = workspace.value; const active = backend.value; if (!store || !active) return;
try { const resolved = await resolvePlugin(uri); const manifest = parseManifest(resolved.manifest); if (manifest.id !== uri) { throw new Error("plugin manifest id does not match the listing URI"); } if (resolved.release.version !== manifest.version) { throw new Error("plugin release version does not match its manifest"); } if (resolved.release.api !== manifest.api) { throw new Error("plugin release API does not match its manifest"); }
const bundle = parsePluginBundle(resolved.artifact); const bundledManifest = parseManifest(bundle.manifest); if (JSON.stringify(bundledManifest) !== JSON.stringify(manifest)) { throw new Error("plugin bundle manifest does not match its release manifest"); } if (!bundle.files.some((file) => file.path === manifest.entry)) { throw new Error(`plugin bundle is missing its entry file "${manifest.entry}"`); }
const capabilities = manifest.capabilities.length ? manifest.capabilities.join(", ") : "none"; const confirmed = await confirm({ title: t("plugins.installConfirmTitle", { name: manifest.name }), description: t("plugins.installConfirm", { version: manifest.version, uri, capabilities, }), confirmLabel: t("plugins.install"), danger: false, }); if (!confirmed) { return; }
await installPluginBundle(active, manifest, bundle.files); await refreshCatalog();
const existing = store.getPluginInstall(manifest.id); if (existing) { store.setPluginInstall({ ...existing, version: manifest.version, source: "registry", manifest: JSON.stringify(manifest), origin: uri, release: resolved.releaseUri, sha256: resolved.release.sha256, }); if (!store.listPluginInstances().some((instance) => instance.pluginId === manifest.id)) { await store.createPluginInstance({ pluginId: manifest.id, title: manifest.name, icon: manifest.icon, }); } } else { await install(manifest.id, { source: "registry", origin: uri, release: resolved.releaseUri, sha256: resolved.release.sha256, }); } bumpPluginsRevision(); } catch (error) { pushError({ pluginId: "registry", message: error instanceof Error ? error.message : String(error), }); throw error; } }
/** * Publishes one local plugin revision to the signed-in account's public * repo. Publishing under the current DID creates a normal registry listing. * The local authoring copy keeps its own local id. */ async function publishToAtmosphere(pluginId: string): Promise<void> { const entry = catalog.value.find((candidate) => candidate.manifest.id === pluginId); const session = atproto.value?.session; if (!entry || !session) { throw new Error("Sign in before publishing a plugin."); } if (!(await atproto.value?.hasPluginPublishingScope())) { throw new Error("Reconnect your account to grant plugin publishing access."); } if (entry.manifest.id.startsWith("at://") && !entry.manifest.id.includes(session.did)) { throw new Error("This plugin belongs to another publisher. Fork it before publishing."); }
const slug = pluginSlug(entry.manifest.id); const listingUri = `at://${session.did}/at.typbase.plugin/${slug}`; const manifest: PluginManifest = { ...entry.manifest, id: listingUri }; const prefix = `/typbase/plugin/${entry.slug}/`; const files = [ ...entry.sources.map((source) => ({ path: source.path.startsWith(prefix) ? source.path.slice(prefix.length) : source.path, text: source.text, })), ...entry.styles.map((style) => ({ path: style.name, text: style.text })), ]; if (!files.some((file) => file.path === manifest.entry)) { throw new Error(`plugin source is missing its entry file "${manifest.entry}"`); } const artifact = createPluginBundle(manifest, files); const published = await publishPlugin(session, session.did, { slug, manifest, artifact, }); pushToast({ titleKey: "plugins.published", descriptionKey: "plugins.publishedHint", params: { uri: published.listingUri }, duration: 4500, }); }
async function setEnabled(pluginId: string, enabled: boolean): Promise<void> { const store = workspace.value; const record = store?.getPluginInstall(pluginId); if (!store || !record) return;
store.setPluginInstall({ ...record, enabled }); }
async function removeInstance(instanceId: string): Promise<void> { const store = workspace.value; if (!store) return;
releaseInstance(instanceId); closeWindow(instanceId); await store.deletePluginInstance(instanceId); }
/** Renames one instance. The sidebar row, window title, and manager show it. */ async function renameInstance(instanceId: string, title: string): Promise<void> { const store = workspace.value; const trimmed = title.trim(); if (!store || !trimmed) return;
await store.updatePluginInstance(instanceId, { title: trimmed }); rerenderInstance(instanceId); }
function releaseInstance(instanceId: string): void { for (const key of [...listeners.keys()]) { if (key.startsWith(`${instanceId}:`)) { listeners.delete(key); renderStates.delete(key); } } docUnsubscribes.get(instanceId)?.(); docUnsubscribes.delete(instanceId); }
async function loadViews(): Promise<void> { const local = localState.value; if (!local || viewsLoaded) return; viewsLoaded = true;
try { const stored = (await local.get<Record<string, Record<string, unknown>>>("pluginViews")) ?? {}; // In-memory patches win: surfaces can render before device state loads. views.value = { ...stored, ...views.value }; } catch { views.value = {}; }
// Surfaces may have rendered before device state was loaded. for (const key of [...listeners.keys()]) { const separator = key.lastIndexOf(":"); void renderInstance(key.slice(0, separator), key.slice(separator + 1) as PluginSurfaceKind); } }
async function loadWindows(): Promise<void> { const local = localState.value; if (!local || windowsLoaded) return; windowsLoaded = true;
try { const stored = (await local.get<Record<string, PluginWindowPlacement>>("pluginWindows")) ?? {}; // A window opened before local state loaded must keep its placement. windows.value = { ...stored, ...windows.value }; } catch { windows.value = {}; } }
watch(localState, () => { void loadViews(); void loadWindows(); }); void loadViews(); void loadWindows();
function persistWindows(): void { const local = localState.value; if (!local) return; if (windowSaveTimer) clearTimeout(windowSaveTimer); windowSaveTimer = setTimeout(() => { windowSaveTimer = undefined; void local.set("pluginWindows", windows.value); }, 400); }
function applyView(instanceId: string, patch: Record<string, unknown>): void { views.value = { ...views.value, [instanceId]: { ...(views.value[instanceId] ?? {}), ...patch }, };
const local = localState.value; if (local) void local.set("pluginViews", views.value); }
function viewOf(instanceId: string): Record<string, unknown> { return views.value[instanceId] ?? {}; }
function resetView(instanceId: string): void { views.value = { ...views.value, [instanceId]: {} };
const local = localState.value; if (local) void local.set("pluginViews", views.value); }
function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); }
function windowOf(instanceId: string): PluginWindowPlacement { const existing = windows.value[instanceId]; if (existing) return existing;
const openCount = Object.values(windows.value).filter((placement) => placement.open).length;
return { open: false, x: 96 + (openCount % 6) * 32, y: 80 + (openCount % 6) * 32, width: DEFAULT_WINDOW_SIZE.width, height: DEFAULT_WINDOW_SIZE.height, z: 1, }; }
function writeWindow(instanceId: string, placement: PluginWindowPlacement): void { windows.value = { ...windows.value, [instanceId]: placement }; persistWindows(); }
function openWindow(instanceId: string): void { const current = windowOf(instanceId); const viewportWidth = typeof window === "undefined" ? 1280 : window.innerWidth; const viewportHeight = typeof window === "undefined" ? 800 : window.innerHeight; const width = Math.min(current.width, Math.max(320, viewportWidth - 16)); const height = Math.min(current.height, Math.max(240, viewportHeight - 96));
writeWindow(instanceId, { ...current, open: true, width, height, x: clamp(current.x, 8, Math.max(8, viewportWidth - width - 8)), y: clamp(current.y, 8, Math.max(8, viewportHeight - height - 8)), z: ++windowZ, }); }
function closeWindow(instanceId: string): void { const current = windows.value[instanceId]; if (!current) return; writeWindow(instanceId, { ...current, open: false }); }
function focusWindow(instanceId: string): void { const current = windowOf(instanceId); if (current.z === windowZ) return; writeWindow(instanceId, { ...current, z: ++windowZ }); }
function moveWindow(instanceId: string, x: number, y: number): void { const current = windowOf(instanceId); const viewportWidth = typeof window === "undefined" ? 1280 : window.innerWidth; const viewportHeight = typeof window === "undefined" ? 800 : window.innerHeight;
writeWindow(instanceId, { ...current, x: clamp(x, -current.width + 80, viewportWidth - 80), y: clamp(y, 0, viewportHeight - 48), }); }
function resizeWindow(instanceId: string, width: number, height: number): void { const current = windowOf(instanceId); writeWindow(instanceId, { ...current, width: clamp(width, 320, 1600), height: clamp(height, 200, 1400), }); }
function subscribe( instanceId: string, kind: PluginSurfaceKind, listener: (state: PluginSurfaceState) => void, ): () => void { const key = keyOf(instanceId, kind); let set = listeners.get(key); if (!set) { set = new Set(); listeners.set(key, set); } set.add(listener);
if (!docUnsubscribes.has(instanceId)) { const store = workspace.value; if (store) { void store .onPluginDocChange(instanceId, () => { for (const surface of surfacesOf(instanceId)) { if (listeners.has(keyOf(instanceId, surface.kind))) { void renderInstance(instanceId, surface.kind); } } }) .then((off) => { if (listeners.has(keyOf(instanceId, kind))) docUnsubscribes.set(instanceId, off); else off(); }); } }
const cached = renderStates.get(key); if (cached !== undefined) listener(cached); else void renderInstance(instanceId, kind);
return () => { const current = listeners.get(key); if (current) { current.delete(listener); if (current.size === 0) { listeners.delete(key); renderStates.delete(key); } } if (![...listeners.keys()].some((entry) => entry.startsWith(`${instanceId}:`))) { docUnsubscribes.get(instanceId)?.(); docUnsubscribes.delete(instanceId); } }; }
/** Queues a render so actions and doc echoes never compile concurrently. */ function renderInstance( instanceId: string, kind: PluginSurfaceKind, action?: PluginAction, result?: PluginActionResult | null, ): Promise<void> { const key = keyOf(instanceId, kind); const previous = renderQueues.get(key) ?? Promise.resolve(); const next = previous .catch(() => { // a failed render must not stall the queue }) .then(() => doRender(instanceId, kind, action, result)); renderQueues.set(key, next);
return next; }
/** * Re-renders the instance's mounted surfaces. Unmounted ones render on * mount, and their stale cache entries were dropped by the patch. */ function rerenderInstance(instanceId: string): void { for (const slot of surfacesOf(instanceId)) { if (listeners.has(keyOf(instanceId, slot.kind))) { void renderInstance(instanceId, slot.kind); } } }
async function doRender( instanceId: string, kind: PluginSurfaceKind, action?: PluginAction, result?: PluginActionResult | null, ): Promise<void> { const store = workspace.value; if (!store) return;
const instance = store.getPluginInstance(instanceId); if (!instance) { releaseInstance(instanceId); return; }
const entry = catalog.value.find((candidate) => candidate.manifest.id === instance.pluginId); const record = store.getPluginInstall(instance.pluginId); if (!entry || !record) { pushError({ instanceId, pluginId: instance.pluginId, surface: kind, message: "plugin sources missing", }); return; }
const manifest = entry.manifest; const surface = manifest.surfaces.find((candidate) => candidate.kind === kind); if (!surface) return;
const key = keyOf(instanceId, kind); const styles = entry.styles.map((style) => style.text); const settings = store.getSettings(); const hasData = manifest.capabilities.includes("plugin.data"); const state: PluginState = hasData ? await store.readPluginState(instanceId) : {}; const canReadPages = manifest.capabilities.includes("pages.read");
const ctx: PluginContext = { plugin: { id: manifest.id, slug: entry.slug, name: manifest.name, version: manifest.version, }, instance: { id: instance.id, title: instance.title, }, surface: { kind: surface.kind, title: surface.title }, locale: locale.value, now: new Date().toISOString(), today: todayISO(), config: parseConfig(instance), state, view: views.value[instanceId] ?? {}, action: action ? { ...action, fields: action.fields ?? {} } : null, result: result ?? null, page: canReadPages && pluginCurrentPageId ? { id: pluginCurrentPageId } : null, data: canReadPages ? { pages: store.listPages(), categories: store.listCategories(), daily: store.listPages().filter((page) => page.path.startsWith("daily/")), } : null, theme: resolveAppTheme(settings).palette as unknown as Record<string, string>, };
try { const started = performance.now(); const sources = plain([{ path: UI_LIBRARY_PATH, text: uiLibrarySource }, ...entry.sources]); const files: { path: string; bytes: Uint8Array }[] = []; const packages: PluginSurfacePackage[] = []; const style = plain({ font: settings.font, mathFont: settings.mathFont, codeFont: settings.codeFont, textSize: settings.textSize, palette: resolveAppTheme(settings).palette, });
let compiled = await compilePluginSurface({ spaceId: store.workspaceId, slug: entry.slug, entry: manifest.entry, fn: surface.fn, sources, styles, files, packages, ctx: plain(ctx), style, });
// Answer `#typbase.query`/`#typbase.embed` requests like notes do, then // recompile with the resolved sources and files. for (let pass = 0; pass < 8 && compiled.requests.length > 0; pass++) { const payloads = await resolveRequestPayloads( compiled.requests, store, pluginCurrentPageId, { pluginId: manifest.id, allowPages: canReadPages, }, ); let added = false; for (const payload of payloads) { if (payload.type === "source") { if (!sources.some((source) => source.path === payload.path)) { sources.push({ path: payload.path, text: payload.text }); added = true; } } else if (payload.type === "package") { if (!packages.some((pkg) => specString(pkg.spec) === specString(payload.spec))) { packages.push({ spec: payload.spec, bytes: payload.bytes }); added = true; } } else if (!files.some((file) => file.path === payload.path)) { files.push({ path: payload.path, bytes: payload.bytes }); added = true; } } if (!added) break;
compiled = await compilePluginSurface({ spaceId: store.workspaceId, slug: entry.slug, entry: manifest.entry, fn: surface.fn, sources, styles, files, packages, ctx: plain(ctx), style, }); }
const duration = Math.round(performance.now() - started);
log({ kind: "render", instanceId, pluginId: manifest.id, message: `${surface.fn} via ${compiled.engine ?? "?"} in ${duration}ms (${compiled.html.length}b)`, });
if (compiled.engine === "local" && compiled.fallbackReason && !fallbackLogged) { fallbackLogged = true; log({ kind: "info", instanceId, pluginId: manifest.id, message: `plugin worker unavailable, compiling on the main thread: ${compiled.fallbackReason}`, }); }
const diagnostics = compiled.diagnostics as Array<{ severity?: string; message?: string; file?: string; line?: number; }>; const compileErrors = diagnostics.filter((diagnostic) => diagnostic.severity === "error"); for (const diagnostic of compileErrors) { pushError({ instanceId, pluginId: manifest.id, surface: kind, message: diagnostic.message ?? "compile error", file: diagnostic.file, line: diagnostic.line, }); }
if (compiled.requests.length) { pushError({ instanceId, pluginId: manifest.id, surface: kind, message: `unresolved plugin imports: ${compiled.requests.map((request) => String(request.value)).join(", ")}`, }); }
// A broken plugin shows its error instead of the recovery render. The // editor's partial-input recovery has no place on a plugin surface. if (compileErrors.length) { const first = compileErrors[0]!; const site = first.file ? ` (${first.file}:${first.line ?? 1})` : ""; publish(key, { status: "error", html: "", styles, error: `${first.message ?? "compile error"}${site}`, }); return; }
const sanitized = sanitizeHtml(compiled.html); for (const error of sanitized.errors) { pushError({ instanceId, pluginId: manifest.id, surface: kind, message: error, }); }
let patched = false; let statePatched = false; if (sanitized.patch) { const validated = validatePatch(sanitized.patch as PluginPatch, manifest); for (const error of validated.errors) { pushError({ instanceId, pluginId: manifest.id, surface: kind, message: error, }); } if (validated.patch.state?.length) { // Logged after the capability check, so the log does not claim a patch // that was refused. if (await patchData(instanceId, validated.patch.state)) { log({ kind: "patch", instanceId, pluginId: manifest.id, message: validated.patch.state .map((op) => `${op.op}:${op.collection}`) .join(", ") .slice(0, 200), }); patched = true; statePatched = true; // Notes embedding this plugin's data recompile. Other surfaces // re-render through the revision watcher. bumpPluginsRevision(); } } if (validated.patch.view && Object.keys(validated.patch.view).length) { log({ kind: "patch", instanceId, pluginId: manifest.id, message: `view ${JSON.stringify(validated.patch.view).slice(0, 160)}`, }); applyView(instanceId, validated.patch.view); patched = true; } }
if (patched) { // This render predates the patch. Drop the cached HTML for every // surface of the instance so a surface that mounts later compiles the // patched state instead of replaying stale markup. State patches go // through the revision watcher. A view-only patch has no revision to // wait for, so the instance's mounted surfaces re-render here. for (const slot of manifest.surfaces) { renderStates.delete(keyOf(instanceId, slot.kind)); } if (!statePatched) rerenderInstance(instanceId); return; }
publish(key, { status: "ok", html: sanitized.html, styles }); } catch (error) { const message = error instanceof Error ? error.message : String(error); pushError({ instanceId, pluginId: manifest.id, surface: kind, message }); publish(key, { status: "error", html: "", styles, error: message }); } }
function publish(key: string, next: PluginSurfaceState): void { const previous = renderStates.get(key); if ( previous && previous.status === next.status && previous.html === next.html && previous.error === next.error && previous.styles.length === next.styles.length && previous.styles.every((style, index) => style === next.styles[index]) ) { return; }
renderStates.set(key, next); for (const listener of listeners.get(key) ?? []) listener(next); }
function stateOf(instanceId: string, kind: PluginSurfaceKind): PluginSurfaceState | undefined { return renderStates.get(keyOf(instanceId, kind)); }
async function dispatch( instanceId: string, kind: PluginSurfaceKind, action: PluginAction, ): Promise<void> { log({ kind: "action", instanceId, message: `${action.name} ${JSON.stringify(action.args ?? {})}`.slice(0, 240), });
if (action.name.startsWith("app.") || action.name.startsWith("ai.")) { const result = await handleBuiltin(instanceId, action); if (result.denied) { publish(keyOf(instanceId, kind), { status: "error", html: "", styles: [], error: `"${action.name}" was denied: the ${result.denied} capability is not declared`, }); return; } if (!result.rerender) await renderInstance(instanceId, kind, action, result); return; }
await renderInstance(instanceId, kind, action); }
function pluginIdOf(instanceId: string): string { return workspace.value?.getPluginInstance(instanceId)?.pluginId ?? "unknown"; }
function capabilityOf(instanceId: string, capability: PluginCapability): boolean { const store = workspace.value; const instance = store?.getPluginInstance(instanceId); const manifest = instance ? manifestOf(instance.pluginId) : undefined;
return manifest?.capabilities.includes(capability) ?? false; }
function deny(instanceId: string, action: PluginAction, capability: PluginCapability) { pushError({ instanceId, pluginId: pluginIdOf(instanceId), message: `action denied: missing capability "${capability}"`, });
return { action: action.name, ok: false, message: `missing capability "${capability}"`, denied: capability, }; }
/** * Applies a patch to an instance's synced collections. */ async function patchData(instanceId: string, ops: PluginPatchOp[]): Promise<boolean> { if (!ops.length) return false; if (!capabilityOf(instanceId, "plugin.data")) { pushError({ instanceId, pluginId: pluginIdOf(instanceId), message: `patch refused: missing capability "plugin.data"`, });
return false; }
const store = workspace.value; if (!store) return false; await store.applyPluginPatch(instanceId, ops);
return true; }
/** Host actions return a result the plugin sees on its next render. */ async function handleBuiltin( instanceId: string, action: PluginAction, ): Promise<PluginActionResult & { rerender?: boolean; denied?: PluginCapability }> { const store = workspace.value; if (!store) return { action: action.name, ok: false, message: "no workspace" };
switch (action.name) { case "app.open-page": { if (!capabilityOf(instanceId, "pages.read")) return deny(instanceId, action, "pages.read"); const id = String(action.args.id ?? action.fields?.id ?? ""); if (id) navigation.openPage(id); return { action: action.name, ok: Boolean(id) }; }
case "app.create-page": { if (!capabilityOf(instanceId, "pages.create")) return deny(instanceId, action, "pages.create"); const title = String(action.fields?.title ?? action.args.title ?? "Untitled"); const page = await store.createPage({ title }); navigation.openPage(page.id); return { action: action.name, ok: true, data: { pageId: page.id } }; }
case "app.create-daily": { if (!capabilityOf(instanceId, "daily.write")) return deny(instanceId, action, "daily.write"); const date = String(action.args.date ?? action.fields?.date ?? todayISO()); const page = await store.createDailyNote(date); navigation.openPage(page.id); return { action: action.name, ok: true, data: { pageId: page.id } }; }
case "app.open-plugin": case "app.open-instance": { const explicit = String(action.args.instanceId ?? ""); if (explicit && store.getPluginInstance(explicit)) { navigation.openPlugin(explicit); return { action: action.name, ok: true }; }
const pluginId = String(action.args.pluginId ?? ""); const kind = String(action.args.surface ?? "pane") as PluginSurfaceKind; const instance = store .listPluginInstances() .find( (candidate) => candidate.pluginId === pluginId && (surfacesOf(candidate.id).some((surface) => surface.kind === kind) || kind === "pane"), ); if (instance) navigation.openPlugin(instance.id); return { action: action.name, ok: Boolean(instance) }; }
case "app.link": { const href = String(action.args.href ?? ""); if (href.startsWith("typbase://page/")) { if (!capabilityOf(instanceId, "pages.read")) return deny(instanceId, action, "pages.read"); navigation.openPage(href.slice("typbase://page/".length)); return { action: action.name, ok: true }; } if (href.startsWith("typbase://plugin/")) { const id = href.slice("typbase://plugin/".length); if (store.getPluginInstance(id)) navigation.openPlugin(id); return { action: action.name, ok: Boolean(store.getPluginInstance(id)), }; } if (/^(https?:|mailto:|tel:)/i.test(href)) { if (!capabilityOf(instanceId, "ui.external")) return deny(instanceId, action, "ui.external"); if (await openExternalLink(href)) { return { action: action.name, ok: true }; } return { action: action.name, ok: false, message: "cancelled" }; } return { action: action.name, ok: false, message: "unsupported link" }; }
case "app.page-append": { if (!capabilityOf(instanceId, "pages.write")) return deny(instanceId, action, "pages.write"); const text = String(action.args.text ?? action.fields?.text ?? ""); if (!text) return { action: action.name, ok: false, message: "nothing to insert", };
const explicitId = String(action.args.pageId ?? ""); const date = String(action.args.date ?? ""); const page = explicitId ? store.getPage(explicitId) : date ? await store.createDailyNote(date) : undefined; if (!page) { pushError({ instanceId, pluginId: pluginIdOf(instanceId), message: "page-append: no page", }); return { action: action.name, ok: false, message: "no page" }; }
const current = await store.loadPageText(page.id); const separator = current.endsWith("\n") || current === "" ? "" : "\n"; const next = `${current}${separator}${text}\n`; await store.setPageText(page.id, next);
// Sections feed the note index and plugin data. Refresh them now so // plugins see fresh content without a page switch. const typstState = await useTypst().catch(() => null); if (typstState) { await refreshSections(store, page.id, next, (source) => engineAvailable() ? toSections(sectionsOf(typstState, source), source) : null, ); } bumpPluginsRevision();
pushToast({ titleKey: "plugins.appended", params: { title: page.title }, duration: 2200, }); return { action: action.name, ok: true, data: { pageId: page.id } }; }
case "app.external": { if (!capabilityOf(instanceId, "ui.external")) return deny(instanceId, action, "ui.external"); const url = String(action.args.url ?? ""); if (/^(https?:|mailto:|tel:)/i.test(url) && (await openExternalLink(url))) { return { action: action.name, ok: true }; } return { action: action.name, ok: false, message: "cancelled" }; }
case "app.toast": { const message = String(action.args.message ?? action.fields?.message ?? ""); if (!message) return { action: action.name, ok: false, message: "empty toast" }; pushToast({ title: message, variant: action.args.tone === "danger" ? "danger" : "default", duration: 3000, }); return { action: action.name, ok: true }; }
case "app.window-open": { openWindow(instanceId); return { action: action.name, ok: true, rerender: false }; }
case "app.window-close": { closeWindow(instanceId); return { action: action.name, ok: true, rerender: false }; }
case "ai.complete": case "ai.stream": { if (!capabilityOf(instanceId, "plugin.ai")) return deny(instanceId, action, "plugin.ai"); const kind = surfaceOf(instanceId, "pane") ? "pane" : firstKind(instanceId); if (!kind) return { action: action.name, ok: false }; await runAi(instanceId, kind, action); return { action: action.name, ok: true, rerender: false }; }
default: { pushError({ instanceId, pluginId: pluginIdOf(instanceId), message: `unknown host action "${action.name}"`, }); return { action: action.name, ok: false, message: "unknown host action", }; } } }
function firstKind(instanceId: string): PluginSurfaceKind | undefined { return surfacesOf(instanceId)[0]?.kind; }
/** Maps a resolved AI call back into the plugin as an `ai.result` render. */ async function runAi( instanceId: string, kind: PluginSurfaceKind, action: PluginAction, ): Promise<void> { const store = workspace.value; if (!store) return;
const followUp = (args: Record<string, unknown>) => renderInstance(instanceId, kind, { id: crypto.randomUUID(), name: "ai.result", args: { request: action.id, ...args }, fields: {}, });
if (!store.getAiSettings().enabled) { await followUp({ error: "AI features are disabled in settings." }); return; }
const args = action.args; const fields = action.fields ?? {}; const prompt = String(args.prompt ?? fields.prompt ?? "").trim(); if (!prompt) { await followUp({ error: "ai: prompt is required" }); return; }
const format = args.format === "typst" ? "typst" : "text"; const canReadPages = capabilityOf(instanceId, "pages.read"); const pageId = canReadPages && typeof (fields.pageId ?? args.pageId) === "string" ? String(fields.pageId ?? args.pageId) : null; const selection = typeof args.selection === "string" ? args.selection : null; const providerId = typeof args.providerId === "string" ? args.providerId : null; const model = typeof args.model === "string" ? args.model : null;
if (action.name === "ai.stream") { await runAiStream(instanceId, { followUp, prompt, format, pageId, selection, providerId, model, collection: String(args.collection ?? fields.collection ?? ""), recordId: String(args.id ?? fields.id ?? ""), field: String(args.field ?? fields.field ?? "text"), }); return; }
try { const result = await completeForPlugin({ store, prompt, format, pageId, selection, providerId, model, }); await followUp({ text: result.text, diagnostics: result.diagnostics }); } catch (error) { await followUp({ error: error instanceof Error ? error.message : String(error), }); } }
/** * Streaming AI calls write the growing text into one plugin record, so a * surface can render its own live chat without new protocol. The field is * patched on a debounce. `<field>Status` tracks streaming/done/error. */ async function runAiStream( instanceId: string, input: { followUp: (args: Record<string, unknown>) => Promise<void>; prompt: string; format: "text" | "typst"; pageId: string | null; selection: string | null; providerId: string | null; model: string | null; collection: string; recordId: string; field: string; }, ): Promise<void> { const store = workspace.value; if (!store) return; if (!input.collection || !input.recordId) { await input.followUp({ error: "ai.stream: collection and id are required", }); return; }
aiStreams.get(instanceId)?.abort(); const controller = new AbortController(); aiStreams.set(instanceId, controller);
const statusField = `${input.field}Status`; let passText = ""; let timer: ReturnType<typeof setTimeout> | undefined; const patch = async (): Promise<void> => { await patchData(instanceId, [ { op: "merge", collection: input.collection, id: input.recordId, record: { [input.field]: passText }, }, ]); }; const schedule = (): void => { if (timer) return; timer = setTimeout(() => { timer = undefined; void patch().catch(() => { // A deleted record stops the stream from the plugin's side. The // completion patch below will recreate nothing. }); }, 150); };
await patchData(instanceId, [ { op: "merge", collection: input.collection, id: input.recordId, record: { [input.field]: "", [statusField]: "streaming" }, }, ]);
try { const result = await completeForPlugin({ store, prompt: input.prompt, format: input.format, pageId: input.pageId, selection: input.selection, providerId: input.providerId, model: input.model, signal: controller.signal, onDelta: (delta) => { passText += delta; schedule(); }, onReset: () => { passText = ""; void patch(); }, });
if (timer) clearTimeout(timer); await patchData(instanceId, [ { op: "merge", collection: input.collection, id: input.recordId, record: { [input.field]: result.text, [statusField]: "done", [`${input.field}Diagnostics`]: JSON.stringify(result.diagnostics), }, }, ]); await input.followUp({ text: result.text, diagnostics: result.diagnostics, }); } catch (error) { if (timer) clearTimeout(timer); const message = error instanceof Error ? error.message : String(error); await patchData(instanceId, [ { op: "merge", collection: input.collection, id: input.recordId, record: { [statusField]: "error", [`${input.field}Error`]: message, }, }, ]).catch(() => undefined); await input.followUp({ error: message }); } finally { if (aiStreams.get(instanceId) === controller) aiStreams.delete(instanceId); } }
// Workspace changes (install, theme, pages) refresh every mounted surface. watch(dataRevision, () => { for (const key of [...listeners.keys()]) { const separator = key.lastIndexOf(":"); void renderInstance(key.slice(0, separator), key.slice(separator + 1) as PluginSurfaceKind); } });
return { catalog, installs, instances, errors, logs, engine: pluginEngine, resetEngine: resetPluginEngine, clearLogs, install, addInstance, installFromFolder, installFromUri, publish: publishToAtmosphere, refreshCatalog, uninstall, setEnabled, removeInstance, renameInstance, instanceById: (id: string) => workspace.value?.getPluginInstance(id), manifestOf, surfacesOf, surfaceOf, instancesWithSurface, hostComponentsOf, subscribe, stateOf, dispatch, renderInstance, errorsFor, clearErrors, windows, windowOf, openWindow, closeWindow, focusWindow, moveWindow, resizeWindow, viewOf, resetView, };}
export const usePlugins = createSharedComposable(usePluginHost);