# KPI tiles

Two to six headline numbers, each with its change and a sparkline. The agent answers in a sentence; the card carries the numbers.

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

Two to six headline numbers, each with its change and a sparkline. The agent answers in a sentence; the card carries the numbers.

## When to use it

**Use it when:** The user asks how something is doing and the answer is 2–6 headline numbers (totals, rates, counts), each with a change vs a period.

**Use something else when:** One number only (answer in text). A trend over time is the point (chart card). Many rows of the same metric (records list / table).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | As soon as the card shows. The agent goes on. |

## States

Besides its data, the template draws these as itself, with `mountState()`. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | While the card loads again in place, for example after Try again. While execute runs, the SDK shows its own loader. |
| Empty | execute found nothing to show. The card says so and the agent explains why. |
| Error | execute returned the failure as data, so the agent can explain it. Try again loads in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### KpiTilesData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `metrics` | `KpiMetric[]` | 2–6 tiles; more are cut. |
| `footnote` (optional) | `string` |  |
| `link` (optional) | `{ label: string; href: string }` |  |

### KpiMetric

| Field | Type | Notes |
| --- | --- | --- |
| `label` | `string` |  |
| `value` | `number \| string` |  |
| `format` (optional) | `NumberFormat` |  |
| `delta` (optional) | `{ value: number; good?: boolean; vs?: string }` | Change in percent. good: false when up is bad (costs, churn); default: up is good. |
| `trend` (optional) | `number[]` | Recent values, oldest first, for the sparkline. |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/kpi-tiles.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/kpi-tiles.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/kpi-tiles.component.ts), [JavaScript](/ui-catalog/files/js/usage/kpi-tiles.component.js)
- kpi-tiles: [TypeScript](/ui-catalog/files/ts/kpi-tiles.ts), [JavaScript](/ui-catalog/files/js/kpi-tiles.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/show_pipeline_kpis/index.ts"
// agent/actions/show_pipeline_kpis/index.ts: a hosted action.
// Copy the template (kpi-tiles.ts) and fs-kit.ts into agent/ui/.

type Result = KpiTilesData | { error: string };

export async function execute(args: { quarter?: string }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch(`/api/pipeline/summary?quarter=${args.quarter ?? "current"}`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The pipeline report didn't load (${res.status}). Nothing changed.` };
  const s = await res.json();
  // Return every number the card shows: the agent reads this, not the card.
  return {
    title: "Pipeline this quarter",
    subtitle: s.periodLabel,
    metrics: [
      { label: "Open pipeline", value: s.open, format: { style: "currency" }, delta: { value: s.openDelta, vs: "vs last quarter" }, trend: s.openTrend },
      { label: "Win rate", value: s.winRate, format: { style: "percent" }, delta: { value: s.winRateDelta, vs: "vs last quarter" } },
    ],
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Pipeline this quarter", state: { kind: "error", text: result.error } });
  } else if (result.metrics.length === 0) {
    mountState({ root, head, title: result.title, state: { kind: "empty", title: "No pipeline yet this quarter", text: "Deals show up here once they have an amount." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

```js title="agent/actions/show_pipeline_kpis/index.js"
// agent/actions/show_pipeline_kpis/index.js: a hosted action.
// Copy the template (kpi-tiles.ts) and fs-kit.ts into agent/ui/.

export async function execute(args, ctx) {
  const res = await ctx.fetch(`/api/pipeline/summary?quarter=${args.quarter ?? "current"}`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The pipeline report didn't load (${res.status}). Nothing changed.` };
  const s = await res.json();
  // Return every number the card shows: the agent reads this, not the card.
  return {
    title: "Pipeline this quarter",
    subtitle: s.periodLabel,
    metrics: [
      { label: "Open pipeline", value: s.open, format: { style: "currency" }, delta: { value: s.openDelta, vs: "vs last quarter" }, trend: s.openTrend },
      { label: "Win rate", value: s.winRate, format: { style: "percent" }, delta: { value: s.winRateDelta, vs: "vs last quarter" } },
    ],
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result, ctx) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Pipeline this quarter", state: { kind: "error", text: result.error } });
  } else if (result.metrics.length === 0) {
    mountState({ root, head, title: result.title, state: { kind: "empty", title: "No pipeline yet this quarter", text: "Deals show up here once they have an amount." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page action handler: the template runs in your page.

type Result = KpiTilesData | { error: string };

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    show_pipeline_kpis: {
      // Return every number the card shows: the agent reads this, not the card.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ quarter }: { quarter?: string }): Promise<Result> =>
        loadPipelineKpis(quarter).catch(() => ({ error: "The pipeline report didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result: Result): void => {
          if (!("error" in result)) return void mount({ root: host, head: header, data: result, api: { displayed: () => shown(result) } });
          mountState({
            root: host, head: header, title: "Pipeline this quarter",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the tiles (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Pipeline this quarter", state: { kind: "loading", label: "Loading pipeline…" } });
                show(await loadPipelineKpis().catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page action handler: the template runs in your page.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    show_pipeline_kpis: {
      // Return every number the card shows: the agent reads this, not the card.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ quarter }) =>
        loadPipelineKpis(quarter).catch(() => ({ error: "The pipeline report didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result) => {
          if (!("error" in result)) return void mount({ root: host, head: header, data: result, api: { displayed: () => shown(result) } });
          mountState({
            root: host, head: header, title: "Pipeline this quarter",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the tiles (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Pipeline this quarter", state: { kind: "loading", label: "Loading pipeline…" } });
                show(await loadPipelineKpis().catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

### kpi-tiles

```ts title="agent/ui/kpi-tiles.ts"
// Template: kpi-tiles. A read-only chat card with 2–6 headline numbers, each with a trend.

export const meta = {
  id: "kpi-tiles",
  title: "KPI tiles",
  surface: "card",
  kind: "read-only",
  mobile: "same",
  whenToUse: "The user asks how something is doing and the answer is 2–6 headline numbers (totals, rates, counts), each with a change vs a period.",
  whenNotToUse: "One number only (answer in text). A trend over time is the point (chart card). Many rows of the same metric (records list / table).",
};

const CSS = `
.fsk-kpi .fsk-kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(132px, 1fr)); gap: 8px; }
.fsk-kpi .fsk-kpi-tile {
  position: relative; display: flex; flex-direction: column; gap: 6px; min-width: 0;
  padding: 12px 12px 0; border-radius: var(--k-r-md);
  background: var(--k-sunken); border: 1px solid transparent; overflow: hidden;
  transition: border-color .15s, background .15s;
}
.fsk-kpi .fsk-kpi-tile:hover { border-color: var(--k-muted-border); background: var(--k-paper); }
.fsk-kpi .fsk-kpi-label { font-size: .86em; color: var(--k-text-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fsk-kpi .fsk-kpi-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; min-height: 20px; }
.fsk-kpi .fsk-kpi-value { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 1.72em; font-weight: 600; letter-spacing: -0.02em; line-height: 1.1; }
.fsk-kpi .fsk-delta { display: inline-flex; align-items: center; gap: 2px; font-size: .79em; font-weight: 600; padding: 1px 6px 1px 4px; border-radius: 999px; }
.fsk-kpi .fsk-delta--good { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-kpi .fsk-delta--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-kpi .fsk-delta--flat { color: var(--k-text-2); background: var(--k-hover); }
.fsk-kpi .fsk-kpi-vs { font-size: .79em; color: var(--k-text-2); }
.fsk-kpi .fsk-spark { display: block; width: calc(100% + 24px); height: 34px; margin: 2px -12px 0; color: var(--k-primary); }
.fsk-kpi .fsk-kpi-tile--bad .fsk-spark { color: var(--k-error); }
.fsk-kpi .fsk-kpi-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 12px; font-size: .86em; color: var(--k-text-2); }
`;

export interface KpiMetric {
  label: string;
  value: number | string;
  format?: NumberFormat;
  /** Change in percent. good: false when up is bad (costs, churn); default: up is good. */
  delta?: { value: number; good?: boolean; vs?: string };
  /** Recent values, oldest first, for the sparkline. */
  trend?: number[];
}

export interface KpiTilesData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** 2–6 tiles; more are cut. */
  metrics: KpiMetric[];
  footnote?: string;
  link?: { label: string; href: string };
}

export interface KpiTilesProps {
  root: HTMLElement;
  head: StyleHost;
  data: KpiTilesData;
  api?: CardApi;
  surface?: "desktop" | "mobile";
}

/** Read-only: draws the tiles and reports "displayed", so the agent doesn't wait. */
export function mount({ root, head, data, api }: KpiTilesProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-kpi", CSS);

  const tiles = data.metrics.slice(0, 6).map((m) => {
    const d = m.delta;
    const sign = d ? Math.sign(d.value) : 0;
    const good = d ? (d.good ?? sign >= 0) : true;
    const tone = !d || sign === 0 ? "flat" : good ? "good" : "bad";
    const valueEl = h("span", { class: "fsk-kpi-value fsk-num" });
    countUp(valueEl, m.value, m.format);
    return h("div", { class: `fsk-kpi-tile${tone === "bad" ? " fsk-kpi-tile--bad" : ""}`, role: "group", "aria-label": `${m.label}: ${formatValue(m.value, m.format)}` },
      h("span", { class: "fsk-kpi-label", title: m.label }, m.label),
      valueEl,
      d && h("div", { class: "fsk-kpi-row" },
        h("span", { class: `fsk-delta fsk-delta--${tone} fsk-num` },
          sign !== 0 && icon(sign > 0 ? "up" : "down", 12), sign === 0 ? "0%" : `${Math.abs(d.value)}%`),
        d.vs && h("span", { class: "fsk-kpi-vs" }, d.vs)),
      (m.trend?.length ?? 0) > 1 ? sparkline(m.trend!, { label: `${m.label} trend` }) : h("div", { style: { height: "12px" } }));
  });

  const card = h("section", { class: "fsk fsk-card fsk-kpi", "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "chart", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    h("div", { class: "fsk-kpi-grid" }, tiles),
    (data.footnote || data.link) && h("footer", { class: "fsk-kpi-foot" },
      h("span", {}, data.footnote ?? ""),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href }, data.link.label, icon("chevron", 14))));

  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => root.replaceChildren();
}

/** The states this card draws besides its data. */
export const states: StateKind[] = ["loading", "empty", "error"];

/** Loading (four tiles of bones), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }: StateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-kpi", CSS);
  const card = stateCard({ state, cls: "fsk-kpi", icon: "chart", title, subtitle, surface, skeleton: () => skeletonTiles(4) });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, KpiTilesData> = {
  default: {
    title: "Pipeline this quarter",
    subtitle: "Q4 · updated 2 min ago",
    metrics: [
      { label: "Open pipeline", value: 1284000, format: { style: "currency" }, delta: { value: 12.4, vs: "vs Q3" }, trend: [40, 42, 41, 47, 52, 50, 58, 61, 66] },
      { label: "Win rate", value: 31.5, format: { style: "percent" }, delta: { value: -2.1, vs: "vs Q3" }, trend: [36, 35, 35, 34, 33, 34, 32, 31, 31.5] },
      { label: "Deals closing", value: 23, delta: { value: 0, vs: "same as Q3" }, trend: [20, 22, 21, 23, 22, 23, 24, 23, 23] },
      { label: "Avg. cycle (days)", value: 38, delta: { value: -8.2, good: true, vs: "faster" }, trend: [46, 45, 44, 43, 41, 40, 40, 39, 38] },
    ],
    footnote: "Owner: you · 4 teams",
    link: { label: "Open report", href: "/reports/pipeline" },
  },
};
```

```js title="agent/ui/kpi-tiles.js"
// Template: kpi-tiles. A read-only chat card with 2–6 headline numbers, each with a trend.

export const meta = {
  id: "kpi-tiles",
  title: "KPI tiles",
  surface: "card",
  kind: "read-only",
  mobile: "same",
  whenToUse: "The user asks how something is doing and the answer is 2–6 headline numbers (totals, rates, counts), each with a change vs a period.",
  whenNotToUse: "One number only (answer in text). A trend over time is the point (chart card). Many rows of the same metric (records list / table).",
};

const CSS = `
.fsk-kpi .fsk-kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(132px, 1fr)); gap: 8px; }
.fsk-kpi .fsk-kpi-tile {
  position: relative; display: flex; flex-direction: column; gap: 6px; min-width: 0;
  padding: 12px 12px 0; border-radius: var(--k-r-md);
  background: var(--k-sunken); border: 1px solid transparent; overflow: hidden;
  transition: border-color .15s, background .15s;
}
.fsk-kpi .fsk-kpi-tile:hover { border-color: var(--k-muted-border); background: var(--k-paper); }
.fsk-kpi .fsk-kpi-label { font-size: .86em; color: var(--k-text-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fsk-kpi .fsk-kpi-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; min-height: 20px; }
.fsk-kpi .fsk-kpi-value { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 1.72em; font-weight: 600; letter-spacing: -0.02em; line-height: 1.1; }
.fsk-kpi .fsk-delta { display: inline-flex; align-items: center; gap: 2px; font-size: .79em; font-weight: 600; padding: 1px 6px 1px 4px; border-radius: 999px; }
.fsk-kpi .fsk-delta--good { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-kpi .fsk-delta--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-kpi .fsk-delta--flat { color: var(--k-text-2); background: var(--k-hover); }
.fsk-kpi .fsk-kpi-vs { font-size: .79em; color: var(--k-text-2); }
.fsk-kpi .fsk-spark { display: block; width: calc(100% + 24px); height: 34px; margin: 2px -12px 0; color: var(--k-primary); }
.fsk-kpi .fsk-kpi-tile--bad .fsk-spark { color: var(--k-error); }
.fsk-kpi .fsk-kpi-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 12px; font-size: .86em; color: var(--k-text-2); }
`;

/** Read-only: draws the tiles and reports "displayed", so the agent doesn't wait. */
export function mount({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-kpi", CSS);

  const tiles = data.metrics.slice(0, 6).map((m) => {
    const d = m.delta;
    const sign = d ? Math.sign(d.value) : 0;
    const good = d ? (d.good ?? sign >= 0) : true;
    const tone = !d || sign === 0 ? "flat" : good ? "good" : "bad";
    const valueEl = h("span", { class: "fsk-kpi-value fsk-num" });
    countUp(valueEl, m.value, m.format);
    return h("div", { class: `fsk-kpi-tile${tone === "bad" ? " fsk-kpi-tile--bad" : ""}`, role: "group", "aria-label": `${m.label}: ${formatValue(m.value, m.format)}` },
      h("span", { class: "fsk-kpi-label", title: m.label }, m.label),
      valueEl,
      d && h("div", { class: "fsk-kpi-row" },
        h("span", { class: `fsk-delta fsk-delta--${tone} fsk-num` },
          sign !== 0 && icon(sign > 0 ? "up" : "down", 12), sign === 0 ? "0%" : `${Math.abs(d.value)}%`),
        d.vs && h("span", { class: "fsk-kpi-vs" }, d.vs)),
      (m.trend?.length ?? 0) > 1 ? sparkline(m.trend, { label: `${m.label} trend` }) : h("div", { style: { height: "12px" } }));
  });

  const card = h("section", { class: "fsk fsk-card fsk-kpi", "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "chart", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    h("div", { class: "fsk-kpi-grid" }, tiles),
    (data.footnote || data.link) && h("footer", { class: "fsk-kpi-foot" },
      h("span", {}, data.footnote ?? ""),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href }, data.link.label, icon("chevron", 14))));

  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => root.replaceChildren();
}

/** The states this card draws besides its data. */
export const states = ["loading", "empty", "error"];

/** Loading (four tiles of bones), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-kpi", CSS);
  const card = stateCard({ state, cls: "fsk-kpi", icon: "chart", title, subtitle, surface, skeleton: () => skeletonTiles(4) });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    title: "Pipeline this quarter",
    subtitle: "Q4 · updated 2 min ago",
    metrics: [
      { label: "Open pipeline", value: 1284000, format: { style: "currency" }, delta: { value: 12.4, vs: "vs Q3" }, trend: [40, 42, 41, 47, 52, 50, 58, 61, 66] },
      { label: "Win rate", value: 31.5, format: { style: "percent" }, delta: { value: -2.1, vs: "vs Q3" }, trend: [36, 35, 35, 34, 33, 34, 32, 31, 31.5] },
      { label: "Deals closing", value: 23, delta: { value: 0, vs: "same as Q3" }, trend: [20, 22, 21, 23, 22, 23, 24, 23, 23] },
      { label: "Avg. cycle (days)", value: 38, delta: { value: -8.2, good: true, vs: "faster" }, trend: [46, 45, 44, 43, 41, 40, 40, 39, 38] },
    ],
    footnote: "Owner: you · 4 teams",
    link: { label: "Open report", href: "/reports/pipeline" },
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
