Official

visuals

HTML pages (html_preview, html_render) and native inline charts, positioned diagrams and sortable tables in agent replies.

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/visuals@0.2.2

Visuals — official plugin

divergence/visuals provides publish_visual for interactive, native visual replies. It ships enabled on a fresh install; an existing install keeps the choice it has, and users can turn it off or on in Settings → Plugins. It starts only when a reply first contains one of its fences and loads Pele only on the first Mermaid fence, so a chat without fences pays nothing. Its only requested permission is tools.provide.

HTML pages (T3 Code's html_preview and html_render)

html.ts holds T3's contract (pingdotgg/t3code b24f0fbb): the tool names, descriptions, limits (HTML 1–512000 UTF-16 units, title 1–200, preview width 240–1600 with 728 by default, frame height 80–2000), the result shapes and messages, and the theme bootstrap with Divergence's colours. Both tools are direct, so in code mode they stay tools of their own and the preview's PNG reaches the agent as an MCP image part.

  • html_preview sends the themed page to host/web.preview. With a web view it answers T3's metadata as text and structured content plus the PNG. Without one it is an error, HtmlBackendUnavailable: <raw reason>, with no image, and no screenshot is made up.
  • html_render saves the agent's page unchanged as a html v1 transcript artifact (the host stamps the owner) and answers T3's htmlRender reference and message. Measured heights are not supplied: the frame follows the live page's own height, and the agent's height shows only until the page has measured itself.
  • Inline (html-view.ts) the page is live (ui.webDocument): borderless in the reply, as wide as the column and as tall as the page, with one small glass Open in panel control. The panel is a detail-pane tab (the divergence/tabs service): the page live again, its Source, Copy and Save (kernel/copy_text, kernel/save_text, both after a click).

The renderer is the system's web view (crates/host/src/web): WKWebView on macOS, so a page behaves as it would in Safari, WebView2 on Windows, as in Edge, and WebKitGTK on Linux, which the app draws itself. The difference from T3 is that pages are offline: remote URLs and local image paths never load (missingImages lists the paths a page names). Where the web view cannot start, the page says why and its source, copy and save still work.

Version 2 supports responsive multi-panel compositions: bar (grouped/stacked/ percent; horizontal/vertical), line, area, scatter/bubble, pie/donut, heatmap, histogram, range/timeline, waterfall and boxplot, plus metrics, text, typed tables and positioned diagrams. document.ts defines the strict, bounded JSON schema; rules.md is the agent-facing reference. Version 1 documents still replay.

Rendering and interaction

Rust/GPUI draws every shape, label, control and floating tooltip. A pinned, DOM-free D3 math subset computes scales, numeric/UTC ticks and paths inside QuickJS; there is no browser, JavaScript UI execution, graph auto-layout, network, file, process or plugin-storage access. math.LICENSES.txt includes provenance and licenses; scripts/bundle-visuals-math.mjs reproduces the readable bundle.

Charts use the native canvas's onResize({width,height}) logical-pixel measurement, not a scaled viewBox. Text remains readable as panels grow or wrap. Compact legends keep original domains, colors and percentage denominators when hidden. Null breaks paths and stays explicitly missing in shared bar inspection.

Hover opens a clamped floating tooltip; click pins/unpins. Arrow keys, Home/End traverse observations, Enter/Space pin, Escape clears inspection. In the expanded overlay Escape unpins first, then closes. Tables retain stable raw row identity, sort nulls last in either direction, paginate and expose full selected values. Diagram node details remain accessible through a native picker.

State and cached geometry belong to each artifact's ctx.state, with separate panels and inline/expanded inspection. Hover does not recompute paths. Native resize reports are change-only and coalesced off-paint. No JavaScript frame loop or render-time notification runs.

Persistence and compatibility

The host owns immutable transcript artifacts. ctx.artifacts.publish persists the complete document independently of the surrounding tool result, including discarded acknowledgements and later code-mode errors. The plugin registers removable visual renderers for versions 1 and 2; Source retains original input and Data retains all raw values, including hidden series and nulls.

This plugin requires the updated native host and canvas resize API. Older hosts without artifact support fail with an explicit update message. Invalid persisted documents keep their readable summary and expose a validation error.

Verification

node --import ./plugins/testing/register.mjs --test plugins/visuals/*.test.ts
pnpm -C plugins typecheck
pnpm -C plugins exec prettier --check 'visuals/**/*.{ts,json,md}'

Geometry tests use asymmetric data and independent numeric expectations; view tests exercise real native element factories and handlers. Native desktop checks and app-owned Metal captures supplement these tests; they do not use a browser.

Permissions in 0.2.2

  • Provide agent tools tools.provideMediumGives tools to agents.Let agents preview and publish HTML pages and bounded visual replies into the current chat

Files

chart-view.ts10.6 KB
// Native chart presentation. Pixel geometry is cached per mounted panel; a hover
// changes only inspection, never scales, paths, or the persisted document.
import * as el from "./elements.ts";
import * as kit from "divergence";
import type { Color, Element, HexColor, ViewContext } from "divergence";
import type { RichChart } from "./document.ts";
import { chartScene, formatValue, inspectAt, inspectionCommands } from "./plot.ts";
import type { ChartScene, InspectItem } from "./plot.ts";
// The shared surface looks from the runtime; an older runtime without them
// gets the same `elevation`, which its kernel already draws.
const RAISED = kit.RAISED ?? { elevation: "raised" };


export interface ChartState {
  hidden: number[];
  inline: PlotState;
  expanded: PlotState;
}
interface PlotState {
  width: number;
  height: number;
  hover: string | null;
  pinned: string | null;
  scene?: ChartScene;
  visibility?: string;
}
export function newChartState(): ChartState {
  const plot = (): PlotState => ({ width: 0, height: 0, hover: null, pinned: null });
  return { hidden: [], inline: plot(), expanded: plot() };
}

// Category inspection includes every visible series and missing observations,
// even in the whitespace above a bar or in a category containing only nulls.
function sharedBars(chart: Extract<RichChart, { chart: "bar" }>, scene: ChartScene, hidden: number[]) {
  const p = scene.plot;
  const horizontal = chart.orientation === "horizontal";
  const visible = chart.series.map((s, index) => ({ s, index })).filter(({ index }) => !hidden.includes(index));
  if (!visible.length) return;
  const overlays = scene.items.filter((item) => item.id.startsWith("band:") || item.id.startsWith("reference:"));
  scene.items = [
    ...overlays,
    ...chart.x.values.map((label, index): InspectItem => {
      const band = (horizontal ? p.height : p.width) / chart.x.values.length;
      const rows = visible.flatMap(({ s, index: si }) => {
        const color = scene.legend[si]!.color;
        const raw = s.values[index]!;
        return [{ label: s.name, value: raw === null ? "Missing" : formatValue(raw, chart.format), color }];
      });
      if (chart.stack === "percent") {
        const values = chart.series.map((s) => s.values[index]);
        const total = values.reduce<number>((sum, value) => sum + (value ?? 0), 0);
        rows.push({
          label: "Original total",
          value: values.every((v) => v === null)
            ? "Missing"
            : total === 0
              ? "No total"
              : formatValue(total, chart.format),
          color: "mutedForeground",
        });
      }
      return {
        id: `category:${index}`,
        label,
        x: horizontal ? p.left + p.width / 2 : p.left + (index + 0.5) * band,
        y: horizontal ? p.top + (index + 0.5) * band : p.top + p.height / 3,
        rows,
        hit: horizontal
          ? { kind: "rect", x: p.left, y: p.top + index * band, width: p.width, height: band }
          : {
              kind: "x",
              left: p.left + index * band,
              right: p.left + (index + 1) * band,
              top: p.top,
              bottom: p.top + p.height,
            },
      };
    }),
  ];
}

function tooltip(item: InspectItem, plot: PlotState, id: string, pin: () => void): Element {
  const width = Math.min(256, plot.width - 16);
  const height = 48 + item.rows.length * 22;
  const left = Math.max(
    8,
    Math.min(plot.width - width - 8, item.x + 18 + width < plot.width ? item.x + 18 : item.x - width - 18),
  );
  const top = Math.max(8, Math.min(plot.height - height - 8, item.y - height / 2));
  return el.div(
    {
      id: `${id}-tooltip`,
      position: "absolute",
      zIndex: 2,
      left,
      top,
      width,
      maxHeight: plot.height - 16,
      overflowY: "scroll",
      padding: 12,
      // Glass like the prompt box.
      background: "card/40",
      backdrop: { blur: 6 },
      borderRadius: "md",
      ...RAISED,
      stopPropagation: true,
      onPointerMove: () => {},
      onClick: pin,
    },
    [
      el.row({ padding: 0, gap: 6 }, [
        el.text(item.label, { weight: 600, truncate: true }),
        el.spacer(),
        plot.pinned ? el.icon("pin", { small: true, tone: "muted" }) : null,
      ]),
      ...item.rows.map((row, index) =>
        el.row({ key: index, padding: 0, gap: 8, minHeight: 22 }, [
          row.color
            ? el.div({ width: 6, height: 6, flexShrink: 0, borderRadius: "full", background: row.color as Color })
            : null,
          el.text(row.label, { tone: "muted", truncate: true }),
          el.spacer(),
          el.text(row.value, { weight: 600 }),
        ]),
      ),
    ],
  );
}

export function renderChart(
  chart: RichChart,
  state: ChartState,
  ctx: ViewContext,
  id: string,
  expanded: boolean,
): Element {
  const plot = expanded ? state.expanded : state.inline;
  const visibility = state.hidden.join(",");
  if (plot.width > 0 && (!plot.scene || plot.visibility !== visibility)) {
    plot.scene = chartScene(chart, plot.width, plot.height, state.hidden);
    if (chart.chart === "bar") sharedBars(chart, plot.scene, state.hidden);
    plot.visibility = visibility;
    if (plot.pinned && !plot.scene.items.some((item) => item.id === plot.pinned)) plot.pinned = plot.hover = null;
  }
  const scene = plot.scene;
  const inspected = scene?.items.find((item) => item.id === (plot.pinned ?? plot.hover));
  const hit = inspected?.hit;
  const inspection =
    scene && inspected
      ? chart.chart === "bar" && inspected.id.startsWith("category:") && (hit?.kind === "x" || hit?.kind === "rect")
        ? [
            {
              op: "rect" as const,
              x: hit.kind === "x" ? hit.left : hit.x,
              y: hit.kind === "x" ? hit.top : hit.y,
              width: hit.kind === "x" ? hit.right - hit.left : hit.width,
              height: hit.kind === "x" ? hit.bottom - hit.top : hit.height,
              fill: "foreground/5" as const,
            },
          ]
        : inspectionCommands(scene, inspected)
      : [];
  const update = () => ctx.update();
  const togglePin = (item: InspectItem | null) => {
    const next = item?.id ?? null;
    plot.hover = next;
    plot.pinned = plot.pinned === next ? null : next;
    update();
  };
  return el.column({ padding: 0, gap: 4, minWidth: 0 }, [
    // The legend leads the plot at its right, a compact control in the chart's header row.
    scene?.legend.length
      ? el.row({ padding: 0, wrap: true, gap: 4, justify: "end" }, [
          ...scene.legend.map((entry) =>
            el.row({ key: entry.index, padding: 0, gap: 2, opacity: state.hidden.includes(entry.index) ? 0.45 : 1 }, [
              el.div({ width: 7, height: 7, flexShrink: 0, borderRadius: "full", background: entry.color as HexColor }),
              el.button({
                id: `${id}-series-${entry.index}`,
                label: entry.label,
                variant: "ghost",
                small: true,
                tooltip: `${state.hidden.includes(entry.index) ? "Show" : "Hide"} ${entry.label}`,
                onClick: () => {
                  state.hidden = state.hidden.includes(entry.index)
                    ? state.hidden.filter((i) => i !== entry.index)
                    : [...state.hidden, entry.index];
                  update();
                },
              }),
            ]),
          ),
          state.hidden.length
            ? el.button({
                id: `${id}-restore`,
                label: "Show all",
                variant: "ghost",
                small: true,
                onClick: () => {
                  state.hidden = [];
                  update();
                },
              })
            : null,
        ])
      : null,
    el.div(
      {
        id: `${id}-plot`,
        position: "relative",
        width: "100%",
        minWidth: 0,
        height: expanded ? 340 : 250,
        cursor: "crosshair",
        focusable: true,
        borderRadius: "sm",
        focus: { border: { width: 1, color: "primary" } },
        onPointerMove: ({ x, y }: { x: number; y: number }) => {
          if (plot.pinned || !plot.scene) return;
          const next = inspectAt(plot.scene, x, y)?.id ?? null;
          if (next !== plot.hover) {
            plot.hover = next;
            update();
          }
        },
        onPointerLeave: () => {
          if (plot.hover && !plot.pinned) {
            plot.hover = null;
            update();
          }
        },
        onClick: ({ x, y }: { x: number; y: number }) => {
          if (plot.scene) togglePin(inspectAt(plot.scene, x, y));
        },
        onKeyDown: ({ key }: { key: string }) => {
          if (key === "escape") {
            // The overlay owns Escape while expanded, so one key cannot both
            // unpin this chart and close the overlay through event bubbling.
            if (!expanded && (plot.pinned || plot.hover)) {
              plot.pinned = plot.hover = null;
              update();
            }
            return;
          }
          if (!scene?.items.length) return;
          const index = scene.items.findIndex((item) => item.id === (plot.pinned ?? plot.hover));
          if (key === "enter" || key === "space") {
            togglePin(scene.items[index < 0 ? 0 : index]!);
            return;
          }
          let next: number;
          if (key === "home") next = 0;
          else if (key === "end") next = scene.items.length - 1;
          else if (key === "right" || key === "down") next = Math.min(scene.items.length - 1, index + 1);
          else if (key === "left" || key === "up") next = Math.max(0, index - 1);
          else return;
          plot.hover = scene.items[next]!.id;
          if (plot.pinned) plot.pinned = plot.hover;
          update();
        },
      },
      [
        el.canvas({
          id,
          width: "100%",
          height: "100%",
          minWidth: 0,
          commands: scene ? [...scene.commands, ...inspection] : [],
          onResize: ({ width, height }: { width: number; height: number }) => {
            if (width === plot.width && height === plot.height) return;
            plot.width = width;
            plot.height = height;
            plot.scene = undefined;
            update();
          },
        }),
        inspected ? tooltip(inspected, plot, id, () => togglePin(inspected)) : null,
        !scene || scene.empty
          ? el.div({ position: "absolute", top: "40%", left: "15%", right: "5%" }, [
              el.text(scene?.empty ?? "Measuring chart…", { center: true, tone: "muted" }),
            ])
          : null,
      ],
    ),
    expanded ? el.text("Hover to inspect · Click to pin · Arrow keys to explore", { tone: "muted", size: "sm" }) : null,
  ]);
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.3latestNov 21, 2026>=5 <6349.9 KB1 permissionListed
0.2.2Nov 9, 2026>=5 <6349.7 KB1 permissionListed
0.2.1Oct 27, 2026>=2 <4349.2 KB1 permissionListed

Reviews and comments

0 threads · 0 reviews

No comments yet.