UI Components
UI plugins are TypeScript projects that produce Web Components (Custom Elements) for the Codumentor interface. This guide covers directory structure, the Plugin SDK, widget development, and building.
See also: Backend Hooks, User Gates (per-user blocking modals), Best Practices, Plugin SDK README
Directory Structure
ui/plugins/my_plugin/
├── manifest.json # Plugin metadata
├── package.json # NPM dependencies and build script
├── tsconfig.json # TypeScript configuration
├── index.js # Built bundle (generated)
└── src/
├── index.ts # Entry point - registers custom elements
├── types.ts # Data interfaces
├── styles.ts # Component CSS
└── components/ # Component files (optional organization)
└── my-card.ts
Quick Start
- Copy the template:
``bash``
cp -r ui/plugins/_template ui/plugins/my_plugin
- Update
manifest.json:
``json``
{
"plugin_id": "my_plugin",
"name": "My Plugin",
"version": "1.0.0",
"description": "What this plugin does",
"event_types": ["plugin.my_plugin.completed"],
"transcript_events": {
"*": { "role": "card", "element": "x-my-plugin-card" }
},
"ui": {
"bundle": "index.js",
"sdk_version": "1.0",
"custom_elements": ["x-my-plugin-card"],
"placements": ["transcript-card"]
}
}
transcript_events (top level, not under ui) declares what each event
means to the conversation and which element draws it — see
Transcript events.
The file's JSON Schema ships with the SDK
(@codumentor/plugin-sdk/manifest.schema.json; plugin new copies it to
ui/types/manifest.schema.json). Add "$schema": "<path to it>" for editor
completion — the host ignores the key — and codumentor plugin validate
checks the manifest against it.
Supported ui.placements values (the ExtensionPlacement union in
ui/src/types/api.ts):
| Placement | Where it renders |
|---|---|
| transcript-card | Plugin events in the transcript — as a line, card or receipt chip by the event's role (see Transcript events) |
| message-actions | Controls in the assistant turn action row (next to copy) |
| chat-header | Small components in the chat header (see Chat Header Widgets) |
| message-list-header | An in-flow row above the transcript's scroll viewport |
| composer-intent | Left of the composer textarea: what this turn does (see Composer Controls) |
| composer-input | Right of the composer textarea: how I am entering this message |
| composer-tray | The state row above the composer textarea (see the tray) |
| activity-panel | Deprecated, not rendered. The activity side panel was removed; manifests declaring it still validate, but the widget never mounts. Background work now shows in the strip above the composer. |
| permission-card | A whole card for a plugin-owned pending permission; see Permission cards. |
| workspace-view | A view in the chat's workspace pane. Widget fields: icon (a host icon name, e.g. files), availability (always \| conversation \| items, default conversation), shortcut (adds an "Open
plugin-id, widget-id, conversation-id, locale, active, layout (split \| mobile) and .target / .items; the element may dispatch workspace-view-state {badge?, busy?, title?}. Guide: workspace-views.md ||
welcome-widget, welcome-repos | Welcome page widget surfaces (see Welcome Page Widgets) ||
sidebar-panel | Plugin-driven sidebar surface ||
admin-panel | Panels on the admin hub page (see Admin Panels) ||
ingestion-panel | Panels inside the Ingestion page (see Ingestion Panels) |
The type is … | string, so a plugin may declare a custom slot; it renders
only where some host component mounts that placement.
- Update
package.json:
``json``
{
"name": "@codumentor/plugin-my-plugin",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "node ../../scripts/plugin-esbuild.js",
"build:watch": "node ../../scripts/plugin-esbuild.js --watch",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@codumentor/plugin-sdk": "file:../../../sdk/web",
"typescript": "^5.3.0"
}
}
The build itself is the SDK's (sdk/web/scripts/plugin-build.js, the code
behind the codumentor-plugin build bin an out-of-tree plugin uses);
ui/scripts/plugin-esbuild.js runs it for in-tree plugins, so no
package.json spells out esbuild flags. Two things it does matter to you:
- Bundles ship minified.
- The SDK is external.
@codumentor/plugin-sdk(and its/stylesand/utilssubpaths) is rewritten to/ui/extensions/sdk/index.js, the one shared SDK bundle the browser loads once, rather than inlined into your bundle. Which is why your bundle is a few KB rather than 110 KB, and whysdk/web/dist/bundle/index.jshas to be built before yours — the orchestrator (npm run build:plugins) does that for you.
- Create your component in
src/index.ts:
```typescript
import {
BasePluginElement,
bindExpandClick,
getBaseStyles,
escapeHtml,
formatMs,
} from "@codumentor/plugin-sdk";
interface MyPluginData {
message: string;
duration_ms?: number;
}
class MyPluginCard extends BasePluginElement
render(): void {
const { message, duration_ms } = this._data;
// Declared as a card, the host draws the frame, status edge and status
// glyph: CARD_STYLES unframes .card and getStatusIcon() returns ""
// then, so this markup is the body only.
this._shadowRoot.innerHTML = ${formatMs(duration_ms)}
<style>${getBaseStyles()}</style>
<div class="card ${this._status}">
<div class="header">
<span class="icon">${this.getStatusIcon()}</span>
<span class="title">My Plugin</span>
${duration_ms ? : ""};
</div>
<p>${escapeHtml(message)}</p>
</div>
}
}
// Register custom element - tag MUST match manifest.json
if (!customElements.get("x-my-plugin-card")) {
customElements.define("x-my-plugin-card", MyPluginCard);
}
export { MyPluginCard };
```
- Build:
``bash``
cd ui && npm run build:plugins
Permission cards
Declare a card at the top level, not as a widget. The key is the exact
permission type: use <plugin_id>.<type> for new types. The existing
browse_handoff wire type belongs to browse.
"permission_cards": {
"browse_handoff": { "element": "x-browse-handoff-card", "workspace_view": "handoff" }
}
List the card in ui.custom_elements and permission-card in ui.placements.
For a workspace offer, also declare workspace-view and a widget of that
placement with the referenced widget_id, availability: "items", a title
and its own declared custom element. Define both tags in the bundle. The
workspace element is a readiness marker for this route: the host renders the
card directly in the active tab panel. It needs no second stream or state.
The host sets the SDK's PermissionCardElement properties before connecting:
.permission (requestId, toolCallId, toolName, permissionType, details),
.locale, .onDecision("allow" | "deny"), .isSubmitting, and .active.
A localized .cardTitle getter names the host frame. Disable decision controls
while submitting; release streams and input listeners on disconnect. Opening,
closing, or hiding a view never answers a request.
By default the host frame is a header, a scrolling body holding the card, and a
host footer with Cancel. A card that needs the whole frame (a live view, say)
sets a .ownsLayout getter to true: the host then draws no footer, and its
body becomes a non-scrolling flex column that fills the height it has (the
workspace pane, or the modal's min(90dvh, 100%)), with the element stretched
to it; lay the card out as a flex column and scroll inside it where needed.
The host reads ownsLayout with cardTitle, after it sets the inputs. Such a
card must offer its own Cancel (onDecision("deny")) and keep it usable while the rest of the card is busy. If the bundle fails to load, the
host frame and its Cancel return as usual.
Only the first pending permission is offered. A workspace offer never changes
focus or selection. It lasts only as long as that pending request: don't
publish a workspace.item or emit a separate handoff event. With the pane off,
a withheld/unavailable widget, or a missing workspace element, the same card
appears in a host modal. If the card cannot load the host offers Cancel only.
Unless the card sets ownsLayout, the host's Cancel remains available even if
the renderer stops responding.
Transcript events: roles and presentations
Every plugin event that reaches the transcript has a role, and the host
turns the role into placement, frame, spacing, disclosure and focus-mode
behaviour — on the web and in the TUI alike. Your element draws content only.
Design and rationale:
plugin-activity-presentation.md.
The four roles
Decide an event's role by asking, in order:
- Does it mark a change to the conversation itself, true from this point on? →
line - Is it output, live work, or something the user must act on? →
card - Otherwise it is bookkeeping about the turn it belongs to →
receipt
| Role | Where it renders | Examples |
|---|---|---|
line | A quiet rule across the column with a sentence in it, at the event's position. May open a document below the rule. | model/effort seam, compaction, push marker, topic shift |
card | A host-framed card at the leading (left) edge, at the event's position — like a tool card. Opening it grows it in place. | file written, process with Kill, server with Start/Retry, scheduled run, an error to fix |
receipt | A chip in the turn's single receipt strip, under the answer. One chip's panel open at a time, full column width. | timings, metrics, memories recalled/stored, skill loaded, context state |
none | Nothing. | a terminal outcome that should disappear (below) |
A receipt is attached to the turn named by its event's turn_id (below), and
the strip sits above the turn's action row; while the turn runs it sits at the
live bottom edge, so a pending "Recalling…" chip is visible before the answer
streams in above it. A receipt with no turn (before the first user message, or
inside a subagent's nested transcript) renders as a card.
In focus mode lines stay visible, the receipt strip stays under the
answer, and cards fold into the work chip unless the event sets
data.focus_visible: true (see focus-mode.md
§"Plugin event visibility").
Declaring roles: transcript_events
Declare role and element per event subtype in ui_manifest(), at the **top
level** of the manifest — beside event_types, not inside ui. The role is
surface-agnostic (the TUI resolves it too), so a plugin without a web bundle
declares it as well. A static manifest.json carries the same top-level key.
def ui_manifest(self) -> dict:
return {
"plugin_id": "my_plugin",
"event_types": [
"plugin.my_plugin.turn_complete",
"plugin.my_plugin.rdc_started",
"plugin.my_plugin.rdc_retrieved",
"plugin.my_plugin.file_written",
],
"transcript_events": {
"turn_complete": {"role": "receipt", "element": "x-my-metrics"},
"rdc_*": {"role": "receipt", "element": "x-my-recall"},
"*": {"role": "card", "element": "x-my-plugin-card"},
},
"ui": {
"bundle_url": "/ui/extensions/plugins/my_plugin/index.js",
"custom_elements": ["x-my-metrics", "x-my-recall", "x-my-plugin-card"],
"placements": ["transcript-card"],
},
}
- Keys match the event subtype (the part after
plugin.<id>.): an exact key wins, then the longestprefixkey, then""(the plugin default). - Field by field: a key that declares only an
elementleaves the role to a broader key, and anelementyour bundle did not register does not count (a broader key's element is used instead). roleis one ofline,card,receipt,none. An unknown value is dropped with a warning (the rest of the manifest survives) and ignored.elementis the custom element that renders the subtype. It wins over the plugin-wideui.transcript_cardand over subtype guessing.- A group whose pending and terminal subtypes map to different elements remounts the element on the update; host-held expansion survives.
An event your manifest does not declare falls back to a default:
data.align == "full" → line (your element still draws its own rule), anything
else → a left card. Declare every subtype you emit.
Per-event override: data.role
data.role ("line" | "card" | "receipt" | "none") overrides the manifest for
one event or group update; unknown values are ignored. Its main use is
"none" on a terminal update: a producer whose outcome turned out to be
empty sends the terminal update with role: "none", the lifecycle update is
applied first, then the chip (or card) is removed — live and after reload.
Do not use _hidden for that: materializers drop _hidden events before the
group update, which strands the pending chip.
await emit("plugin.my_plugin.rdc_retrieved", {
"status": "success",
"event_group_id": run_id,
"role": "none", # nothing recalled: no chip at all
}, turn_id)
Whole-state group updates: data.supersedes_group
A group update is a patch: the materializers merge {old, new}, so every
event of the group is kept in the store. A producer whose every update carries
the group's complete state — a live card refreshed several times a turn —
can set supersedes_group: true. The event store then deletes the group's
earlier events of the same type once the new one is written, so the group
costs one stored row however often it updated. Live clients see no difference;
a reload finds only the newest row, so a key that only an earlier update
carried is gone — do not set the flag on partial updates.
await emit("plugin.my_plugin.snapshot", {
**whole_state,
"event_group_id": f"my_plugin:{turn_id}",
"supersedes_group": True,
}, turn_id)
Element presentations
The host mounts your element with a presentation property (reflected as an
attribute, so your stylesheet can key off :host([presentation="chip"])):
presentation | Mounted for | Your element renders |
|---|---|---|
"line" | a line | the glyph and text inside the host's rule — never the rule |
"panel" (line) | below a line's rule, only when the line instance's hasPanel is true | a closed one-line preview, and the document while expanded |
"card" | a card (and a receipt with no strip) | the card body — no outer frame, no status edge, no status glyph |
"chip" | a receipt's chip in the strip | glyph, short label, optional value (~24 characters) — use chipHtml() + RECEIPT_STYLES |
"panel" (receipt) | below the strip while the chip is open | the whole panel, actions included, with no frame or header (the chip is the header) |
Declaring support. List the presentations your element draws in a static
presentations on its class; the host reads it off customElements.get(tag)
before mounting. The default is ["card"]. Listing "chip" implies the
receipt "panel". Lines need no declaration.
import { BasePluginElement, chipHtml, RECEIPT_STYLES, getBaseStyles, formatMs } from "@codumentor/plugin-sdk";
class MyMetrics extends BasePluginElement<{ elapsed_ms: number }> {
static presentations = ["card", "chip"] as const;
get hasPanel() { return true; }
render() {
if (this.presentation === "chip") {
this._shadowRoot.innerHTML = `<style>${RECEIPT_STYLES}</style>` +
chipHtml({ glyph: "⏲", label: "Turn", value: formatMs(this._data.elapsed_ms) });
return;
}
// "panel" and "card": the body only — the host draws frame and status.
this._shadowRoot.innerHTML = `<style>${getBaseStyles()}</style><div class="card">…</div>`;
}
}
A receipt element that does not list "chip" gets a host-drawn chip from
data.chip_label, else data.summary, else the plugin and action names, and
its card presentation inside the open panel. So the cheapest good receipt is a
short chip_label in the event data. Plugins without a web bundle get the same
three presentations from the generic fields (summary, chip_label,
details_lines, details_markdown) through the host fallback renderer.
What the host reads off your element after every event and whenever you
call notifyHost() (which dispatches PLUGIN_ELEMENT_CHANGED_EVENT):
| Member | Instance | Meaning |
|---|---|---|
hasPanel | line, chip | false → no disclosure (a plain line, a chip that is text, not a button) |
chipAction | chip | {label, ariaLabel?, busy?} or null — the one inline control for queued or running work (cancel). The host renders it as its own button beside the chip and calls runChipAction(). All other actions belong in the panel. |
cardStatus | card | the status the frame shows when it differs from the event's — a card that tracks live state itself (polling a server it started), or a waiting prompt sent as pending that is really a warning. Null = the event's status. |
hidden (attribute) | card | set it on yourself when there is nothing to show (an event you only render on error, a dismissed card); the host hides the frame too |
The host owns the frame
For any host-set presentation (hostFramed is true) the host draws the card
frame (--color-bg-inset surface, hairline border, max-width: 90%), the
status edge (pending → --accent-live, success → muted green, warning,
error), and the status glyph on the body's first line (spinner while
pending, ⚠ / ✗ with accessible names; success is quiet). On chips it draws
the button, the same glyphs and the error colour. So:
getStatusIcon()returns""when host-framed, andCARD_STYLESunframes.cardunder:host([presentation="card"])— an element written against the SDK styles needs no change.- Do not draw your own status edge, status glyph, outer border or expand arrow in
card/chip/panel. Content glyphs (🧠, 📦) are yours. - Gate any custom framing on
hostFramed, so an undeclared mount — which has nopresentationattribute and gets no host frame — still looks right.
See visual-language.md §4.10 for the
exact tokens.
Status contract
- Every visible event carries
status:"pending","success","warning"or"error". Anything else is logged as invalid and treated aspending— a card with a spinner that never stops. - Every pending event gets a terminal update in the same
event_group_id: success, warning, error, orrole: "none"— including on exceptions, timeouts, cancellation and background completion. A turn ending is not proof your background work ended. Emit the terminal update from afinallypath. - Group updates are merged before the role is resolved, so a terminal update may change the subtype (and with it the declared role or element).
- Missing counts mean unknown, not zero: send the outcome you know.
turn_id: which turn a receipt belongs to
ui_event_emitter(event_type, data, turn_id=None) stamps the event with the
current turn when you pass none. Work that finishes later — memory storage
completing after the next turn started — must keep its receipt under the turn
that caused it: emit the pending event inside that turn (or pass its
turn_id), and keep the event_group_id. The envelope's turn id is kept from
a group's first event, live and in the snapshot, so the terminal chip lands
in the original turn's strip. An event with no turn id is attached to the turn
it arrives in.
TUI
The same resolver runs in Python (api/ui/services/transcript_role.py), fed
by the same top-level transcript_events. PluginCard (TUI SDK) is mounted
with presentation = card | line | chip | panel and exposes hooks
that default to the generic fields — _build_line_content(),
_has_line_document() / _build_line_document() / _build_line_preview()
for lines, chip_text() for the strip (no status glyph: the strip draws it),
and _build_details_text() for the panel. Cards sit at the left edge with the
host status edge. See distribution.md and
src/codumentor/plugins/tui_sdk/plugin_card.py.
Plugin SDK Reference
The SDK (@codumentor/plugin-sdk) provides types, utilities, and base classes.
Types
import type {
PluginEvent, // Full event object passed to components
PluginEventStatus, // "pending" | "success" | "warning" | "error"
PluginPresentation, // "card" | "line" | "chip" | "panel"
PluginChipAction, // { label, ariaLabel?, busy? }
PluginElement, // Interface for custom elements
PluginManifest, // manifest.json structure
} from "@codumentor/plugin-sdk";
Base Class
BasePluginElement<TData> provides:
| Property/Method | Description |
|---|---|
_shadowRoot | Shadow DOM root |
_event | Full event object |
_data | Event data (typed as TData) |
_status | Current status |
_expanded | Expansion state for collapsible cards |
escapeHtml(text) | HTML escape utility |
getStatusIcon() | Status emoji — "" when hostFramed |
static presentations | Presentations the element draws (default ["card"]; add "chip" for receipts) |
presentation | How the host mounted this instance: card / line / chip / panel (reflected as an attribute) |
hostFramed | True when the host set a presentation — it draws frame, status edge and glyph |
hasPanel | Override: whether a line / chip opens a panel |
chipAction / runChipAction() | Override: the one inline control on a chip for queued/running work |
cardStatus | Override: status for the host frame when it differs from the event's |
notifyHost() | Ask the host to re-read hasPanel / chipAction / cardStatus |
toggleExpanded() | Toggle expansion state (call this from your click handler) |
setExpanded(value) | Set expansion state directly (same channel as above) |
expanded | Property the host sets to restore expansion; also readable |
render() | Abstract — you must implement this |
Both expansion setters reflect an expanded attribute onto your element. The
app's stylesheet cannot see inside your shadow root, so that attribute is how
the transcript learns a card grew. Nothing beside a card reflows when it opens:
cards stack, they never share a row.
The host sets the event property, which triggers render() automatically.
Expansion is held by the host, not by your element
Your element does not outlive the transcript's layout decisions. It is
rebuilt on re-materialization, when focus mode moves it between renderers, when
a receipt's chip and panel instances are mounted, and when a group update
switches its element. Each of those destroys the element and the host builds
a new one — taking _expanded with it.
So the state lives above the card, keyed by the plugin event id, and the two
halves of BasePluginElement keep it in sync:
setExpanded/toggleExpanded— you call these, from a click handler. Besides re-rendering and reflecting the attribute, they dispatch a bubblingPLUGIN_CARD_EXPANDED_EVENT("codumentor:plugin-card-expanded", detail{ expanded }) that tells the host the user opened or closed this card.expanded— the host sets this property, on a freshly built element, to whatever it remembers. It applies the state silently: it does not dispatch the event, so state coming down can never echo back up.
None of that needs anything from your card beyond routing every toggle through
setExpanded/toggleExpanded — which bindExpandClick already does. Do not
assign this._expanded directly: the host would never hear about it, and the
next re-parenting would undo it.
Utilities
import {
escapeHtml, // Escape HTML special characters
formatMs, // Format milliseconds (e.g., "1.2s", "500ms")
formatBytes, // Format bytes (e.g., "1.5 KB")
formatNumber, // Format numbers with locale
formatPercent, // Format percentages
truncate, // Truncate text with ellipsis
} from "@codumentor/plugin-sdk";
To hand the user off to the chat, startNewChat({ prefill }) opens a new,
empty conversation with prefill in its composer — never sent, so the user
reviews it first. It works from a full page too (the host navigates to the
chat). See the SDK README, "Starting a new chat".
To open a host route such as a conversation (/c/<id>) without a page load,
call navigateInApp(url): it pushes the URL and fires the popstate the
host's router listens for.
A header widget that must know whether the conversation it shows has a turn
in flight (to hold back an action until it is idle) listens for
TURN_STATUS_EVENT and keeps a TurnActivity: record(event) on every
event, isActive(conversationId) when rendering. It is keyed by
conversation because the host keeps one widget instance for the session and
the event only reports the open conversation's stream.
Styles
The SDK provides CSS that integrates with the host's dark mode:
import {
// All base styles combined
getBaseStyles,
// Individual style modules
CSS_TOKENS, // CSS custom properties (--color-*, --radius-*, etc.)
CARD_STYLES, // .card, .header, .details
BADGE_STYLES, // .badge
STATUS_STYLES, // .success, .error, .pending
CODE_STYLES, // code, pre
LOADING_STYLES, // .loading, .loading-spinner
// Component styles
BUTTON_STYLES, // .btn, .btn-primary
TABLE_STYLES, // table, th, td
LIST_STYLES, // ul, li styles
INPUT_STYLES, // input, textarea
} from "@codumentor/plugin-sdk";
Always use CSS custom properties for colors to support dark mode:
.my-element {
background: var(--color-bg-inset); /* NOT #f5f5f5 */
color: var(--color-text); /* NOT #111 */
border: 1px solid var(--color-border); /* NOT #e0e0e0 */
}
Role tokens and "edge, not fill"
The host app's colors are not decorative — each accent has exactly one job.
doc/core-dev/design/visual-language.md
is the source of truth; the short version for plugin authors:
--accent-live— interactive or in-flight. Only for something clickable right now or actively working/streaming.--accent-user— the human's voice. Not available to plugin content; don't use it for emphasis or status.--accent-inner— the agent's inner work (thinking/subagent-shaped content). Recessed only — a low-alpha tint, never full strength.--color-success/--color-warning/--color-error(plus their-textvariants) — outcome only: done, needs attention, or failed.
Plugin cards read as neutral with a colored edge, not a colored fill. For a
declared card the host draws that edge from the event status (or your
cardStatus) — don't draw one yourself. The SDK's own
sdk-card-info|success|warning|error classes, for an undeclared mount
that frames itself, put the status color on the left border only
(plugin-sdk.css); the surface stays --color-bg-inset. A status color
filling the whole card is the mistake to avoid, inside a host frame or not.
Expand/Collapse Helper
import { bindExpandClick } from "@codumentor/plugin-sdk";
class MyCard extends BasePluginElement<MyData> {
render() {
this._shadowRoot.innerHTML = `...`;
// Add click handler for expandable header
bindExpandClick(this._shadowRoot, ".header", () => this.toggleExpanded());
}
}
Events that open into a document
An event whose open state is a document — a summary, a report — is usually a
line with a panel: the line instance renders the sentence, returns
hasPanel = true, and the panel instance renders a closed one-line preview
and, while expanded, the document. The host holds the document to a reading
measure (two thirds of the transcript column from 700px, the whole column
below); your wrapper should not cap its own width. A receipt's panel and a
card that opens are sized by the host the same way.
To render markdown inside such a document, use the SDK's renderer with
escapeRawHtml whenever the text is model output or comes from repository or
conversation content — marked passes embedded HTML straight through, and the
result goes into your shadow root via innerHTML:
import { renderMarkdownHtml, MARKDOWN_PREVIEW_STYLES } from "@codumentor/plugin-sdk";
const html = renderMarkdownHtml(text, { escapeRawHtml: true });
MARKDOWN_PREVIEW_STYLES carries the matching block styles (it targets
.markdown-content) and follows the host theme.
Offering "open these cards by default"
A card whose open state is worth reading every time can offer the reader a
setting for it, without any front-end change. Declare a boolean in your
settings_schema and mark it "opens_cards": True:
def ui_manifest(self) -> dict:
return {
"settings_schema": {
"properties": {
"open_summary_cards": {
"type": "boolean",
"title": "Open summary cards by default",
"default": False,
"opens_cards": True,
},
},
},
}
The transcript resolves the flag generically (ui/src/state/hiddenPluginCards.ts)
and every card of that plugin mounts with expanded already set. Notes:
- It is the mirror of
"hides_cards": True, the flag that lets a boolean switch your cards off. A plugin may declare both; they are independent. - An unset value falls back to the declared
default, so the toggle reads the same in the settings panel as the transcript behaves. PreferFalse: a default-open document at every event is a lot of transcript to scroll past. - It is a default, not a lock. The reader closing such a card is remembered for the rest of the conversation, and that decision beats the setting.
- Nothing in your plugin reads the value back — the host does. That is also why the "every declared setting must be read by something" tripwire (
tests/test_plugin_settings_read_sites.py) accepts the flag as the answer.
Using Other Frameworks
The build contract is framework-agnostic. Your plugin just needs to:
- Have a
buildscript inpackage.json - Output an ES module that registers custom elements
- Custom elements accept an
eventproperty
You can use:
| Framework | Approach |
|---|---|
| Vanilla TS | Extend BasePluginElement or raw HTMLElement |
| Lit | Use @customElement decorator |
| Svelte | Compile with customElement: true |
| Preact/React | Wrap with @preact/custom-element or similar |
| Vue | Use defineCustomElement() |
Example with Lit
import { LitElement, html, css } from "lit";
import { customElement, property } from "lit/decorators.js";
import type { PluginEvent } from "@codumentor/plugin-sdk";
@customElement("x-my-plugin-card")
export class MyPluginCard extends LitElement {
@property({ type: Object })
event?: PluginEvent<MyData>;
render() {
const data = this.event?.data;
return html`<div class="card">${data?.message}</div>`;
}
}
Welcome Page Widgets
Plugins can contribute widgets to the welcome page by adding a widgets array to the manifest:
{
"ui": {
"widgets": [{
"id": "status_widget",
"element": "x-my-status-widget",
"title": "My Status",
"placement": "welcome-sidebar"
}]
}
}
Widget Implementation with API Fetching
class MyStatusWidget extends HTMLElement {
private _shadowRoot: ShadowRoot;
private _config: { refresh_interval_seconds?: number } = {};
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: "open" });
}
set config(value: { refresh_interval_seconds?: number }) {
this._config = value || {};
if (value?.refresh_interval_seconds) {
setInterval(() => this.fetchData(), value.refresh_interval_seconds * 1000);
}
}
connectedCallback() {
this.fetchData();
}
async fetchData() {
const response = await fetch("/ui/plugins/my_plugin/status/summary");
const data = await response.json();
this.render(data);
}
render(data: any) {
this._shadowRoot.innerHTML = `
<style>${getBaseStyles()}${WIDGET_STYLES}</style>
<div class="widget">
<div class="widget-header">${data.title}</div>
<div class="widget-content">${data.count} items</div>
</div>
`;
}
}
customElements.define("x-my-status-widget", MyStatusWidget);
Two-Tier Loading Pattern
For optimal performance, implement two API endpoints — a fast summary for initial render and a full dataset for expanded views:
# Backend API routes
@router.get("/status/summary")
async def get_summary(request: Request):
# Fast endpoint for initial render (< 100ms)
return {"count": 5, "top_items": [...], "has_more": True}
@router.get("/status")
async def get_full(request: Request):
# Full data when user expands
return {"items": [...]}
Building Plugins
Build Commands
From the ui/ directory:
# Build everything (plugins + main UI)
npm run build
# Build only plugins
npm run build:plugins
# Build with verbose output
npm run build:plugins:verbose
# Build a specific plugin
node scripts/build-plugins.js --plugin=telemetry
# Watch mode (in plugin directory)
cd plugins/my_plugin && npm run build:watch
Build Contract
The build system (ui/scripts/build-plugins.js) expects:
package.jsonwith abuildscriptmanifest.jsonwith plugin metadata andui.bundlepath- After
npm run build, the file atmanifest.ui.bundlemust exist
The orchestrator:
- Builds the SDK first (
sdk/web) - Installs dependencies for each plugin if needed
- Runs
npm run buildfor each plugin - Copies bundles to
ui/dist/plugins/{plugin_id}/
Code splitting (opt-in). If your bundle is eager (a chat-header or welcome
widget) but also carries a heavy page app, set
"pluginBuild": { "splitting": true } in package.json and import() the
app lazily from its element. The build then emits chunk-<hash>.js files flat
beside index.js; they are served, packaged and git-ignored like it. The entry
must still define every declared custom element. Example: ui/plugins/goals.
Extra plugin folders
ui/plugins/ is always searched. Further source folders (for example an
overlay repository's own plugins) are named by CODUMENTOR_UI_PLUGIN_DIRS,
separated by the OS path separator (: on Linux/macOS, ; on Windows);
relative entries resolve against the repository root, not the current
directory. One variable drives every consumer:
build-plugins.jsandwatch-plugins.jsbuild/watch those plugins too (bundles are built in place, and copied toui/dist/plugins/<id>/like the built-in ones). The shared discovery lives inui/scripts/plugin-dirs.js.vite.config.tsserves/ui/extensions/plugins/<id>/from the folder that has the plugin and runs itssrc/*/.test.ts(x)undernpm run test:unit.- The backend (
ui_plugins_dirs()insrc/codumentor/utils/bundle.py) looks a plugin id up inui/plugins/first, then in each extra folder. scripts/build.specandscripts/build_nuitka.pystage every folder's bundles into the package's singleui/plugins/; a packaged binary ignores the variable at runtime. The container build (deploy/Dockerfile.backend) only copiesui/plugins/, so an overlay must add its folder there itself.
A plugin id must be unique across all folders: the build (and vite) refuse
an id that two folders both offer. Plugins outside ui/plugins/ cannot use the
in-tree node ../../scripts/plugin-esbuild.js build script; use the SDK's
codumentor-plugin build / codumentor-plugin watch instead.
Development Workflow
- Start the dev server:
``bash``
cd ui && npm run dev
- Build plugins when you make changes:
``bash``
npm run build:plugins
# Or use watch mode in the plugin directory
- Refresh the browser to see changes (or use the plugin's watch mode + browser refresh)
Settings panes
A plugin's per-user settings appear as its row under Settings → Extensions.
ui_manifest() declares what the row renders: a settings_schema (the host
builds a form), a settings_widget (your own custom element, with
"web_component": "x-…" and the tag in ui.custom_elements with the
settings-panel placement), an oauth_connection, or several of them. In the
TUI the row mounts the Textual widget your plugin returns from
tui_settings_widget(user_id).
A plugin may instead put those same settings in a pane at the root of the
Settings sidebar by declaring settings_pane.
Most plugins should not declare a
settings_pane. Usesettings_schema
orsettings_widget: they appear under Settings → Extensions, which is where
users look for a plugin's options. A root pane lengthens the Settings sidebar
for every user of every deployment that loads your plugin.A root pane is for a plugin that meets all three of these:
- it owns a product-level concern that most users visit, such as the models a conversation runs on;
- without it, the concern would have to be a core section;
- its pane stands on its own rather than listing options.
If you are unsure, it does not qualify. Raise it in review before adding one.
def ui_manifest(self):
return {
# … existing keys, including what the pane renders:
"settings_widget": {"web_component": "x-my-plugin-settings"},
"settings_pane": {
"id": "models", # slug, unique per process
"title": {"en": "Models", "hu": "Modellek"},
"icon": "model", # host icon token
"order": 10, # among plugin panes
# "access_feature": "<plugin>.<feature>", # optional
},
}
| Field | Required | Meaning |
|---|---|---|
id | Yes | A slug ([a-z][a-z0-9_-]*, at most 40 characters), unique per process. The web section id is plugin:<id>. |
title | Yes | The nav label by locale. en is required; other locales fall back to it. |
icon | No | A token from the host set: model, key, link, user, chart, database, globe. Anything else, or none, renders a generic glyph. You cannot supply your own SVG. |
order | No | Position among plugin panes (default 100); ties sort by id. |
access_feature | No | The access feature the pane belongs to. |
What the host does with it:
- Position is banded. The sidebar is General, Tool Approvals, Shared, the plugin panes (by
order, thenid), Extensions, About. A plugin cannot reorder, replace or sit between core items. - One rendering path. The pane's body is exactly what your Extensions row would have rendered — schema form,
settings_widget,oauth_connection— under the pane's localized title. A plugin with a pane has no Extensions row. A pane with nothing to render is not shown. - One pane per plugin, first come first served. A duplicate
idgoes to the plugin loaded first (priority order, which is deterministic). The other plugin's pane is refused with an error log naming both, and that plugin keeps its Extensions row. Ownership is decided over every loaded plugin's declaration before any access check, so it is the same for every user: a pane withheld from one user does not pass itsidto the next plugin. An invalid declaration (noentitle, anidthat is not a slug) is refused the same way. - Gating.
access_featureonsettings_panewithholds the pane from a principal without the feature — and your settings with it: they do not fall back to an Extensions row.access_featureonsettings_widgetwithholds just the widget. An edition that excludes your plugin sends no manifest, so no pane. - Deep links.
openSettings("plugin:<id>")opens the pane. An olderopenSettings("extensions", { pluginId })for a plugin that now owns a pane is redirected to the pane, so existing links keep working; a link to a pane that is not there falls back to the plugin's Extensions row, then General. - TUI. The pane gets its own entry in the Settings sidebar, before Plugin Settings, mounting your
tui_settings_widget(and your schema form, if you have one) — also when your plugin has no web settings at all. The Plugin Settings accordion skips your plugin. There is no new TUI hook. - Operators can see it. Startup logs one line listing the plugin panes in force (
Settings panes from plugins: models (thinking_modes)), so an operator can see what lengthened their sidebar.
The in-tree users are thinking_modes, whose pane is Settings → Models
(catalog), and the agent_instructions builtin,
whose pane is Settings → Custom instructions
(catalog).
Admin Panels
Plugins can contribute panels to the /admin hub page by declaring admin-panel as a placement and adding a widget with placement: "admin-panel".
Manifest Configuration
{
"plugin_id": "my_plugin",
"name": "My Plugin",
"version": "1.0.0",
"event_types": ["plugin.my_plugin.completed"],
"ui": {
"bundle": "index.js",
"sdk_version": "1.0",
"custom_elements": ["x-my-plugin-admin"],
"placements": ["admin-panel"],
"widgets": [{
"id": "my_admin_panel",
"element": "x-my-plugin-admin",
"title": "My Plugin Settings",
"placement": "admin-panel",
"priority": 100
}]
}
}
Admin Panel Custom Element
Admin panel elements receive a config property (same pattern as welcome widgets) with optional endpoint and refresh configuration:
class MyPluginAdmin extends HTMLElement {
private _shadowRoot: ShadowRoot;
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: "open" });
}
set config(value: { refresh_interval_seconds?: number; summary_endpoint?: string; detail_endpoint?: string }) {
// Use config for API endpoints or refresh intervals
}
connectedCallback() {
this.render();
}
render() {
this._shadowRoot.innerHTML = `
<style>${getBaseStyles()}</style>
<div class="admin-panel">
<p>Plugin admin content here</p>
</div>
`;
}
}
if (!customElements.get("x-my-plugin-admin")) {
customElements.define("x-my-plugin-admin", MyPluginAdmin);
}
The admin hub automatically wraps each admin panel widget in a <section> with the widget's title as a heading. Widgets are sorted by priority (lower values appear first).
Ingestion Panels
Plugins can contribute panels inside the Ingestion page (/admin/ingest) — below the built-in full-ingestion and per-repo sections — by declaring ingestion-panel as a placement and adding a widget with placement: "ingestion-panel". Use this (instead of admin-panel) when your panel is conceptually part of ingestion/indexing and belongs next to those controls rather than on the standalone admin hub.
Manifest Configuration
Identical to an admin panel, only the placement string differs:
{
"ui": {
"custom_elements": ["x-my-plugin-ingestion"],
"placements": ["ingestion-panel"],
"widgets": [{
"id": "my_ingestion_panel",
"element": "x-my-plugin-ingestion",
"title": "My Plugin Indexing",
"placement": "ingestion-panel",
"priority": 100
}]
}
}
Custom Element
Authoring is the same as an admin panel: the element receives the same config property (refresh_interval_seconds, summary_endpoint, detail_endpoint), and the host wraps each widget in a titled <section>, sorted by priority.
Both placements are rendered by the same reusable host — <PluginPanelHost placement=… /> backed by the usePluginPanels(placement) hook (ui/src/components/PluginPanelHost.tsx, ui/src/hooks/usePluginPanels.ts). AdminPage mounts placement="admin-panel"; IngestPage mounts placement="ingestion-panel". Adding a host to a new core page is just <PluginPanelHost placement="…" /> plus a new value in ExtensionPlacement (ui/src/types/api.ts).
Gating
The Ingestion page is already an admin-only route, so an ingestion-panel section is only visible to admins. This is visibility only — keep enforcing permissions on your plugin's own endpoints server-side (e.g. require_permission("admin:*")); the placement does not gate API calls.
The branch_switching plugin's branch-overlay panel is the canonical example (plugins/branch_switching/plugin.py ui_manifest; design rationale in doc/features/branch-overlay-admin-design.md §5, "Option C").
Full Pages
A widget lives inside someone else's layout. When your plugin needs a whole
screen — a browser, a dashboard, a management console — declare a page
instead. Each entry in ui.pages mounts your custom element at its own SPA
route:
"ui": {
"bundle_url": "/ui/extensions/plugins/my_plugin/index.js",
"custom_elements": ["x-my-plugin-browser"],
"pages": [
{
"page_id": "browser",
"path": "browser", # relative, no leading slash
"title": "Browser", # shown as the page heading
"custom_element": "x-my-plugin-browser",
},
],
}
| Field | Description |
|---|---|
page_id | Stable identifier for the page within your plugin |
path | Route segment, relative — the host mounts it under /plugins/<plugin_id>/ |
title | Human-readable page title |
custom_element | Tag from your bundle to mount as the page body |
The example above is reachable at /plugins/my_plugin/browser. Routing goes
through App.tsx's /plugins/:pluginId/* entry, so you add no React code and
touch no core routing.
Carry page state in the URL hash, not in component state, so deep links from
a transcript card restore the full view:
/plugins/workspace_files/repos#?repo=alpha&path=docs/report.md
workspace_files (repo browser), agentic_memory, log_collection
and user_feedback all ship pages this way.
Several pages, one element. When several ui.pages entries name the same
custom_element, the host keeps that one instance while the user moves between
them and only updates its page-id attribute; a different element remounts.
So a plugin can run its own in-app router: history.pushState plus a
dispatched popstate changes the URL, the host re-matches the page, and your
element keeps its state. goals does this (ui/plugins/goals/src/paths.ts).
Pages are not gated for you. The route renders for any authenticated user;
enforce authorization on the plugin API endpoints the page calls, exactly as
with admin panels.
Chat Header Widgets
Plugins can contribute small components to the chat header. The header is a single responsive action bar: every item — native actions and plugin widgets alike — is placed by the same priority-ordered overflow pass, which keeps as many items inline as fit the available width and collapses the rest into the overflow (⋮) menu.
Each chat-header widget declares two layout fields:
priority— higher = more important. Items are laid out left-to-right by descending priority, and when space runs out the lowest-priorityautoitems are the first to collapse into the menu. Defaults to100. The core inline band is spaced by100so a new action can slot in without reshuffling the rest: trial badge1000(pinned, leftmost), then Preview900(only with a pinned app or a configured dev server), Push800, Workspace750, Focus700, Control Room600, Share500, Repos300, Goals200, Settings50(inline actions); admin-200(menu item). A widget that omitsprioritytakes the default100, which lands in the reserved gap between Goals (200) and Settings (50).collapse— the collapse intent:"pinned": always inline, never collapsed (e.g. the trial badge)"menu": always in the overflow menu"auto"(default): inline while there is room, otherwise overflows into the menu
Ordering inside the menu. priority is a single axis shared by the inline row and the menu — there is no separate "menu priority". The menu is one list that merges always-"menu" items with any auto items that happened to overflow for lack of space, then sorts the whole thing by descending priority (highest at the top). So a "menu" widget left at the default 100 will interleave with — and race against — whatever auto items got pushed out of the inline row on a given viewport. For a "menu" widget, prefer a negative priority so it settles near the bottom of the menu, below the space-driven overflow and in a stable spot. Use a high positive priority only when you deliberately want it near the top of the menu, accepting that it will sit among the overflowed auto items. Native items bracket the range: the user button anchors the top at 10000, logout the bottom at -10000.
Manifest Configuration
Add a widget with placement: "chat-header" in ui.widgets. (Declaring "chat-header" in ui.placements is optional and purely informational — discovery is driven by ui.widgets[].)
{
"plugin_id": "my_plugin",
"name": "My Plugin",
"version": "1.0.0",
"event_types": ["plugin.my_plugin.completed"],
"ui": {
"bundle": "index.js",
"sdk_version": "1.0",
"custom_elements": ["x-my-header-status"],
"placements": ["chat-header"],
"widgets": [{
"id": "header_status",
"element": "x-my-header-status",
"title": "Status Indicator",
"placement": "chat-header",
"priority": 100,
"collapse": "auto"
}]
}
}
A widget that a workspace view of the same plugin replaces may declare superseded_by_view: "<view widget_id>": while the workspace pane is on and that view is available, the host does not draw it. See workspace-views.md.
When a widget is relocated between the inline row and the menu, the host sets a display-mode attribute ("inline" or "menu") on the custom element so it can adapt its rendering (e.g. show a label next to the icon in the menu).
Custom Element Properties
The host sets the following properties on the custom element:
| Property | Type | Description |
|---|---|---|
conversationId | string | Current conversation ID |
locale | string | Current UI locale (e.g., "en", "hu") |
widgetId | string | Widget ID from the manifest |
pluginId | string | Plugin ID |
Example Implementation
class MyHeaderStatus extends HTMLElement {
private _shadowRoot: ShadowRoot;
private _conversationId?: string;
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: "open" });
}
set conversationId(value: string | undefined) {
this._conversationId = value;
this.render();
}
connectedCallback() {
this.render();
}
render() {
this._shadowRoot.innerHTML = `
<style>
:host { display: inline-flex; align-items: center; }
.badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 12px;
background: var(--color-bg-inset);
border: 1px solid var(--color-border);
font-size: 12px;
color: var(--color-text-secondary);
}
.dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--color-primary);
}
</style>
<div class="badge">
<span class="dot"></span>
Connected
</div>
`;
}
}
if (!customElements.get("x-my-header-status")) {
customElements.define("x-my-header-status", MyHeaderStatus);
}
Multiple plugins can contribute to the header slot. They are laid out side by
side in descending priority — the highest-priority item sits leftmost, and
the lowest-priority auto items are the first to collapse into the ⋮ menu when
space runs out (ui/src/components/headerOverflow.ts).
Note: this is the opposite of
admin-panel/ingestion-panel, where
panels sort by ascending priority (lower value first). The chat header sorts
descending because therepriorityexpresses importance — what survives
inline when the bar is tight — not just position.
Message Actions
A message-actions widget renders in the small row under an assistant answer,
next to copy (ui/src/components/MessageActions.tsx). The row appears after
every completed answer, in normal and focus mode alike, so one element is
mounted per answer. Widgets sort by ascending priority.
Element context
The host sets context (a MessageActionsContext from
@codumentor/plugin-sdk) and also each field as a property of the same name,
plus widgetId, pluginId and locale:
| Field | Type | Attribute | Meaning |
|---|---|---|---|
conversationId | string? | conversation-id | The conversation |
turnId | string? | turn-id | Root turn id (the user message id), when known |
assistantMessageId | string? | assistant-message-id | The answer's message id |
assistantContent | string | — | The turn's final assistant text |
isLatestTurn | boolean | latest-turn (present when true) | This row is under the conversation's latest answer |
turnOutcome | `"completed" \ | "cancelled" \ | "error"` |
canSend | boolean | can-send (present when true) | The viewer can send into this conversation from here |
- Latest and responding. At most one row is the latest, and only while nothing is in flight: the latest row is not rendered while the conversation is responding or a send is pending. When a turn starts, that element is removed (normal mode) or every row is removed (focus mode), so a widget that shows only on the latest row needs no separate "responding" signal. A trailing turn with no answer (cancelled before any text) has no row, and the answer above it is not the latest either.
- Outcome.
cancelledwhen the turn carries a cancel notice;errorwhen it is the latest turn and ended withturn.failed. An earlier failed turn reportscompleted, because only the latest turn's failure is known. A turn waiting on an approval is still in flight, so it has no latest row. - Can send. False in the admin chat viewer and in a conversation from another folder (the composer is blocked there). Share views and subagent transcripts do not render this row at all.
isLatestTurn,turnOutcomeandcanSendcan change while the element is mounted. The host updates the properties and attributes in place and assigns a newcontextobject, so acontextsetter (orattributeChangedCallbackon the attributes) sees each change. The other fields remount the element.
To send a user turn from a widget, dispatch the window event
codumentor:send-chat-message with { conversation_id, text }. By default the
composer is cleared, as when the user presses Send; add preserve_draft: true
to leave a half-typed draft alone.
Composer Controls
The composer row — the one with the textarea and the send button — is two
placements, not one, split by what a control is rather than where it happens
to sit:
| Placement | Side | It answers | Overflow |
|---|---|---|---|
composer-intent | left of the textarea | what this turn does | into the + menu |
composer-input | right of the textarea | how I am entering this message | icon-only, then gone |
The split exists because one overflow policy cannot serve both. A mode picker
works fine as a dropdown row: you open it, you choose, you close. A
press-and-hold microphone does not — so the input cluster is never put in a
menu. Which side a new control belongs on therefore stops being a judgement
call.
Both clusters go through one measured pass over their union, so the globally
least important control on the row collapses first regardless of side; only what
happens to it comes from its own placement.
Layout fields
priority— higher = more important, exactly aschat-header: laid out furthest from the textarea, and last to collapse. Defaults to50. Reference points among the native controls: thinking chip60, speak-replies40(intent); push-to-talk50, voice conversation30, native dictation20(input). On the input side the highest priority renders nearest the send button, in the thumb zone, so the visual order there is the reverse of the priority order.collapse— what happens when the row runs out of room:"pinned": always on the row. It guarantees presence, never a label — a pinned control still degrades to icon-only when the budget is tight."menu": always in the+menu.composer-intentonly; an input control that declares it is simply absent, since that cluster has no menu."auto"(default): on the row while there is room, then icon-only, then demoted — into the menu forcomposer-intent, out of sight forcomposer-input."hide": likeauto, but with no menu fallback. For a control that is a redundant convenience (native dictation is one) rather than the only way to reach something.group(composer-inputonly) — an optional merge group. Accepted today so a manifest can declare it; a single merged trigger for the group is not implemented yet.
The three display modes
There is no way for a widget to demand a label. Instead the host sets
display-mode on the custom element and the widget must render sanely in
all three:
display-mode | What the host is asking for |
|---|---|
"inline" | The full trigger — icon and label |
"compact" | Icon only. Presence beats labels when the row is tight |
"menu" | A labelled row inside the + dropdown |
Presence comes first: the host places every control compact, sees who fits, then
hands labels back from the highest priority down. A control that renders nothing
at "compact" will simply vanish at a width where it could have stayed.
The element is moved, never re-created
A composer widget is instantiated once and relocated between the row and
the menu — and it stays alive, detached, while the menu is shut. That is what
lets a demoted widget go on tracking the state it will show when the user
finally opens the +.
Subscribe in the
constructor, notconnectedCallback. A widget demoted
into a closed menu has no DOM at all, soconnectedCallbackhas not run and
will not run again until the menu opens. This is the same rule
chat-header widgets follow, and for the same reason.
Menu behaviour
Rows in the + close the menu when clicked, which is what an entry that acts
once and is done wants. A widget that owns a toggle, a stepper, or anything with
more than one hit target opts out by putting data-keep-open on itself — the
host reads it at click time, so a widget may change its mind — and then closes
the menu itself when it is finished.
The dropdown is a role="menu" whose native rows are role="menuitem", walked
with the arrow keys. A plugin's row is not given that role: the host cannot
activate a control that lives inside your shadow root, so keyboard access is
yours to provide — render a focusable element (a <button>) in an open shadow
root and it is reachable by Tab.
The tray, and the state a control publishes
Demotion would otherwise be lossy: a control pushed into a shut + takes its
state with it, and the user has to open a menu to find out that replies are
being read aloud or which mode this turn runs at. The composer tray — an
in-flow, wrapping row directly above the textarea — is where that state goes on
being readable with nothing opened.
The host draws the chip, never the widget. A widget is one element and
cannot be in two DOM places at once, so drawing its own chip would cost it the
"moved, never re-created" guarantee above. Instead it declares its state, and
the host renders it — which also means every plugin's chip is styled the same.
Publish in either spelling. Both carry the same fields:
| Field | Attribute | Meaning |
|---|---|---|
| label | data-state-label | Short text, glyph included if you want one (◐ Slow · High). No label ⇒ nothing published. |
| tone | data-state-tone | default (the host stays quiet) \ |
| count | data-state-count | A badge, rendered only above 1. |
| actionable | data-state-actionable | Optional chip activation opt-in: only boolean true in event detail or the exact attribute value "true" enables it. Omitted or false stays passive. |
| progress | data-state-progress | Activity: 0..1, drawn as a thin bar along the chip's bottom edge. Omitted ⇒ no bar (indeterminate). Values are clamped to 0..1; a non-numeric value counts as omitted. |
| detail | data-state-detail | Activity: one line of figures (12/80 · 34/120 MB · ~2 min), shown beside the label where there is room and at the top of the popover. |
| actions | data-state-actions | Activity: a JSON array of {id, label?, disabled?} (bare strings are accepted as ids). The host draws the buttons in the popover. |
| compact label | data-state-compact-label | The label on narrow (mobile) widths, e.g. 📁 · 42%. Falls back to label. |
// Attributes — read the moment the host creates your element, so this is the
// spelling that carries *initial* state.
this.setAttribute("data-state-label", "3 folders");
this.setAttribute("data-state-tone", "active");
this.setAttribute("data-state-count", "3");
// Or an event on yourself, for an update you already have in hand.
this.dispatchEvent(new CustomEvent("codumentor:composer-state", {
detail: { label: "3 folders", tone: "active", count: 3 },
}));
Two rules follow from the contract:
defaultis silence. A chip appears only for a non-default state, which is what lets the tray cost exactly zero pixels on a conversation with nothing to say. Publishdefault(or no label) when you are sitting at the value the user would have got anyway.- A chip is drawn only while your control is off the row. On the row your own trigger is showing; a chip beside it would be the same string twice.
Opting in to chip activation
Chips are informational and passive by default. A plugin that can handle
activation opts in with data-state-actionable="true" or actionable: true in
its codumentor:composer-state detail. String "true" in event detail, an empty
attribute, and other truthy values do not opt in.
When the user activates an actionable chip, the host first opens the overflow
(+) menu, then dispatches COMPOSER_ACTIVATE_EVENT
("codumentor:composer-activate") directly on the existing plugin element
with detail { source: "chip" }. The element is not recreated. Listen on the
element itself and open or focus your own control; the host does not synthesize
a click inside your shadow root.
import { COMPOSER_ACTIVATE_EVENT } from "@codumentor/plugin-sdk";
// Install once, for example in your element's constructor.
this.addEventListener(COMPOSER_ACTIVATE_EVENT, (event) => {
const { source } = (event as CustomEvent<{ source: "chip" }>).detail;
if (source === "chip") {
this.shadowRoot?.querySelector<HTMLButtonElement>("button")?.focus();
}
});
this.setAttribute("data-state-actionable", "true");
Removing the attribute or publishing state without actionable: true makes the
chip passive again. Attribute and event updates remain last-writer-wins.
A control that needs a genuine custom in-flow row rather than a chip — something
InputAttachments-shaped — declares placement: "composer-tray" and renders
into the row itself.
Activity chips: tray widgets that publish state
A composer-tray widget that publishes a label gets a host-drawn chip in
the tray, for as long as the label is there. This is how long-running work
shows (design client-fs-transfers §3.5, D8): a copy, an upload, a save-back.
The host draws every such chip the same way: label, tone, the progress bar and
the detail.
- Passive chip (the default): clicking opens a popover. The popover shows the detail, the action buttons, and your element itself as the popover content. The host keeps the element in a stable node and only hides and shows it, so render whatever the user should see on click (names, file lists, your own buttons) into your shadow root. To close the popover from inside, dispatch
codumentor:composer-popover-closeon yourself. - Action buttons dispatch
COMPOSER_ACTIVATE_EVENTon your element with{ source: "action", action: id }, synchronously inside the click. - Actionable chip: with
data-state-actionable="true"the chip is a button with no popover. A click dispatches{ source: "chip" }, still inside the user gesture, so calls such asrequestPermission()or a file picker work from the handler. - No label means no chip. The element then renders in the row as before.
this.setAttribute("data-state-tone", "active");
this.setAttribute("data-state-progress", "0.42");
this.setAttribute("data-state-detail", "12/80 · 34/120 MB · ~2 min");
this.setAttribute("data-state-actions", JSON.stringify([{ id: "cancel", label: "Cancel" }]));
this.setAttribute("data-state-compact-label", "📁 · 42%");
this.setAttribute("data-state-label", "📁 Project · copying"); // last: the label makes the chip
this.addEventListener(COMPOSER_ACTIVATE_EVENT, (e) => {
const d = (e as CustomEvent).detail;
if (d.source === "action" && d.action === "cancel") void cancelJob();
});
The first producer is the client_fs folder chip
(ui/plugins/client_fs/src/folder-chip.ts).
What the + says on your behalf
The tray carries the label; the + carries the fact that your control is in
there. When the row runs out of space and pushes controls into the menu, the
trigger grows a dot — a count once it is holding more than one, and the same
number in its accessible name, since a dot is invisible to a screen reader. Your
published tone colours it: the loudest one among everything demoted wins.
Two consequences worth knowing:
- A
collapse: "menu"widget never marks the trigger. It declared the menu its home, so nothing was lost by it being there, and a dot that is always present would say nothing. Only controls the row had to give up are counted. - The dot appears even when you published nothing. That is the case it exists for:
defaultis silence in the tray, so without it a control could be demoted with no trace at all. You do not have to publish state to stay discoverable — publishing is what upgrades the dot to a readable chip.
The tray sorts by ascending priority (left to right, like panels), the
opposite of the two row clusters beside it. The clusters sort descending
because therepriorityexpresses importance, which is what decides who
survives when the row is tight; the tray never collapses, so there it is only
position.
Manifest configuration
{
"widgets": [{
"widget_id": "turn_scope",
"title": "Turn scope",
"placement": "composer-intent",
"priority": 45,
"collapse": "auto",
"custom_element": "x-my-turn-scope"
}]
}
The custom element receives the same properties as a header widget
(conversationId, locale, widgetId, pluginId) plus the display-mode
attribute above.
UI Component Guidelines
- Always escape user content: Use
escapeHtml()for any dynamic text - Support dark mode: Use CSS custom properties, not hardcoded colors
- Use Shadow DOM: Provides style isolation from the host
- Handle all states: Render appropriately for
pending,success,error - Keep bundles small: The SDK is ~15KB; aim for <50KB total per plugin
Settings action widgets
Plugins may declare ui.widgets[] entries with placement: "settings-panel"
to add actions to the Settings sidebar, before About. These are distinct from
settings_widget forms and root settings_pane sections. The host loads each
custom element on demand when Settings opens, ordered by descending priority
then plugin/widget ID, and supplies locale, plugin-id, widget-id, and the
active conversation-id (omitted without a conversation). The bug-report plugin
uses this surface to open its report dialog without a main-menu entry.