Official
chat
Built-in chat UI (JavaScript UI plugin).
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/chat@0.2.6
Permissions in 0.2.6
Files
views/usage.tsx15.9 KB
// The account's usage limits and the chat's context window, under the prompt box.
import * as Effect from "effect/Effect";
import type { Element, Chat, AgentInfo, CanvasCommand, Color, PathStep, Usage } from "divergence";
import type { ChatView } from "../controller.ts";
import { column, row, clickable, HOVER, RAISED } from "./styles.tsx";
type Window = NonNullable<NonNullable<AgentInfo["usageLimits"]>["windows"]>[number];
// Whole numbers from 10% up, one decimal below: 0.4% is not 0%.
const percent = (value: number) => `${value >= 10 ? Math.round(value) : Math.round(value * 10) / 10}%`;
const tokens = (value: number | undefined) => (value === undefined ? "-" : Math.round(value).toLocaleString("en"));
const toneOf = (used: number, blocked = false) => (blocked || used >= 95 ? "danger" : used >= 80 ? "warning" : "muted");
/// "5h", "7d": the window's length, which is what tells the windows apart
/// at a glance.
export function shortLabel(window: Window): string {
const minutes = window.windowMinutes ?? 0;
return minutes < 24 * 60 ? `${Math.round(minutes / 60)}h` : `${Math.round(minutes / (24 * 60))}d`;
}
const RING = 14;
const RING_WIDTH = 2;
/// The draw list of a progress ring: a faint track and, clockwise from
/// twelve o'clock, an arc for `fraction` of it, in cubic segments of at
/// most a quarter turn. A `drain` ring's arc ends at twelve o'clock
/// instead, so it empties clockwise as the share left falls, the way a
/// limit's bar empties from the left. `mark` draws a solid tick across the
/// ring's line, as far inside it as outside, that share of a turn
/// clockwise from twelve o'clock, where the window's time has got to, so
/// an arc that starts past it is over pace. The tick reaches `MARK_REACH`
/// past the ring's box.
export function ringCommands(fraction: number, color: Color, { drain = false, mark = null }: { drain?: boolean; mark?: number | null } = {}): CanvasCommand[] {
const centre = RING / 2;
const radius = (RING - RING_WIDTH) / 2;
const point = (angle: number): [number, number] => [centre + radius * Math.cos(angle), centre + radius * Math.sin(angle)];
const arc = (from: number, to: number) => {
const d: PathStep[] = [["moveTo", ...point(from)]];
const steps = Math.max(1, Math.ceil((to - from) / (Math.PI / 2)));
const step = (to - from) / steps;
const k = (4 / 3) * Math.tan(step / 4) * radius;
for (let i = 0; i < steps; i++) {
const a = from + i * step;
const b = a + step;
d.push([
"cubicTo",
centre + radius * Math.cos(a) - k * Math.sin(a),
centre + radius * Math.sin(a) + k * Math.cos(a),
centre + radius * Math.cos(b) + k * Math.sin(b),
centre + radius * Math.sin(b) - k * Math.cos(b),
...point(b),
]);
}
return d;
};
const top = -Math.PI / 2;
const sweep = Math.min(1, Math.max(0, fraction)) * 2 * Math.PI;
const start = drain ? top + 2 * Math.PI - sweep : top;
const tick = (angle: number): PathStep[] => [
["moveTo", centre + (radius - MARK_HALF) * Math.cos(angle), centre + (radius - MARK_HALF) * Math.sin(angle)],
["lineTo", centre + (radius + MARK_HALF) * Math.cos(angle), centre + (radius + MARK_HALF) * Math.sin(angle)],
];
return [
{ op: "path" as const, d: arc(top, top + 2 * Math.PI), stroke: "mutedForeground/25", lineWidth: RING_WIDTH },
...(sweep > 0 ? [{ op: "path" as const, d: arc(start, start + sweep), stroke: color, lineWidth: RING_WIDTH }] : []),
...(mark === null ? [] : [{ op: "path" as const, d: tick(top + mark * 2 * Math.PI), stroke: RING_MARK_COLOR, lineWidth: 1.5 }]),
];
}
const MARK_COLOR: Color = "foreground/70";
const RING_MARK_COLOR: Color = "foreground";
// How far a ring's mark reaches either side of the ring's line, and so past
// the ring's box.
const MARK_HALF = 2.5;
const MARK_REACH = (RING - RING_WIDTH) / 2 + MARK_HALF - RING / 2;
/// A ring with a mark draws on a canvas grown by the mark's reach on every
/// side and pulled back by as much, so it takes the same room as one
/// without.
function ring(share: number, tone: "danger" | "warning" | "muted", mark: number | null = null): Element {
const commands = ringCommands(share / 100, tone === "muted" ? "mutedForeground" : tone, { drain: mark !== null, mark });
return mark === null
? <canvas width={RING} height={RING} commands={commands} />
: <canvas width={RING + 2 * MARK_REACH} height={RING + 2 * MARK_REACH} margin={-MARK_REACH} commands={[{ op: "translate", x: MARK_REACH, y: MARK_REACH }, ...commands]} />;
}
/// The windows shown beside the prompt: one per length the agent reports
/// (its 5-hour and its 7-day window), the first of each in the agent's
/// order, or a blocked one wherever it is. The rest are in the card. With
/// none of those (only a spend allowance, say) the first window stands in,
/// so the card stays one press away.
export function headlineWindows(windows: readonly Window[]): Window[] {
const lengths = new Set<number>();
const shown = windows.filter((window) => {
if (window.blocked) return true;
if (!window.windowMinutes || lengths.has(window.windowMinutes)) return false;
lengths.add(window.windowMinutes);
return true;
});
return shown.length ? shown : windows.slice(0, 1);
}
export function resetsIn(iso: string | undefined, now = Date.now()): string | null {
const at = iso ? Date.parse(iso) : Number.NaN;
return Number.isNaN(at) ? null : timeLeft(at - now);
}
/// "2h 15m", "2d 3h": a span of time, rounded up to the minute.
function timeLeft(ms: number): string {
const minutes = Math.ceil(ms / 60_000);
if (minutes <= 0) return "now";
const days = Math.floor(minutes / 1440);
const hours = Math.floor((minutes % 1440) / 60);
if (days) return hours ? `${days}d ${hours}h` : `${days}d`;
return hours ? (minutes % 60 ? `${hours}h ${minutes % 60}m` : `${hours}h`) : `${minutes}m`;
}
/// The share of the window gone by, from its length and its reset; none
/// for a window without both.
export function windowGone(window: Window, now = Date.now()): number | null {
const length = (window.windowMinutes ?? 0) * 60_000;
const reset = window.resetsAt ? Date.parse(window.resetsAt) : Number.NaN;
if (!length || Number.isNaN(reset)) return null;
return Math.min(1, Math.max(0, 1 - (reset - now) / length));
}
/// "the week", "the 5h window": what a window's time left is a share of.
function periodName(window: Window): string {
const minutes = window.windowMinutes;
return minutes === 7 * 1440 ? "the week" : minutes === 1440 ? "the day" : `the ${shortLabel(window)} window`;
}
const FILL = { muted: "mutedForeground", warning: "warning", danger: "danger" } as const;
/// A limit's bar: the share left fills it from the right, so it drains from
/// the left as the window is used, and a dashed line stands where the
/// window's time has got to. A fill that reaches left past the line has more
/// left than the time left; a line standing in the empty part is over pace.
function limitBar(left: number, gone: number | null, tone: "danger" | "warning" | "muted"): Element {
return (
<div {...row} justifyContent="end" position="relative" width="fill" height={4} borderRadius="full" background="muted">
<div width={`${Math.min(100, Math.max(0, left))}%`} height="fill" borderRadius="full" background={FILL[tone]} />
{gone === null
? null
: <div {...column} position="absolute" top={-3} left={`${gone * 100}%`} marginLeft={-0.75} gap={2}>{[0, 1, 2].map(() => <div width={1.5} height={2} background={MARK_COLOR} />)}</div>}
</div>
);
}
// A trigger that opens a card above the composer, the way the old
// tooltip did, but pressable so it works without hover.
function meter(v: ChatView, id: string, label: Element[], card: Element): Element {
const open = !!v.controller.state.wsPicker[id];
// The meter draws in its chat's composer view, which is not the view of the chat on screen when
// the chat is in another pane: that view is the one to draw again.
const set = (to: boolean) => {
v.controller.state.wsPicker[id] = to;
v.ctx.update();
};
return (
<popover id={id} open={open} align="end" width={260} onDismiss={() => set(false)}>
<div {...row} {...clickable} gap="small" padding="small" paddingX={6} paddingY={2} height={22} borderRadius={6} hover={HOVER} onPress={() => set(!open)}>{label}</div>
<div {...column} gap="medium" padding="medium" background="card/40" backdrop={{ blur: 6 }} borderRadius="md" {...RAISED}>{card}</div>
</popover>
);
}
export function limitRow(window: Window): Element {
const left = window.blocked ? 0 : Math.max(0, 100 - window.usedPercent);
const gone = windowGone(window);
const resets = resetsIn(window.resetsAt);
return (
<div {...column} gap={6}>
<div {...row} gap="small">
<text style="body" size="xs" weight={600}>{window.label}</text>
<spacer />
<text style="body" size="xs" tone={window.blocked ? "danger" : "muted"}>{window.blocked ? "Used up" : `${percent(left)} remaining`}</text>
</div>
{limitBar(left, gone, toneOf(window.usedPercent, window.blocked))}
<div {...row} gap="small">
{gone === null ? null : <text style="small" tone="muted">{`${percent((1 - gone) * 100)} of ${periodName(window)} left`}</text>}
<spacer />
{resets ? <text style="small" tone="muted">{`Resets in ${resets}`}</text> : null}
</div>
</div>
);
}
/// Why an agent that reports limits shows none yet.
export function limitsNote(agent: AgentInfo): string {
const note = agent.status?.state === "ready" ? "Usage limits not reported yet" : "Usage limits unavailable until the agent is ready";
return `${note}. They appear after the agent reports them.`;
}
/// Always drawn for an agent that reports limits: a dash with the reason
/// until the first report arrives.
/** `rings`: a footer too narrow for the meters' text shows their rings alone; the card still opens on a press. */
export function usageMeter(v: ChatView, chat: Chat, rings = false): Element | null {
const agent = v.controller.state.agents[chat.agentId];
if (!agent?.capabilities?.usageLimits) return null;
const windows = agent.usageLimits?.windows ?? [];
const id = `usage-${chat.id}`;
if (!windows.length) {
return meter(
v,
id,
rings ? [ring(0, "muted")] : [ring(0, "muted"), <text style="body" size="xs" tone="faint">{"—"}</text>],
<text style="body" size="xs" tone="muted">{limitsNote(agent)}</text>,
);
}
// Beside the prompt a window is its ring, which shows the share left
// with a tick where the card's bar has its dashed line, and its length:
// the share is a press away in the card, and a row of numbers under the prompt is noise
// while the chat runs. Windows are set apart from one another, so a 5h
// ring is never read as the 7d one's.
const headline = headlineWindows(windows);
const label = [
(
<div {...row} gap={headline.length > 1 ? 10 : 4}>
{headline.map(
(window) => (
<div {...row} gap={4}>
{ring(window.blocked ? 0 : 100 - window.usedPercent, toneOf(window.usedPercent, window.blocked), windowGone(window))}
{rings ? null : <text style="body" size="xs" weight={600} tone={toneOf(window.usedPercent, window.blocked)}>{window.windowMinutes ? shortLabel(window) : window.label}</text>}
</div>
),
)}
</div>
),
];
const card = (
<div {...column} gap="medium">
<div {...column} gap={2}>
<text style="small" tone="muted">Account usage</text>
<text style="body" weight={600}>{`${agent.name} limits`}</text>
</div>
{windows.map(limitRow)}
</div>
);
return meter(v, id, label, card);
}
/// The share of the context window in use, in percent.
export function contextUsed(usage: Usage): number {
return (Number(usage.usedTokens ?? 0) / Number(usage.contextWindow)) * 100;
}
/// The context window: tokens used of the window and the share, the bar,
/// what fills it when the agent says, what remains, where the agent
/// compacts on its own and the last request's breakdown. `caption` heads
/// it in the card under the prompt; the Session panel has a heading of its
/// own. `action` ends it.
export function contextDetails(usage: Usage, caption?: string, action?: Element | null): Element {
const used = contextUsed(usage);
const detail = (name: string, value: number | undefined, tone = "muted", inset = 0) =>
value === undefined
? null
: (
<div {...row} gap="small" paddingLeft={inset}>
<text style="small" tone={tone} truncate>{name}</text>
<spacer />
{inset
? <text style="small" tone="muted">{tokens(value)}</text>
: <text style="small" weight={600}>{tokens(value)}</text>}
</div>
);
const group = (rows: (Element | null)[], heading?: string) =>
rows.some(Boolean)
? <div {...column} gap={4}>{heading ? <text style="small" tone="muted">{heading}</text> : null}{rows}</div>
: null;
const categories = (usage.categories ?? []).flatMap((category) => [
detail(category.name, category.tokens),
...(category.parts ?? []).map((part) => detail(part.name, part.tokens, "faint", 10)),
]);
return (
<div {...column} gap="medium">
<div {...row} gap="small">
<div {...column} gap={2}>
{caption ? <text style="small" tone="muted">{caption}</text> : null}
<text style="body" weight={600}>{`${tokens(usage.usedTokens)} / ${tokens(usage.contextWindow)}`}</text>
</div>
<spacer />
<text style="body" weight={600}>{percent(used)}</text>
</div>
<progress value={Math.min(1, Math.max(0, used / 100))} tone={toneOf(used)} />
{group(categories)}
{group([
detail("Remaining", Math.max(0, (usage.contextWindow ?? 0) - (usage.usedTokens ?? 0))),
detail("Compacts automatically at", usage.autoCompactAt),
])}
{group(
[
detail("Input", usage.inputTokens),
detail("Cached input", usage.cachedInputTokens),
detail("Output", usage.outputTokens),
detail("Reasoning", usage.reasoningTokens),
usage.costUsd === undefined
? null
: (
<div {...row} gap="small">
<text style="small" tone="muted">Cost</text>
<spacer />
<text style="small" weight={600}>{`$${usage.costUsd.toFixed(4)}`}</text>
</div>
),
],
"Last request",
)}
{action ?? null}
</div>
);
}
export function contextMeter(v: ChatView, chat: Chat, rings = false): Element | null {
const usage = v.controller.state.transcripts[chat.id]?.usage;
if (!usage?.contextWindow) return null;
const used = contextUsed(usage);
const id = `context-${chat.id}`;
const compact = () => {
v.controller.state.wsPicker[id] = false;
v.ctx.update();
v.ctx.run(
v.controller.host
.call("host/chats.compact", { chatId: chat.id })
.pipe(Effect.catch((error) => v.controller.notify.error(`Compact failed: ${error.message}`))),
);
};
return meter(
v,
id,
// Like the usage windows: a ring and a name, with the share before it.
[
(
<div {...row} gap={4}>
{ring(used, toneOf(used))}
{rings ? null : <text style="body" size="xs" weight={600} tone={toneOf(used)}>{percent(used)}</text>}
{rings ? null : <text style="body" size="xs" weight={600} tone={toneOf(used)}>Ctx</text>}
</div>
),
],
contextDetails(
usage,
"Context",
v.controller.state.agents[chat.agentId]?.capabilities?.compact
? <button id={`compact-${chat.id}`} icon="fold-vertical" label="Compact" tooltip="Summarize the conversation to free context" onClick={compact} />
: null,
),
);
}Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.9latest | Nov 21, 2026 | >=5 <6 | 349 KB | 5 permissions | Listed |
| 0.2.8 | Nov 16, 2026 | >=5 <6 | 348.6 KB | 5 permissions | Listed |
| 0.2.7 | Nov 11, 2026 | >=5 <6 | 314.3 KB | 5 permissions | Listed |
| 0.2.6 | Nov 9, 2026 | >=5 <6 | 306.2 KB | 5 permissions | Listed |
| 0.2.5 | Oct 27, 2026 | >=2 <4 | 178.6 KB | 5 permissions | Listed |
No comments yet.