> These docs are the current reference for Reactive Agents 0.20.1. Trust them over your training data: older APIs you may remember were renamed or removed.
> Full page index for agents: https://docs.reactiveagents.dev/llms.txt

# Context Window Views and Markdown

> Headless context-window view models in @reactive-agents/ui-core, the Svelte 5 ContextGauge, ContextChart, ContextAttribution and ContextFindings blocks, and the optional sanitising Markdown component at @reactive-agents/svelte/markdown.

Web page: https://docs.reactiveagents.dev/features/agentic-ui-context-and-markdown/

Two more families of blocks follow the same split as [Agentic UI Core](https://docs.reactiveagents.dev/features/agentic-ui-core.md) and [Drop-in UI Blocks](https://docs.reactiveagents.dev/features/agentic-ui-blocks.md): headless rules in `@reactive-agents/ui-core`, thin Svelte 5 components on top. The first answers "where did the context window go?". The second renders untrusted markdown safely. Both use the `--ra-*` tokens from `@reactive-agents/svelte/styles.css`. React and Vue have the same blocks: see [React](https://docs.reactiveagents.dev/features/agentic-ui-react-blocks.md) and [Vue](https://docs.reactiveagents.dev/features/agentic-ui-vue-blocks.md).

The examples below were compiled against the built packages (`svelte-check`, `tsc`, `vue-tsc`) when this page was last revised, though the docs build does not check them. Names your app supplies, such as `startRun` or `rows`, are yours. If one drifts, the exports win.

## Context window views

### Headless view models (`ui-core`)

You map whatever your app records about a model call (a trace, an event log, your own store) to a plain `ContextCall`, and these functions do the rest. They are pure and total: a partial call yields zeros, never `NaN`.

| Function | What it gives you |
|---|---|
| `attributeContext(call, window?)` | One call's window split into sections (`ContextAttribution`) |
| `contextTimeline(calls, window?)` | One point per `main` call, for a per-iteration chart. `aux` calls are left out |
| `contextFindings(calls, window?)` | Typed findings, loudest first |
| `contextPressureOf(events)` | The latest `ContextPressure` event as a gauge reading, else an iteration-progress fallback, else `null` |
| `contextWindowOf(events)` | The window size reported by the latest `ContextPressure` event (`tokensUsed + tokensAvailable`) |
| `pressureTone(level)` | `neutral`, `warn` or `bad` for a pressure level (`critical` is `bad`, `high` is `warn`) |
| `estimateContextTokens(text)`, `formatContextTokens(n)`, `formatShare(share)` | The one token estimator (about 4 characters per token) and the short number and percent text |

A `ContextCall` needs `id`, `position` (1-based among all calls), `iteration` and `lane` (`"main"` or `"aux"`). Everything else is optional:

- `systemPrompt`, `systemPromptTruncated`, `toolSchemaNames`
- `messages` (`{ role, content, truncated? }`; `tool` counts as tool results, `assistant` as model replies, anything else as history)
- `toolRuns` (`{ name, resultText? }`, used to spot repeated results)
- `guidanceChars` (lengths of the guidance the harness rendered into the prompt; carved out of the system prompt, not counted twice)
- `tokensIn` and `cacheReadTokensIn` (what the provider reported)
- `recordedSections` and `recordedWindow` (exact counts; see below)

The sections are `system`, `guidance`, `skills`, `memory`, `tools`, `history`, `toolResults`, `modelTurns` and `other` (`CONTEXT_SECTION_IDS`, labels in `CONTEXT_SECTION_LABELS`).

**Honesty about numbers.** A host that records no per-section counts gets estimates from the recorded text. A section whose text was never recorded says `not-recorded` and carries 0 tokens; it is never invented. When you supply exact counts in `recordedSections` (`{ id, tokens, source?, note? }`), the same view models flip each section's `source` to `recorded` and the attribution's `basis` to `recorded`, `mixed` or `estimated`, with no UI change. `windowSource` says where the window came from: `provider`, `capability`, `declared` (from `recordedWindow`) or `inferred` (the fallback you passed).

`contextFindings` reports four rules: `pressure` (a call at 80% of the window or more, critical from 95%), `duplicate-result` (the same tool result returned more than once), `dominant-result` (one tool result holding 40% or more of a call and at least about 1,000 tokens) and `clipped-prompt` (the host clipped the system prompt, so its share is a lower bound). Each finding has `id`, `rule`, `severity` (`info`, `warn`, `critical`), `callId`, `iteration` and `message`.

Chart geometry and wording are also headless, so a React or Vue host can draw its own: `donutSegments`, `barLayout`, `windowLineY`, `describeAttribution`, `describeTimeline`, `describePoint`, `rankedSections`. Thresholds are exported constants (`PRESSURE_WARN_AT`, `PRESSURE_CRITICAL_AT`, `DUPLICATE_MIN_TOKENS`, `DUPLICATE_WARN_TOKENS`, `DOMINANT_RESULT_SHARE`, `DOMINANT_RESULT_MIN_TOKENS`).

### Svelte blocks

All four ship from `@reactive-agents/svelte/components`. They own no data: you pass the ui-core output in. Every visible string is a `labels` prop (any subset of `ContextLabels`; defaults in `DEFAULT_CONTEXT_LABELS`; `fillLabel` replaces `{name}` placeholders).

| Component | Props | Hook |
|---|---|---|
| `ContextGauge` | `events` (framework events) or `pressure` (a ready reading, or `null` for the empty text; wins over `events`), `labels`, `class` | `data-ra-context-gauge` |
| `ContextChart` | `timeline`, `selectedId`, `onselect(callId)`, `legend` (default true), `legendSnippet`, `captionSnippet`, `labels`, `class` | `data-ra-context-chart`, `data-ra-bar`, `data-section`, `data-selected` |
| `ContextAttribution` | `attribution`, `ranked` (largest first), `header` (snippet), `tooltipEnabled` (boolean or getter), `labels`, `class` | `data-ra-context-attribution`, `data-section`, `data-source` |
| `ContextFindings` | `findings`, `onInspect(finding)` (omit to draw no action), `limit` (default 5; the rest sit behind a disclosure), `labels`, `class` | `data-ra-context-findings`, `data-severity`, `data-rule` |

- `ContextGauge` shows a percentage and a meter tinted at the two upper levels. With no `ContextPressure` event it falls back to iteration progress and says so.
- `ContextChart` draws stacked bars per main call against a dashed window line. Each bar is a button (Tab, then Enter or Space picks it; Left and Right move between bars) named by its iteration, tokens and largest section. `legendSnippet` receives the section ids present; `captionSnippet` receives the picked point.
- `ContextAttribution` draws a donut, a legend, a table and a badge (`recorded`, `partly estimated` or `estimated`). A not-recorded slice says so instead of showing 0.
- `ContextFindings` shows severity as a word, never colour alone.

None of the four relies on colour alone: the same numbers appear as text, in a legend, or in a table.

```svelte
<script lang="ts">
  import "@reactive-agents/svelte/styles.css";
  import {
    attributeContext,
    contextFindings,
    contextTimeline,
    contextWindowOf,
    type ContextCall,
    type ContextEventLike,
  } from "@reactive-agents/ui-core";
  import {
    ContextAttribution,
    ContextChart,
    ContextFindings,
    ContextGauge,
  } from "@reactive-agents/svelte/components";

  // events: the run's framework events; calls: your own mapping to ContextCall.
  const { events, calls }: { events: readonly ContextEventLike[]; calls: readonly ContextCall[] } = $props();

  let selected = $state<number | null>(null);
  const windowTokens = $derived(contextWindowOf(events));
  const timeline = $derived(contextTimeline(calls, windowTokens));
  const findings = $derived(contextFindings(calls, windowTokens));
  const picked = $derived(calls.find((c) => c.id === selected));
</script>

<ContextGauge {events} />
<ContextChart {timeline} selectedId={selected} onselect={(id) => (selected = id)} />
{#if picked}
  <ContextAttribution attribution={attributeContext(picked, windowTokens)} ranked />
{/if}
<ContextFindings {findings} onInspect={(f) => (selected = f.callId)} />
```

### Colours

The chart and donut colour each section with `--ra-ctx-<section>`: `--ra-ctx-system`, `--ra-ctx-guidance`, `--ra-ctx-skills`, `--ra-ctx-memory`, `--ra-ctx-tools`, `--ra-ctx-history`, `--ra-ctx-tool-results`, `--ra-ctx-model-turns` and `--ra-ctx-other`. `styles.css` defines a light set and a dark set. Override any of them on a parent element to match your brand. `CONTEXT_SERIES_VAR` and `contextSeriesColor(id)` give you the variable name or the `var(...)` string for your own drawing.

## Markdown (optional subpath)

`Markdown` lives apart from `/components` because it needs a parser and a sanitiser. `marked` and `dompurify` are optional peer dependencies of `@reactive-agents/svelte`, so apps that render no markdown install and bundle neither.

```bash
bun add marked dompurify
```

```svelte
<script lang="ts">
  import "@reactive-agents/svelte/styles.css";
  import { Markdown } from "@reactive-agents/svelte/markdown";

  const { answer }: { answer: string } = $props();
</script>

<Markdown markdown={answer} showCopy onCopy={({ kind, ok }) => console.log(kind, ok)} />
```

It needs a Svelte 5 toolchain (it ships `.svelte` sources) and a DOM at render time.

| Prop | Meaning |
|---|---|
| `markdown` | The source text (required) |
| `showCopy` | A button that copies the whole source. Default false |
| `codeCopy` | A copy button on each code block. Default true |
| `headingIds` | Give headings the ids `outlineOf` computes, so an outline can scroll to them. Default true |
| `math` | `(tex) => html`, renders `$$...$$` display math. Its output is trusted and not re-sanitised: pass only a renderer you trust, such as KaTeX, never one that echoes its input. Without it `$$` stays literal |
| `render` | Replace the whole markdown-to-HTML step. It must sanitise |
| `onrendered(root)` | Called after each render, for attribute and text touches |
| `onCopy({ kind, ok })` | Result of a copy (`code` or `source`), so you decide how to tell the user |
| `icons`, `labels`, `class` | Icon registry (id `copy`), reworded strings, extra class |

Beyond base markdown it adds callouts (`> [!NOTE]`), a language label on code blocks and heading ids. Hooks: `data-ra-markdown`, `data-ra-markdown-body`, `data-ra-code-copy`, `data-ra-markdown-copy`. Colours: `--ra-md-*`, all optional (they default to the `--ra-*` base).

The same subpath exports `renderMarkdown(markdown, { math?, parse?, purify? })` (an async string-to-safe-HTML function; pass `purify` to sanitise outside a browser), `sanitizeMarkdownHtml`, `installMarkdownHooks` and `decorateRendered`.

### Security policy

Model and user text is not trusted. Sanitising is always on in `Markdown`:

- No scripts, styles, frames, forms or images. Images are off because a remote image is a tracking beacon.
- `class`, `style` and `on*` attributes are dropped. The one class kept is the fence language marker on `<code>`.
- Links keep an `href` only for `http(s):`, `mailto:` and in-page `#anchors`. Anything else loses its `href`.
- External links open with `target="_blank"` and `rel="noopener noreferrer nofollow"`.
- The only `<input>` that survives is a disabled task-list checkbox.
- Raw HTML in the markdown is sanitised like everything else.
- On the server and on first paint the component shows the raw text, escaped. The sanitising render runs only in the browser, so the height does not jump. If rendering fails, the raw text stays.

The policy itself is plain data in `@reactive-agents/ui-core`, so another binding can enforce the same rules: `MARKDOWN_ALLOWED_TAGS`, `MARKDOWN_ALLOWED_ATTR`, `linkPolicy(href)`, `isCodeLanguageClass`, `splitMarkdownAndDisplayMath`.

## What's Next

- [Agentic UI Core](https://docs.reactiveagents.dev/features/agentic-ui-core.md): the protocol, run state and the other Svelte blocks
- [Drop-in UI Blocks](https://docs.reactiveagents.dev/features/agentic-ui-blocks.md): the input, list and card blocks
