PotionUI Docs v0.3.0

Contributing a chat mode

A plugin with its own page (a pages: entry) can give that page a dedicated chat assistant instead of sharing the generic one. Declare it in manifest.yml; no Python class is needed:

On this page
yaml
chat_modes:
  - id: "my-plugin"
    name: "My Plugin Assistant"
    description: "Helps with things specific to this plugin"
    icon: "photo"
    default_route_prefixes:
      - "/plugins/my-plugin"
    tools:
      - "count_datasets"
    system_prompt: |
      You are an assistant for My Plugin. Use the tools below to ground your answers.

      Available tools:
      {{TOOL_HINTS}}

The frontend resolves which mode a chat panel opens in by matching the current route against every mode's default_route_prefixes (longest prefix wins); visiting your plugin's page auto-selects this mode, no navigation wiring required on your part. tools: lists tool names the mode's system prompt always mentions ({{TOOL_HINTS}} expands to their hints); a tool becomes usable in the mode either by being named there or by declaring the mode in its own modes: list (see "A chat tool" above) — declaring it in both places is redundant but harmless. Disabling the plugin removes the mode and its tools from every registry automatically.

Driving the chat panel from your plugin's page#

window.__potionui.chat is the frontend host API ($lib/plugin-api/host.ts) a plugin-hosted page uses to work with the global chat assistant without the assistant knowing your plugin exists:

  • provideContext(key, provider) — registers a function called on every chat send; its return value is merged into the outgoing context_metadata under key (a null return is skipped, not sent). Call the returned unregister function when your page unmounts.
  • declareMode(modeId) — makes modeId the assistant's active mode for as long as the declaration is active, overriding the route-prefix match (useful for a mode that isn't reachable through any route prefix, e.g. an admin-only setup wizard). The most recently declared mode wins if more than one is active; unregistering restores route-based resolution.
  • onToolApplied(toolName, handler) — runs handler with the result of each call to toolName in the conversation (its data, decoded from JSON): a tool that needs approval once the user approves it, any other tool once the assistant's reply that ran it has arrived. For an approved tool it runs before (and instead of) any core hardcoded handling for that tool name. See "When onToolApplied runs" below.
  • open(), close(), toggle() — open, close or flip the global chat panel, the same panel the sidebar button and the keyboard shortcut drive. Pair them with declareMode/provideContext to open the assistant already focused on your page, for example from an "Ask the assistant" button.
  • isOpen() — whether the panel is open right now.
  • prefill(text, {replace?}) — puts text in the chat composer without sending it, opens the panel if it is closed and focuses the composer, so the user reads and edits the message and sends it, or not, as with one they typed. A draft the user has already typed is kept; pass {replace: true} to overwrite it. Called while the panel is still loading, the text lands as soon as the chat is ready; it is dropped if the panel is closed first or the chat is not ready within 15 seconds.
  • send(text) — sends text as the user's message, as if they had typed it, in the mode the page resolves (the route-prefix match, or your declareMode), opening the panel if it is closed. The user does not confirm it: the message appears in the conversation as theirs and the assistant answers it; a tool declared with requires_approval still waits for their approval as usual. When the open conversation is in another mode, a new conversation is started in the page's mode; the previous one stays in the chat history. Your provideContext providers run for this message like for any other, and the draft in the composer is left alone. Returns a promise that resolves once the message is on its way (not when the assistant has answered) and rejects with an Error when the chat is unavailable: no chat model configured, the assistant still answering the previous message, the conversation could not be created, the panel closed before the chat was ready, or the chat not ready within 15 seconds. An empty text rejects with a TypeError. Prefer prefill when the user should read the message before it goes.

open, close, toggle, isOpen, prefill and send are absent on hosts that predate them: feature-detect them before offering a button that relies on them, or call them as window.__potionui.chat.open?.().

js
const chat = window.__potionui.chat;
draftButton.hidden = !chat.prefill;
draftButton.onclick = () => chat.prefill('Plan the shots for this storyboard');
sendButton.hidden = !chat.send;
sendButton.onclick = async () => {
  try {
    await chat.send('Add a closing shot to the storyboard');
  } catch (error) {
    window.__potionui.notifications.toast('error', error.message);
  }
};
js
const unregisterContext = window.__potionui.chat.provideContext('comfyui_import_wizard', () => ({
  step: currentStep,
  workflow_id: workflowId
}));
const unregisterMode = window.__potionui.chat.declareMode('comfyui-import-wizard');
const unregisterTool = window.__potionui.chat.onToolApplied('import_comfyui_workflow', (result) => {
  applyImportedWorkflow(result.workflow);
});
askButton.onclick = () => window.__potionui.chat.open();

// on unmount:
unregisterContext();
unregisterMode();
unregisterTool();

When onToolApplied runs. A tool declared with requires_approval reaches the handler when the user approves it; a rejected call never does. Any other tool reaches it when the assistant's reply that ran it is final: at the end of the streamed answer (including one the app reattaches to after a reload), when the app recovers a reply whose stream was cut, in the non-streaming fallback, and for the tools the assistant runs while it carries on after an approval. Such a call reaches the handler only when it succeeded and its data is JSON: a tool that returns plain text, a failed or skipped call, and a call that waits for approval or whose approval expired are not passed on. Nothing reaches the handler while the user has switched the assistant's tools off (Tools OFF in the composer).

Each call reaches the handler at most once. A call is identified by its assistant message and its position in that message, so a reply that arrives twice (live, then again when the app recovers it after a dropped connection) does not run the handler again, and an approved call is never run a second time as an unapproved one. Opening an earlier conversation from the chat history does not replay its tool results, and a handler registered after a result arrived does not receive it.

The handler may return {status, message?} with status one of 'applied', 'stale', 'partial' or 'noop'. When it reports 'stale' or 'partial' with a message, the chat shows that message in place of the assistant's narration for that reply, the same way it does for an approved tool; when one reply ran several such calls, the last message wins. It changes what is shown, not the stored conversation. A handler that throws is logged, and the reply's other calls still reach their handlers.

js
const unregisterShot = window.__potionui.chat.onToolApplied('my_plugin_add_shot', (result) => {
  if (result.project_id !== currentProjectId) {
    return { status: 'stale', message: 'That shot belongs to another project; it was not added here.' };
  }
  timeline.insertShot(result.shot);
  return { status: 'applied' };
});

On a host that predates this, only approved calls reach the handler, and nothing on window.__potionui tells the two apart.

Following a turn live. A tool that runs without approval reaches onToolApplied only when the whole reply is final, which can be many calls later. A page whose tools save its document on the server can follow each call as it ends: the host dispatches a potionui:tool-end event on window for every tool call of a streamed turn, with detail = {tool_name, success, pending} (pending is true for a call that now waits for the user's approval). The event carries no result, so read your own state again, and keep onToolApplied for the result itself: a page that misses the event (a host that predates it, a reply recovered after a dropped connection) still gets the result there.

js
const => {
  const { tool_name, success, pending } = event.detail;
  if (success && !pending && myTools.includes(tool_name)) reloadDocumentIfNewer();
};
window.addEventListener('potionui:tool-end', onToolEnd);
// on unmount:
window.removeEventListener('potionui:tool-end', onToolEnd);